Commit graph

503 commits

Author SHA1 Message Date
Florian Weimer 7c241325d6 Force building with -fno-common
As a result, is not necessary to specify __attribute__ ((nocommon))
on individual definitions.

GCC 10 defaults to -fno-common on all architectures except ARC,
but this change is compatible with older GCC versions and ARC, too.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2021-07-09 20:09:14 +02:00
Florian Weimer 2dd87703d4 nptl: Move changing of stack permissions into ld.so
All the stack lists are now in _rtld_global, so it is possible
to change stack permissions directly from there, instead of
calling into libpthread to do the change.

Tested-by: Carlos O'Donell <carlos@redhat.com>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2021-05-10 10:31:41 +02:00
Florian Weimer d017b0ab5a elf: Introduce __tls_pre_init_tp
This is an early variant of __tls_init_tp, primarily for initializing
thread-related elements of _rtld_global/GL.

Some existing initialization code not needed for NPTL is moved into
the generic version of this function.

Tested-by: Carlos O'Donell <carlos@redhat.com>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2021-05-10 10:31:41 +02:00
Florian Weimer d6163dfd38 elf, nptl: Resolve recursive lock implementation early
If libpthread is included in libc, it is not necessary to delay
initialization of the lock/unlock function pointers until libpthread
is loaded.  This eliminates two unprotected function pointers
from _rtld_global and removes some initialization code from
libpthread.

Tested-by: Carlos O'Donell <carlos@redhat.com>
Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2021-05-10 10:31:41 +02:00
Florian Weimer 7cbf1c8416 elf, nptl: Initialize static TLS directly in ld.so
The stack list is available in ld.so since commit
1daccf403b ("nptl: Move stack list
variables into _rtld_global"), so it's possible to walk the stack
list directly in ld.so and perform the initialization there.

This eliminates an unprotected function pointer from _rtld_global
and reduces the libpthread initialization code.
2021-05-05 06:20:31 +02:00
Florian Weimer 90d7e7e5bd elf: Introduce __tls_init_tp for second-phase TCB initialization
TLS_INIT_TP is processor-specific, so it is not a good place to
put thread library initialization code (it would have to be repeated
for all CPUs).  Introduce __tls_init_tp as a separate function,
to be called immediately after TLS_INIT_TP.  Move the existing
stack list setup code for NPTL to this function.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2021-04-21 19:49:51 +02:00
Florian Weimer fada901819 dlfcn: dlerror needs to call free from the base namespace [BZ #24773]
Calling free directly may end up freeing a pointer allocated by the
dynamic loader using malloc from libc.so in the base namespace using
the allocator from libc.so in a secondary namespace, which results in
crashes.

This commit redirects the free call through GLRO and the dynamic
linker, to reach the correct namespace.  It also cleans up the dlerror
handling along the way, so that pthread_setspecific is no longer
needed (which avoids triggering bug 24774).
2021-04-21 19:49:51 +02:00
Florian Weimer b2964eb1d9 dlfcn: Failures after dlmopen should not terminate process [BZ #24772]
Commit 9e78f6f6e7 ("Implement
_dl_catch_error, _dl_signal_error in libc.so [BZ #16628]") has the
side effect that distinct namespaces, as created by dlmopen, now have
separate implementations of the rtld exception mechanism.  This means
that the call to _dl_catch_error from libdl in a secondary namespace
does not actually install an exception handler because the
thread-local variable catch_hook in the libc.so copy in the secondary
namespace is distinct from that of the base namepace.  As a result, a
dlsym/dlopen/... failure in a secondary namespace terminates the process
with a dynamic linker error because it looks to the exception handler
mechanism as if no handler has been installed.

This commit restores GLRO (dl_catch_error) and uses it to set the
handler in the base namespace.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2021-04-21 19:49:51 +02:00
Florian Weimer 851f32cf7b ld.so: Implement the --list-diagnostics option 2021-03-02 14:39:24 +01:00
H.J. Lu 86f65dffc2 ld.so: Add --list-tunables to print tunable values
Pass --list-tunables to ld.so to print tunables with min and max values.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2021-01-15 05:59:10 -08:00
Paul Eggert 2b778ceb40 Update copyright dates with scripts/update-copyrights
I used these shell commands:

../glibc/scripts/update-copyrights $PWD/../gnulib/build-aux/update-copyright
(cd ../glibc && git commit -am"[this commit message]")

and then ignored the output, which consisted lines saying "FOO: warning:
copyright statement not found" for each of 6694 files FOO.
I then removed trailing white space from benchtests/bench-pthread-locks.c
and iconvdata/tst-iconv-big5-hkscs-to-2ucs4.c, to work around this
diagnostic from Savannah:
remote: *** pre-commit check failed ...
remote: *** error: lines with trailing whitespace found
remote: error: hook declined to update refs/heads/master
2021-01-02 12:17:34 -08:00
Florian Weimer 4d0985543f elf: Record libc.so link map when it is the main program (bug 20972)
Otherwise, it will not participate in the dependency sorting.

Fixes commit 9ffa50b26b
("elf: Include libc.so.6 as main program in dependency sort
(bug 20972)").

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2020-12-15 20:56:04 +01:00
Szabolcs Nagy c00452d775 elf: Pass the fd to note processing
To handle GNU property notes on aarch64 some segments need to
be mmaped again, so the fd of the loaded ELF module is needed.

When the fd is not available (kernel loaded modules), then -1
is passed.

The fd is passed to both _dl_process_pt_gnu_property and
_dl_process_pt_note for consistency. Target specific note
processing functions are updated accordingly.

Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
2020-12-11 15:45:37 +00:00
Florian Weimer dad90d5282 elf: Add glibc-hwcaps support for LD_LIBRARY_PATH
This hacks non-power-set processing into _dl_important_hwcaps.
Once the legacy hwcaps handling goes away, the subdirectory
handling needs to be reworked, but it is premature to do this
while both approaches are still supported.

ld.so supports two new arguments, --glibc-hwcaps-prepend and
--glibc-hwcaps-mask.  Each accepts a colon-separated list of
glibc-hwcaps subdirectory names.  The prepend option adds additional
subdirectories that are searched first, in the specified order.  The
mask option restricts the automatically selected subdirectories to
those listed in the option argument.  For example, on systems where
/usr/lib64 is on the library search path,
--glibc-hwcaps-prepend=valgrind:debug causes the dynamic loader to
search the directories /usr/lib64/glibc-hwcaps/valgrind and
/usr/lib64/glibc-hwcaps/debug just before /usr/lib64 is searched.

Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
2020-12-04 09:13:43 +01:00
Florian Weimer 1daccf403b nptl: Move stack list variables into _rtld_global
Now __thread_gscope_wait (the function behind THREAD_GSCOPE_WAIT,
formerly __wait_lookup_done) can be implemented directly in ld.so,
eliminating the unprotected GL (dl_wait_lookup_done) function
pointer.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2020-11-16 19:33:30 +01:00
Rolf Eike Beer 7ee881f1f4 rtld: fix typo in comment 2020-10-13 05:49:58 -07:00
Florian Weimer 542923d949 elf: Implement ld.so --version
This prints out version information for the dynamic loader and
exits immediately, without further command line processing
(which seems to match what some GNU tools do).

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2020-10-08 15:33:00 +02:00
Florian Weimer e0f1a58f3d elf: Implement ld.so --help
--help processing is deferred to the point where the executable has
been loaded, so that it is possible to eventually include information
from the main executable in the help output.

As suggested in the GNU command-line interface guidelines, the help
message is printed to standard output, and the exit status is
successful.

Handle usage errors closer to the GNU command-line interface
guidelines.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2020-10-08 15:00:39 +02:00
Florian Weimer 27316f4a23 elf: Record whether paths come from LD_LIBRARY_PATH or --library-path
This allows more precise LD_DEBUG diagnostics.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2020-10-08 14:29:49 +02:00
Florian Weimer 9590a71adc elf: Move ld.so error/help output to _dl_usage
Also add a comment to elf/Makefile, explaining why we cannot use
config.status for autoconf template processing.

Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2020-10-08 13:38:23 +02:00
Florian Weimer 2bf9e641fd elf: Extract command-line/environment variables state from rtld.c
Introduce struct dl_main_state and move it to <dl-main.h>.  Rename
enum mode to enum rtld_mode and add the rtld_mode_ prefix to the enum
constants.

This avoids the need for putting state that is only needed during
startup into the ld.so data segment.
2020-10-08 12:05:47 +02:00
Vincent Mihalkovic c670278934 ld.so: add an --argv0 option [BZ #16124] 2020-09-29 12:34:40 +02:00
Szabolcs Nagy 17796419b5 rtld: Account static TLS surplus for audit modules
The new static TLS surplus size computation is

  surplus_tls = 192 * (nns-1) + 144 * nns + 512

where nns is controlled via the rtld.nns tunable. This commit
accounts audit modules too so nns = rtld.nns + audit modules.

rtld.nns should only include the namespaces required by the
application, namespaces for audit modules are accounted on top
of that so audit modules don't use up the static TLS that is
reserved for the application. This allows loading many audit
modules without tuning rtld.nns or using up static TLS, and it
fixes

FAIL: elf/tst-auditmany

Note that DL_NNS is currently a hard upper limit for nns, and
if rtld.nns + audit modules go over the limit that's a fatal
error. By default rtld.nns is 4 which allows 12 audit modules.

Counting the audit modules is based on existing audit string
parsing code, we cannot use GLRO(dl_naudit) before the modules
are actually loaded.
2020-07-08 17:32:56 +01:00
Szabolcs Nagy 0c7b002fac rtld: Add rtld.nns tunable for the number of supported namespaces
TLS_STATIC_SURPLUS is 1664 bytes currently which is not enough to
support DL_NNS (== 16) number of dynamic link namespaces, if we
assume 192 bytes of TLS are reserved for libc use and 144 bytes
are reserved for other system libraries that use IE TLS.

A new tunable is introduced to control the number of supported
namespaces and to adjust the surplus static TLS size as follows:

surplus_tls = 192 * (rtld.nns-1) + 144 * rtld.nns + 512

The default is rtld.nns == 4 and then the surplus TLS size is the
same as before, so the behaviour is unchanged by default. If an
application creates more namespaces than the rtld.nns setting
allows, then it is not guaranteed to work, but the limit is not
checked. So existing usage will continue to work, but in the
future if an application creates more than 4 dynamic link
namespaces then the tunable will need to be set.

In this patch DL_NNS is a fixed value and provides a maximum to
the rtld.nns setting.

Static linking used fixed 2048 bytes surplus TLS, this is changed
so the same contract is used as for dynamic linking.  With static
linking DL_NNS == 1 so rtld.nns tunable is forced to 1, so by
default the surplus TLS is reduced to 144 + 512 = 656 bytes. This
change is not expected to cause problems.

Tested on aarch64-linux-gnu and x86_64-linux-gnu.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2020-07-08 17:32:56 +01:00
Szabolcs Nagy c7aa8596de rtld: Clean up PT_NOTE and add PT_GNU_PROPERTY handling
Add generic code to handle PT_GNU_PROPERTY notes. Invalid
content is ignored, _dl_process_pt_gnu_property is always called
after PT_LOAD segments are mapped and it has no failure modes.
Currently only one NT_GNU_PROPERTY_TYPE_0 note is handled, which
contains target specific properties: the _dl_process_gnu_property
hook is called for each property.

The old _dl_process_pt_note and _rtld_process_pt_note differ in how
the program header is read.  The old _dl_process_pt_note is called
before PT_LOAD segments are mapped and _rtld_process_pt_note is called
after PT_LOAD segments are mapped. The old _rtld_process_pt_note is
removed and _dl_process_pt_note is always called after PT_LOAD
segments are mapped and now it has no failure modes.

The program headers are scanned backwards so that PT_NOTE can be
skipped if PT_GNU_PROPERTY exists.

Co-Authored-By: H.J. Lu <hjl.tools@gmail.com>
Reviewed-by: Adhemerval Zanella  <adhemerval.zanella@linaro.org>
2020-07-08 14:28:53 +01:00
H.J. Lu 674ea88294 x86: Move CET control to _dl_x86_feature_control [BZ #25887]
1. Include <dl-procruntime.c> to get architecture specific initializer in
rtld_global.
2. Change _dl_x86_feature_1[2] to _dl_x86_feature_1.
3. Add _dl_x86_feature_control after _dl_x86_feature_1, which is a
struct of 2 bitfields for IBT and SHSTK control

This fixes [BZ #25887].
2020-05-18 06:15:02 -07:00
Florian Weimer 03e187a41d elf: Add initial flag argument to __libc_early_init
The rseq initialization should happen only for the libc in the base
namespace (in the dynamic case) or the statically linked libc.  The
__libc_multiple_libcs flag does not quite cover this case at present,
so this commit introduces a flag argument to __libc_early_init,
indicating whether the libc being libc is the primary one (of the main
program).

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2020-04-29 15:44:03 +02:00
Florian Weimer ec935dea63 elf: Implement __libc_early_init
This function is defined in libc.so, and the dynamic loader calls
right after relocation has been finished, before any ELF constructors
or the preinit function is invoked.  It is also used in the static
build for initializing parts of the static libc.

To locate __libc_early_init, a direct symbol lookup function is used,
_dl_lookup_direct.  It does not search the entire symbol scope and
consults merely a single link map.  This function could also be used
to implement lookups in the vDSO (as an optimization).

A per-namespace variable (libc_map) is added for locating libc.so,
to avoid repeated traversals of the search scope.  It is similar to
GL(dl_initfirst).  An alternative would have been to thread a context
argument from _dl_open down to _dl_map_object_from_fd (where libc.so
is identified).  This could have avoided the global variable, but
the change would be larger as a result.  It would not have been
possible to use this to replace GL(dl_initfirst) because that global
variable is used to pass the function pointer past the stack switch
from dl_main to the main program.  Replacing that requires adding
a new argument to _dl_init, which in turn needs changes to the
architecture-specific libc.so startup code written in assembler.

__libc_early_init should not be used to replace _dl_var_init (as
it exists today on some architectures).  Instead, _dl_lookup_direct
should be used to look up a new variable symbol in libc.so, and
that should then be initialized from the dynamic loader, immediately
after the object has been loaded in _dl_map_object_from_fd (before
relocation is run).  This way, more IFUNC resolvers which depend on
these variables will work.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2020-04-24 22:32:09 +02:00
Florian Weimer 8f7a75d700 elf: Implement DT_AUDIT, DT_DEPAUDIT support [BZ #24943]
binutils ld has supported --audit, --depaudit for a long time,
only support in glibc has been missing.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2020-04-03 16:26:10 +02:00
Florian Weimer 4c6e0415ef elf: Simplify handling of lists of audit strings
All list elements are colon-separated strings, and there is a hard
upper limit for the number of audit modules, so it is possible to
pre-allocate a fixed-size array of strings to which the LD_AUDIT
environment variable and --audit arguments are added.

Also eliminate the global variables for the audit list because
the list is only needed briefly during startup.

There is a slight behavior change: All duplicate LD_AUDIT environment
variables are now processed, not just the last one as before.  However,
such environment vectors are invalid anyway.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2020-04-03 16:26:10 +02:00
Florian Weimer 3a0ecccb59 ld.so: Do not export free/calloc/malloc/realloc functions [BZ #25486]
Exporting functions and relying on symbol interposition from libc.so
makes the choice of implementation dependent on DT_NEEDED order, which
is not what some compiler drivers expect.

This commit replaces one magic mechanism (symbol interposition) with
another one (preprocessor-/compiler-based redirection).  This makes
the hand-over from the minimal malloc to the full malloc more
explicit.

Removing the ABI symbols is backwards-compatible because libc.so is
always in scope, and the dynamic loader will find the malloc-related
symbols there since commit f0b2132b35
("ld.so: Support moving versioned symbols between sonames
[BZ #24741]").

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2020-02-15 11:01:23 +01:00
Adhemerval Zanella 1bdda52fe9 elf: Move vDSO setup to rtld (BZ#24967)
This patch moves the vDSO setup from libc to loader code, just after
the vDSO link_map setup.  For static case the initialization
is moved to _dl_non_dynamic_init instead.

Instead of using the mangled pointer, the vDSO data is set as
attribute_relro (on _rtld_global_ro for shared or _dl_vdso_* for
static).  It is read-only even with partial relro.

It fixes BZ#24967 now that the vDSO pointer is setup earlier than
malloc interposition is called.

Also, vDSO calls should not be a problem for static dlopen as
indicated by BZ#20802.  The vDSO pointer would be zero-initialized
and the syscall will be issued instead.

Checked on x86_64-linux-gnu, i686-linux-gnu, aarch64-linux-gnu,
arm-linux-gnueabihf, powerpc64le-linux-gnu, powerpc64-linux-gnu,
powerpc-linux-gnu, s390x-linux-gnu, sparc64-linux-gnu, and
sparcv9-linux-gnu.  I also run some tests on mips.

Reviewed-by: Siddhesh Poyarekar <siddhesh@sourceware.org>
2020-01-03 11:22:07 -03:00
Joseph Myers d614a75396 Update copyright dates with scripts/update-copyrights. 2020-01-01 00:14:33 +00:00
Florian Weimer a509eb117f Avoid late dlopen failure due to scope, TLS slotinfo updates [BZ #25112]
This change splits the scope and TLS slotinfo updates in dlopen into
two parts: one to resize the data structures, and one to actually apply
the update.  The call to add_to_global_resize in dl_open_worker is moved
before the demarcation point at which no further memory allocations are
allowed.

_dl_add_to_slotinfo is adjusted to make the list update optional.  There
is some optimization possibility here because we could grow the slotinfo
list of arrays in a single call, one the largest TLS modid is known.

This commit does not fix the fatal meory allocation failure in
_dl_update_slotinfo.  Ideally, this error during dlopen should be
recoverable.

The update order of scopes and TLS data structures is retained, although
it appears to be more correct to fully initialize TLS first, and then
expose symbols in the newly loaded objects via the scope update.

Tested on x86_64-linux-gnu.

Change-Id: I240c58387dabda3ca1bcab48b02115175fa83d6c
2019-11-27 20:55:35 +01:00
Florian Weimer e1d559f337 Introduce link_map_audit_state accessor function
To improve GCC 10 compatibility, it is necessary to remove the l_audit
zero-length array from the end of struct link_map.  In preparation of
that, this commit introduces an accessor function for the audit state,
so that it is possible to change the representation of the audit state
without adjusting the code that accesses it.

Tested on x86_64-linux-gnu.  Built on i686-gnu.

Change-Id: Id815673c29950fc011ae5301d7cde12624f658df
2019-11-15 13:03:40 +01:00
Florian Weimer c7bf5ceab6 Properly initialize audit cookie for the dynamic loader [BZ #25157]
The l_audit array is indexed by audit module, not audit function.

Change-Id: I180eb3573dc1c57433750f5d8cb18271460ba5f2
2019-11-15 13:03:32 +01:00
Paul Eggert 5a82c74822 Prefer https to http for gnu.org and fsf.org URLs
Also, change sources.redhat.com to sourceware.org.
This patch was automatically generated by running the following shell
script, which uses GNU sed, and which avoids modifying files imported
from upstream:

sed -ri '
  s,(http|ftp)(://(.*\.)?(gnu|fsf|sourceware)\.org($|[^.]|\.[^a-z])),https\2,g
  s,(http|ftp)(://(.*\.)?)sources\.redhat\.com($|[^.]|\.[^a-z]),https\2sourceware.org\4,g
' \
  $(find $(git ls-files) -prune -type f \
      ! -name '*.po' \
      ! -name 'ChangeLog*' \
      ! -path COPYING ! -path COPYING.LIB \
      ! -path manual/fdl-1.3.texi ! -path manual/lgpl-2.1.texi \
      ! -path manual/texinfo.tex ! -path scripts/config.guess \
      ! -path scripts/config.sub ! -path scripts/install-sh \
      ! -path scripts/mkinstalldirs ! -path scripts/move-if-change \
      ! -path INSTALL ! -path  locale/programs/charmap-kw.h \
      ! -path po/libc.pot ! -path sysdeps/gnu/errlist.c \
      ! '(' -name configure \
            -execdir test -f configure.ac -o -f configure.in ';' ')' \
      ! '(' -name preconfigure \
            -execdir test -f preconfigure.ac ';' ')' \
      -print)

and then by running 'make dist-prepare' to regenerate files built
from the altered files, and then executing the following to cleanup:

  chmod a+x sysdeps/unix/sysv/linux/riscv/configure
  # Omit irrelevant whitespace and comment-only changes,
  # perhaps from a slightly-different Autoconf version.
  git checkout -f \
    sysdeps/csky/configure \
    sysdeps/hppa/configure \
    sysdeps/riscv/configure \
    sysdeps/unix/sysv/linux/csky/configure
  # Omit changes that caused a pre-commit check to fail like this:
  # remote: *** error: sysdeps/powerpc/powerpc64/ppc-mcount.S: trailing lines
  git checkout -f \
    sysdeps/powerpc/powerpc64/ppc-mcount.S \
    sysdeps/unix/sysv/linux/s390/s390-64/syscall.S
  # Omit change that caused a pre-commit check to fail like this:
  # remote: *** error: sysdeps/sparc/sparc64/multiarch/memcpy-ultra3.S: last line does not end in newline
  git checkout -f sysdeps/sparc/sparc64/multiarch/memcpy-ultra3.S
2019-09-07 02:43:31 -07:00
Adhemerval Zanella 1e372ded4f Refactor hp-timing rtld usage
This patch refactor how hp-timing is used on loader code for statistics
report.  The HP_TIMING_AVAIL and HP_SMALL_TIMING_AVAIL are removed and
HP_TIMING_INLINE is used instead to check for hp-timing avaliability.
For alpha, which only defines HP_SMALL_TIMING_AVAIL, the HP_TIMING_INLINE
is set iff for IS_IN(rtld).

Checked on aarch64-linux-gnu, x86_64-linux-gnu, and i686-linux-gnu. I also
checked the builds for all afected ABIs.

	* benchtests/bench-timing.h: Replace HP_TIMING_AVAIL with
	HP_TIMING_INLINE.
	* nptl/descr.h: Likewise.
	* elf/rtld.c (RLTD_TIMING_DECLARE, RTLD_TIMING_NOW, RTLD_TIMING_DIFF,
	RTLD_TIMING_ACCUM_NT, RTLD_TIMING_SET): Define.
	(dl_start_final_info, _dl_start_final, dl_main, print_statistics):
	Abstract hp-timing usage with RTLD_* macros.
	* sysdeps/alpha/hp-timing.h (HP_TIMING_INLINE): Define iff IS_IN(rtld).
	(HP_TIMING_AVAIL, HP_SMALL_TIMING_AVAIL): Remove.
	* sysdeps/generic/hp-timing.h (HP_TIMING_AVAIL, HP_SMALL_TIMING_AVAIL,
	HP_TIMING_NONAVAIL): Likewise.
	* sysdeps/ia64/hp-timing.h (HP_TIMING_AVAIL, HP_SMALL_TIMING_AVAIL):
	Likewise.
	* sysdeps/powerpc/powerpc32/power4/hp-timing.h (HP_TIMING_AVAIL,
	HP_SMALL_TIMING_AVAIL): Likewise.
	* sysdeps/powerpc/powerpc64/hp-timing.h (HP_TIMING_AVAIL,
	HP_SMALL_TIMING_AVAIL): Likewise.
	* sysdeps/sparc/sparc32/sparcv9/hp-timing.h (HP_TIMING_AVAIL,
	HP_SMALL_TIMING_AVAIL): Likewise.
	* sysdeps/sparc/sparc64/hp-timing.h (HP_TIMING_AVAIL,
	HP_SMALL_TIMING_AVAIL): Likewise.
	* sysdeps/x86/hp-timing.h (HP_TIMING_AVAIL, HP_SMALL_TIMING_AVAIL):
	Likewise.
	* sysdeps/generic/hp-timing-common.h: Update comment with
	HP_TIMING_AVAIL removal.
2019-03-22 17:30:44 -03:00
Adhemerval Zanella 38cc11daa4 nptl: Remove pthread_clock_gettime pthread_clock_settime
This patch removes CLOCK_THREAD_CPUTIME_ID and CLOCK_PROCESS_CPUTIME_ID support
from clock_gettime and clock_settime generic implementation.  For Linux, kernel
already provides supports through the syscall and Hurd HTL lacks
__pthread_clock_gettime and __pthread_clock_settime internal implementation.

As described in clock_gettime man-page [1] on 'Historical note for SMP
system', implementing CLOCK_{THREAD,PROCESS}_CPUTIME_ID with timer registers
is error-prone and susceptible to timing and accurary issues that the libc
can not deal without kernel support.

This allows removes unused code which, however, still incur in some runtime
overhead in thread creation (the struct pthread cpuclock_offset
initialization).

If hurd eventually wants to support them it should either either implement as
a kernel facility (or something related due its architecture) or in system
specific implementation.

Checked on aarch64-linux-gnu, x86_64-linux-gnu, and i686-linux-gnu. I also
checked on a i686-gnu build.

	* nptl/Makefile (libpthread-routines): Remove pthread_clock_gettime and
	pthread_clock_settime.
	* nptl/pthreadP.h (__find_thread_by_id): Remove prototype.
	* elf/dl-support.c [!HP_TIMING_NOAVAIL] (_dl_cpuclock_offset): Remove.
	(_dl_non_dynamic_init): Remove _dl_cpuclock_offset setting.
	* elf/rtld.c (_dl_start_final): Likewise.
	* nptl/allocatestack.c (__find_thread_by_id): Remove function.
	* sysdeps/generic/ldsodefs.h [!HP_TIMING_NOAVAIL] (_dl_cpuclock_offset):
	Remove.
	* sysdeps/mach/hurd/dl-sysdep.c [!HP_TIMING_NOAVAIL]
	(_dl_cpuclock_offset): Remove.
	* nptl/descr.h (struct pthread): Rename cpuclock_offset to
	cpuclock_offset_ununsed.
	* nptl/nptl-init.c (__pthread_initialize_minimal_internal): Remove
	cpuclock_offset set.
	* nptl/pthread_create.c (START_THREAD_DEFN): Likewise.
	* sysdeps/nptl/fork.c (__libc_fork): Likewise.
	* nptl/pthread_clock_gettime.c: Remove file.
	* nptl/pthread_clock_settime.c: Likewise.
	* sysdeps/unix/clock_gettime.c (hp_timing_gettime): Remove function.
	[HP_TIMING_AVAIL] (realtime_gettime): Remove CLOCK_THREAD_CPUTIME_ID
	and CLOCK_PROCESS_CPUTIME_ID support.
	* sysdeps/unix/clock_settime.c (hp_timing_gettime): Likewise.
	[HP_TIMING_AVAIL] (realtime_gettime): Likewise.
	* sysdeps/posix/clock_getres.c (hp_timing_getres): Likewise.
	[HP_TIMING_AVAIL] (__clock_getres): Likewise.
	* sysdeps/unix/clock_nanosleep.c (CPUCLOCK_P, INVALID_CLOCK_P):
	Likewise.
	(__clock_nanosleep): Remove CPUCLOCK_P and INVALID_CLOCK_P usage.

[1] http://man7.org/linux/man-pages/man2/clock_gettime.2.html
2019-03-22 15:37:43 -03:00
Joseph Myers 34a5a1460e Break some lines before not after operators.
The GNU Coding Standards specify that line breaks in expressions
should go before an operator, not after one.  This patch fixes various
code to do this.  It only changes code that appears to be mostly
following GNU style anyway, not files and directories with
substantially different formatting.  It is not exhaustive even for
files using GNU style (for example, changes to sysdeps files are
deferred for subsequent cleanups).  Some files changed are shared with
gnulib, but most are specific to glibc.  Changes were made manually,
with places to change found by grep (so some cases, e.g. where the
operator was followed by a comment at end of line, are particularly
liable to have been missed by grep, but I did include cases where the
operator was followed by backslash-newline).

This patch generally does not attempt to address other coding style
issues in the expressions changed (for example, missing spaces before
'(', or lack of parentheses to ensure indentation of continuation
lines properly reflects operator precedence).

Tested for x86_64, and with build-many-glibcs.py.

	* benchtests/bench-memmem.c (simple_memmem): Break lines before
	rather than after operators.
	* benchtests/bench-skeleton.c (TIMESPEC_AFTER): Likewise.
	* crypt/md5.c (md5_finish_ctx): Likewise.
	* crypt/sha256.c (__sha256_finish_ctx): Likewise.
	* crypt/sha512.c (__sha512_finish_ctx): Likewise.
	* elf/cache.c (load_aux_cache): Likewise.
	* elf/dl-load.c (open_verify): Likewise.
	* elf/get-dynamic-info.h (elf_get_dynamic_info): Likewise.
	* elf/readelflib.c (process_elf_file): Likewise.
	* elf/rtld.c (dl_main): Likewise.
	* elf/sprof.c (generate_call_graph): Likewise.
	* hurd/ctty-input.c (_hurd_ctty_input): Likewise.
	* hurd/ctty-output.c (_hurd_ctty_output): Likewise.
	* hurd/dtable.c (reauth_dtable): Likewise.
	* hurd/getdport.c (__getdport): Likewise.
	* hurd/hurd/signal.h (_hurd_interrupted_rpc_timeout): Likewise.
	* hurd/hurd/sigpreempt.h (HURD_PREEMPT_SIGNAL_P): Likewise.
	* hurd/hurdfault.c (_hurdsig_fault_catch_exception_raise):
	Likewise.
	* hurd/hurdioctl.c (fioctl): Likewise.
	* hurd/hurdselect.c (_hurd_select): Likewise.
	* hurd/hurdsig.c (_hurdsig_abort_rpcs): Likewise.
	(STOPSIGS): Likewise.
	* hurd/hurdstartup.c (_hurd_startup): Likewise.
	* hurd/intr-msg.c (_hurd_intr_rpc_mach_msg): Likewise.
	* hurd/lookup-retry.c (__hurd_file_name_lookup_retry): Likewise.
	* hurd/msgportdemux.c (msgport_server): Likewise.
	* hurd/setauth.c (_hurd_setauth): Likewise.
	* include/features.h (__GLIBC_USE_DEPRECATED_SCANF): Likewise.
	* libio/libioP.h [IO_DEBUG] (CHECK_FILE): Likewise.
	* locale/programs/ld-ctype.c (set_class_defaults): Likewise.
	* localedata/tests-mbwc/tst_swscanf.c (tst_swscanf): Likewise.
	* login/tst-utmp.c (do_check): Likewise.
	(simulate_login): Likewise.
	* mach/lowlevellock.h (lll_lock): Likewise.
	(lll_trylock): Likewise.
	* math/test-fenv.c (ALL_EXC): Likewise.
	* math/test-fenvinline.c (ALL_EXC): Likewise.
	* misc/sys/cdefs.h (__attribute_deprecated_msg__): Likewise.
	* nis/nis_call.c (__do_niscall3): Likewise.
	* nis/nis_callback.c (cb_prog_1): Likewise.
	* nis/nis_defaults.c (searchaccess): Likewise.
	* nis/nis_findserv.c (__nis_findfastest_with_timeout): Likewise.
	* nis/nis_ismember.c (internal_ismember): Likewise.
	* nis/nis_local_names.c (nis_local_principal): Likewise.
	* nis/nss_nis/nis-rpc.c (_nss_nis_getrpcbyname_r): Likewise.
	* nis/nss_nisplus/nisplus-netgrp.c (_nss_nisplus_getnetgrent_r):
	Likewise.
	* nis/ypclnt.c (yp_match): Likewise.
	(yp_first): Likewise.
	(yp_next): Likewise.
	(yp_master): Likewise.
	(yp_order): Likewise.
	* nscd/hstcache.c (cache_addhst): Likewise.
	* nscd/initgrcache.c (addinitgroupsX): Likewise.
	* nss/nss_compat/compat-pwd.c (copy_pwd_changes): Likewise.
	(internal_getpwuid_r): Likewise.
	* nss/nss_compat/compat-spwd.c (copy_spwd_changes): Likewise.
	* posix/glob.h (__GLOB_FLAGS): Likewise.
	* posix/regcomp.c (peek_token): Likewise.
	(peek_token_bracket): Likewise.
	(parse_expression): Likewise.
	* posix/regexec.c (sift_states_iter_mb): Likewise.
	(check_node_accept_bytes): Likewise.
	* posix/tst-spawn3.c (do_test): Likewise.
	* posix/wordexp-test.c (testit): Likewise.
	* posix/wordexp.c (parse_tilde): Likewise.
	(exec_comm): Likewise.
	* posix/wordexp.h (__WRDE_FLAGS): Likewise.
	* resource/vtimes.c (TIMEVAL_TO_VTIMES): Likewise.
	* setjmp/sigjmp.c (__sigjmp_save): Likewise.
	* stdio-common/printf_fp.c (__printf_fp_l): Likewise.
	* stdio-common/tst-fileno.c (do_test): Likewise.
	* stdio-common/vfprintf-internal.c (vfprintf): Likewise.
	* stdlib/strfmon_l.c (__vstrfmon_l_internal): Likewise.
	* stdlib/strtod_l.c (round_and_return): Likewise.
	(____STRTOF_INTERNAL): Likewise.
	* stdlib/tst-strfrom.h (TEST_STRFROM): Likewise.
	* string/strcspn.c (STRCSPN): Likewise.
	* string/test-memmem.c (simple_memmem): Likewise.
	* termios/tcsetattr.c (tcsetattr): Likewise.
	* time/alt_digit.c (_nl_parse_alt_digit): Likewise.
	* time/asctime.c (asctime_internal): Likewise.
	* time/strptime_l.c (__strptime_internal): Likewise.
	* time/sys/time.h (timercmp): Likewise.
	* time/tzfile.c (__tzfile_compute): Likewise.
2019-02-22 01:32:36 +00:00
Florian Weimer 3b856d093f elf: Ignore LD_AUDIT interfaces if la_version returns 0 [BZ #24122]
This change moves the audit module loading and early notification into
separate functions out of dl_main.

It restores the bug fix from commit
8e889c5da3  ("elf: Fix LD_AUDIT for
modules with invalid version (BZ#24122)") which was reverted in commit
83e6b59625  ("[elf] Revert 8e889c5da3
(BZ#24122)").

The actual bug fix is the separate error message for the case when
la_version returns zero.  The dynamic linker error message (which is
NULL in this case) is no longer used.  Based on the intended use of
version zero (ignore this module due to explicit request), the message
is only printed if debugging is enabled.
2019-02-12 13:36:56 +01:00
Joseph Myers 32db86d558 Add fall-through comments.
This patch adds fall-through comments in some cases where -Wextra
produces implicit-fallthrough warnings.

The patch is non-exhaustive.  Apart from architecture-specific code
for non-x86_64 architectures, it does not change sunrpc/xdr.c (legacy
code, probably should have such changes, but left to be dealt with
separately), or places that already had comments about the
fall-through but not matching the form expected by
-Wimplicit-fallthrough=3 (the default level with -Wextra; my
inclination is to adjust those comments to match rather than
downgrading to -Wimplicit-fallthrough=1 to allow any comment), or one
place where I thought the implicit fallthrough was not correct and so
should be handled separately as a bug fix.  I think the key thing to
consider in review of this patch is whether the fall-through is indeed
intended and correct in each place where such a comment is added.

Tested for x86_64.

	* elf/dl-exception.c (_dl_exception_create_format): Add
	fall-through comments.
	* elf/ldconfig.c (parse_conf_include): Likewise.
	* elf/rtld.c (print_statistics): Likewise.
	* locale/programs/charmap.c (parse_charmap): Likewise.
	* misc/mntent_r.c (__getmntent_r): Likewise.
	* posix/wordexp.c (parse_arith): Likewise.
	(parse_backtick): Likewise.
	* resolv/ns_ttl.c (ns_parse_ttl): Likewise.
	* sysdeps/x86/cpu-features.c (init_cpu_features): Likewise.
	* sysdeps/x86_64/dl-machine.h (elf_machine_rela): Likewise.
2019-02-12 10:30:34 +00:00
David Newall 8692ebdb12 elf: Implement --preload option for the dynamic linker 2019-02-04 13:35:12 +01:00
Adhemerval Zanella 83e6b59625 [elf] Revert 8e889c5da3 (BZ#24122)
It triggers an invalid build issue on GCC8+ and does not covers all
corner cases.
2019-01-25 08:10:15 -02:00
Adhemerval Zanella 8e889c5da3 elf: Fix LD_AUDIT for modules with invalid version (BZ#24122)
The error handling patch for invalid audit modules version access
invalid memory:

elf/rtld.c:

1454               unsigned int (*laversion) (unsigned int);
1455               unsigned int lav;
1456               if  (err_str == NULL
1457                    && (laversion = largs.result) != NULL
1458                    && (lav = laversion (LAV_CURRENT)) > 0
1459                    && lav <= LAV_CURRENT)
1460                 {
[...]
1526               else
1527                 {
1528                   /* We cannot use the DSO, it does not have the
1529                      appropriate interfaces or it expects something
1530                      more recent.  */
1531 #ifndef NDEBUG
1532                   Lmid_t ns = dlmargs.map->l_ns;
1533 #endif
1534                   _dl_close (dlmargs.map);
1535
1536                   /* Make sure the namespace has been cleared entirely.  */
1537                   assert (GL(dl_ns)[ns]._ns_loaded == NULL);
1538                   assert (GL(dl_ns)[ns]._ns_nloaded == 0);
1539
1540                   GL(dl_tls_max_dtv_idx) = tls_idx;
1541                   goto not_loaded;
1542                 }

1431           const char *err_str = NULL;
1432           bool malloced;
1433           (void) _dl_catch_error (&objname, &err_str, &malloced, dlmopen_doit,
1434                                   &dlmargs);
1435           if (__glibc_unlikely (err_str != NULL))
1436             {
1437             not_loaded:
1438               _dl_error_printf ("\
1439 ERROR: ld.so: object '%s' cannot be loaded as audit interface: %s; ignored.\n",
1440                                 name, err_str);
1441               if (malloced)
1442                 free ((char *) err_str);
1443             }

On failure the err_str will be NULL and _dl_debug_vdprintf does not handle
it properly:

elf/dl-misc.c:
200             case 's':
201               /* Get the string argument.  */
202               iov[niov].iov_base = va_arg (arg, char *);
203               iov[niov].iov_len = strlen (iov[niov].iov_base);
204               if (prec != -1)
205                 iov[niov].iov_len = MIN ((size_t) prec, iov[niov].iov_len);
206               ++niov;
207               break;

This patch fixes the issues and improves the error message.

Checked on x86_64-linux-gnu and i686-linux-gnu

	[BZ #24122]
	* elf/Makefile (tests): Add tst-audit13.
	(modules-names): Add tst-audit13mod1.
	(tst-audit13.out, LDFLAGS-tst-audit13mod1.so, tst-audit13-ENV): New
	rule.
	* elf/rtld.c (dl_main): Handle invalid audit module version.
	* elf/tst-audit13.c: New file.
	* elf/tst-audit13mod1.c: Likewise.

Reviewed-by: Carlos O'Donell <carlos@redhat.com>
2019-01-24 09:38:43 -02:00
Joseph Myers 04277e02d7 Update copyright dates with scripts/update-copyrights.
* All files with FSF copyright notices: Update copyright dates
	using scripts/update-copyrights.
	* locale/programs/charmap-kw.h: Regenerated.
	* locale/programs/locfile-kw.h: Likewise.
2019-01-01 00:11:28 +00:00
H.J. Lu f753fa7dea x86: Support IBT and SHSTK in Intel CET [BZ #21598]
Intel Control-flow Enforcement Technology (CET) instructions:

https://software.intel.com/sites/default/files/managed/4d/2a/control-flow-en
forcement-technology-preview.pdf

includes Indirect Branch Tracking (IBT) and Shadow Stack (SHSTK).

GNU_PROPERTY_X86_FEATURE_1_IBT is added to GNU program property to
indicate that all executable sections are compatible with IBT when
ENDBR instruction starts each valid target where an indirect branch
instruction can land.  Linker sets GNU_PROPERTY_X86_FEATURE_1_IBT on
output only if it is set on all relocatable inputs.

On an IBT capable processor, the following steps should be taken:

1. When loading an executable without an interpreter, enable IBT and
lock IBT if GNU_PROPERTY_X86_FEATURE_1_IBT is set on the executable.
2. When loading an executable with an interpreter, enable IBT if
GNU_PROPERTY_X86_FEATURE_1_IBT is set on the interpreter.
  a. If GNU_PROPERTY_X86_FEATURE_1_IBT isn't set on the executable,
     disable IBT.
  b. Lock IBT.
3. If IBT is enabled, when loading a shared object without
GNU_PROPERTY_X86_FEATURE_1_IBT:
  a. If legacy interwork is allowed, then mark all pages in executable
     PT_LOAD segments in legacy code page bitmap.  Failure of legacy code
     page bitmap allocation causes an error.
  b. If legacy interwork isn't allowed, it causes an error.

GNU_PROPERTY_X86_FEATURE_1_SHSTK is added to GNU program property to
indicate that all executable sections are compatible with SHSTK where
return address popped from shadow stack always matches return address
popped from normal stack.  Linker sets GNU_PROPERTY_X86_FEATURE_1_SHSTK
on output only if it is set on all relocatable inputs.

On a SHSTK capable processor, the following steps should be taken:

1. When loading an executable without an interpreter, enable SHSTK if
GNU_PROPERTY_X86_FEATURE_1_SHSTK is set on the executable.
2. When loading an executable with an interpreter, enable SHSTK if
GNU_PROPERTY_X86_FEATURE_1_SHSTK is set on interpreter.
  a. If GNU_PROPERTY_X86_FEATURE_1_SHSTK isn't set on the executable
     or any shared objects loaded via the DT_NEEDED tag, disable SHSTK.
  b. Otherwise lock SHSTK.
3. After SHSTK is enabled, it is an error to load a shared object
without GNU_PROPERTY_X86_FEATURE_1_SHSTK.

To enable CET support in glibc, --enable-cet is required to configure
glibc.  When CET is enabled, both compiler and assembler must support
CET.  Otherwise, it is a configure-time error.

To support CET run-time control,

1. _dl_x86_feature_1 is added to the writable ld.so namespace to indicate
if IBT or SHSTK are enabled at run-time.  It should be initialized by
init_cpu_features.
2. For dynamic executables:
   a. A l_cet field is added to struct link_map to indicate if IBT or
      SHSTK is enabled in an ELF module.  _dl_process_pt_note or
      _rtld_process_pt_note is called to process PT_NOTE segment for
      GNU program property and set l_cet.
   b. _dl_open_check is added to check IBT and SHSTK compatibilty when
      dlopening a shared object.
3. Replace i386 _dl_runtime_resolve and _dl_runtime_profile with
_dl_runtime_resolve_shstk and _dl_runtime_profile_shstk, respectively if
SHSTK is enabled.

CET run-time control can be changed via GLIBC_TUNABLES with

$ export GLIBC_TUNABLES=glibc.tune.x86_shstk=[permissive|on|off]
$ export GLIBC_TUNABLES=glibc.tune.x86_ibt=[permissive|on|off]

1. permissive: SHSTK is disabled when dlopening a legacy ELF module.
2. on: IBT or SHSTK are always enabled, regardless if there are IBT or
SHSTK bits in GNU program property.
3. off: IBT or SHSTK are always disabled, regardless if there are IBT or
SHSTK bits in GNU program property.

<cet.h> from CET-enabled GCC is automatically included by assembly codes
to add GNU_PROPERTY_X86_FEATURE_1_IBT and GNU_PROPERTY_X86_FEATURE_1_SHSTK
to GNU program property.  _CET_ENDBR is added at the entrance of all
assembly functions whose address may be taken.  _CET_NOTRACK is used to
insert NOTRACK prefix with indirect jump table to support IBT.  It is
defined as notrack when _CET_NOTRACK is defined in <cet.h>.

	 [BZ #21598]
	* configure.ac: Add --enable-cet.
	* configure: Regenerated.
	* elf/Makefille (all-built-dso): Add a comment.
	* elf/dl-load.c (filebuf): Moved before "dynamic-link.h".
	Include <dl-prop.h>.
	(_dl_map_object_from_fd): Call _dl_process_pt_note on PT_NOTE
	segment.
	* elf/dl-open.c: Include <dl-prop.h>.
	(dl_open_worker): Call _dl_open_check.
	* elf/rtld.c: Include <dl-prop.h>.
	(dl_main): Call _rtld_process_pt_note on PT_NOTE segment.  Call
	_rtld_main_check.
	* sysdeps/generic/dl-prop.h: New file.
	* sysdeps/i386/dl-cet.c: Likewise.
	* sysdeps/unix/sysv/linux/x86/cpu-features.c: Likewise.
	* sysdeps/unix/sysv/linux/x86/dl-cet.h: Likewise.
	* sysdeps/x86/cet-tunables.h: Likewise.
	* sysdeps/x86/check-cet.awk: Likewise.
	* sysdeps/x86/configure: Likewise.
	* sysdeps/x86/configure.ac: Likewise.
	* sysdeps/x86/dl-cet.c: Likewise.
	* sysdeps/x86/dl-procruntime.c: Likewise.
	* sysdeps/x86/dl-prop.h: Likewise.
	* sysdeps/x86/libc-start.h: Likewise.
	* sysdeps/x86/link_map.h: Likewise.
	* sysdeps/i386/dl-trampoline.S (_dl_runtime_resolve): Add
	_CET_ENDBR.
	(_dl_runtime_profile): Likewise.
	(_dl_runtime_resolve_shstk): New.
	(_dl_runtime_profile_shstk): Likewise.
	* sysdeps/linux/x86/Makefile (sysdep-dl-routines): Add dl-cet
	if CET is enabled.
	(CFLAGS-.o): Add -fcf-protection if CET is enabled.
	(CFLAGS-.os): Likewise.
	(CFLAGS-.op): Likewise.
	(CFLAGS-.oS): Likewise.
	(asm-CPPFLAGS): Add -fcf-protection -include cet.h if CET
	is enabled.
	(tests-special): Add $(objpfx)check-cet.out.
	(cet-built-dso): New.
	(+$(cet-built-dso:=.note)): Likewise.
	(common-generated): Add $(cet-built-dso:$(common-objpfx)%=%.note).
	($(objpfx)check-cet.out): New.
	(generated): Add check-cet.out.
	* sysdeps/x86/cpu-features.c: Include <dl-cet.h> and
	<cet-tunables.h>.
	(TUNABLE_CALLBACK (set_x86_ibt)): New prototype.
	(TUNABLE_CALLBACK (set_x86_shstk)): Likewise.
	(init_cpu_features): Call get_cet_status to check CET status
	and update dl_x86_feature_1 with CET status.  Call
	TUNABLE_CALLBACK (set_x86_ibt) and TUNABLE_CALLBACK
	(set_x86_shstk).  Disable and lock CET in libc.a.
	* sysdeps/x86/cpu-tunables.c: Include <cet-tunables.h>.
	(TUNABLE_CALLBACK (set_x86_ibt)): New function.
	(TUNABLE_CALLBACK (set_x86_shstk)): Likewise.
	* sysdeps/x86/sysdep.h (_CET_NOTRACK): New.
	(_CET_ENDBR): Define if not defined.
	(ENTRY): Add _CET_ENDBR.
	* sysdeps/x86/dl-tunables.list (glibc.tune): Add x86_ibt and
	x86_shstk.
	* sysdeps/x86_64/dl-trampoline.h (_dl_runtime_resolve): Add
	_CET_ENDBR.
	(_dl_runtime_profile): Likewise.
2018-07-16 14:08:27 -07:00
Zack Weinberg 329ea513b4 Avoid cancellable I/O primitives in ld.so.
Neither the <dlfcn.h> entry points, nor lazy symbol resolution, nor
initial shared library load-up, are cancellation points, so ld.so
should exclusively use I/O primitives that are not cancellable.  We
currently achieve this by having the cancellation hooks compile as
no-ops when IS_IN(rtld); this patch changes to using exclusively
_nocancel primitives in the source code instead, which makes the
intent clearer and significantly reduces the amount of code compiled
under IS_IN(rtld) as well as IS_IN(libc) -- in particular,
elf/Makefile no longer thinks we require a copy of unwind.c in
rtld-libc.a.  (The older mechanism is preserved as a backstop.)

The bulk of the change is splitting up the files that define the
_nocancel I/O functions, so they don't also define the variants that
*are* cancellation points; after which, the existing logic for picking
out the bits of libc that need to be recompiled as part of ld.so Just
Works.  I did this for all of the _nocancel functions, not just the
ones used by ld.so, for consistency.

fcntl was a little tricky because it's only a cancellation point for
certain opcodes (F_SETLKW(64), which can block), and the existing
__fcntl_nocancel wasn't applying the FCNTL_ADJUST_CMD hook, which
strikes me as asking for trouble, especially as the only nontrivial
definition of FCNTL_ADJUST_CMD (for powerpc64) changes F_*LK* opcodes.
To fix this, fcntl_common moves to fcntl_nocancel.c along with
__fcntl_nocancel, and changes its name to the extern (but hidden)
symbol __fcntl_nocancel_adjusted, so that regular fcntl can continue
calling it.  __fcntl_nocancel now applies FCNTL_ADJUST_CMD; so that
both both fcntl.c and fcntl_nocancel.c can see it, the only nontrivial
definition moves from sysdeps/u/s/l/powerpc/powerpc64/fcntl.c to
.../powerpc64/sysdep.h and becomes entirely a macro, instead of a macro
that calls an inline function.

The nptl version of libpthread also changes a little, because its
"compat-routines" formerly included files that defined all the
_nocancel functions it uses; instead of continuing to duplicate them,
I exported the relevant ones from libc.so as GLIBC_PRIVATE.  Since the
Linux fcntl.c calls a function defined by fcntl_nocancel.c, it can no
longer be used from libpthread.so; instead, introduce a custom
forwarder, pt-fcntl.c, and export __libc_fcntl from libc.so as
GLIBC_PRIVATE.  The nios2-linux ABI doesn't include a copy of vfork()
in libpthread, and it was handling that by manipulating
libpthread-routines in .../linux/nios2/Makefile; it is cleaner to do
what other such ports do, and have a pt-vfork.S that defines no symbols.

Right now, it appears that Hurd does not implement _nocancel I/O, so
sysdeps/generic/not-cancel.h will forward everything back to the
regular functions.  This changed the names of some of the functions
that sysdeps/mach/hurd/dl-sysdep.c needs to interpose.

	* elf/dl-load.c, elf/dl-misc.c, elf/dl-profile.c, elf/rtld.c
	* sysdeps/unix/sysv/linux/dl-sysdep.c
	Include not-cancel.h.  Use __close_nocancel instead of __close,
	__open64_nocancel instead of __open, __read_nocancel instead of
	__libc_read, and __write_nocancel instead of __libc_write.

	* csu/check_fds.c (check_one_fd)
	* sysdeps/posix/fdopendir.c (__fdopendir)
	* sysdeps/posix/opendir.c (__alloc_dir): Use __fcntl_nocancel
        instead of __fcntl and/or __libc_fcntl.

	* sysdeps/unix/sysv/linux/pthread_setname.c (pthread_setname_np)
	* sysdeps/unix/sysv/linux/pthread_getname.c (pthread_getname_np)
        * sysdeps/unix/sysv/linux/i386/smp.h (is_smp_system):
	Use __open64_nocancel instead of __open_nocancel.

	* sysdeps/unix/sysv/linux/not-cancel.h: Move all of the
	hidden_proto declarations to the end and issue them if either
	IS_IN(libc) or IS_IN(rtld).
	* sysdeps/unix/sysv/linux/Makefile [subdir=io] (sysdep_routines):
	Add close_nocancel, fcntl_nocancel, nanosleep_nocancel,
	open_nocancel, open64_nocancel, openat_nocancel, pause_nocancel,
	read_nocancel, waitpid_nocancel, write_nocancel.

        * io/Versions [GLIBC_PRIVATE]: Add __libc_fcntl,
        __fcntl_nocancel, __open64_nocancel, __write_nocancel.
        * posix/Versions: Add __nanosleep_nocancel, __pause_nocancel.

        * nptl/pt-fcntl.c: New file.
        * nptl/Makefile (pthread-compat-wrappers): Remove fcntl.
        (libpthread-routines): Add pt-fcntl.
        * include/fcntl.h (__fcntl_nocancel_adjusted): New function.
        (__libc_fcntl): Remove attribute_hidden.
	* sysdeps/unix/sysv/linux/fcntl.c (__libc_fcntl): Call
	__fcntl_nocancel_adjusted, not fcntl_common.
        (__fcntl_nocancel): Move to new file fcntl_nocancel.c.
	(fcntl_common): Rename to __fcntl_nocancel_adjusted; also move
	to fcntl_nocancel.c.
	* sysdeps/unix/sysv/linux/fcntl_nocancel.c: New file.
	* sysdeps/unix/sysv/linux/powerpc/powerpc64/fcntl.c: Remove file.
	* sysdeps/unix/sysv/linux/powerpc/powerpc64/sysdep.h:
	Define FCNTL_ADJUST_CMD here, as a self-contained macro.

	* sysdeps/unix/sysv/linux/close.c: Move __close_nocancel to...
	* sysdeps/unix/sysv/linux/close_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/nanosleep.c: Move __nanosleep_nocancel to...
	* sysdeps/unix/sysv/linux/nanosleep_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/open.c: Move __open_nocancel to...
	* sysdeps/unix/sysv/linux/open_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/open64.c: Move __open64_nocancel to...
	* sysdeps/unix/sysv/linux/open64_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/openat.c: Move __openat_nocancel to...
	* sysdeps/unix/sysv/linux/openat_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/openat64.c: Move __openat64_nocancel to...
	* sysdeps/unix/sysv/linux/openat64_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/pause.c: Move __pause_nocancel to...
	* sysdeps/unix/sysv/linux/pause_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/read.c: Move __read_nocancel to...
	* sysdeps/unix/sysv/linux/read_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/waitpid.c: Move __waitpid_nocancel to...
	* sysdeps/unix/sysv/linux/waitpid_nocancel.c: ...this new file.
	* sysdeps/unix/sysv/linux/write.c: Move __write_nocancel to...
	* sysdeps/unix/sysv/linux/write_nocancel.c: ...this new file.

        * sysdeps/unix/sysv/linux/nios2/Makefile: Don't override
        libpthread-routines.
        * sysdeps/unix/sysv/linux/nios2/pt-vfork.S: New file which
        defines nothing.

        * sysdeps/mach/hurd/dl-sysdep.c: Define __read instead of
        __libc_read, and __write instead of __libc_write.  Define
        __open64 in addition to __open.
2018-06-12 09:53:04 -04:00
Maciej W. Rozycki 10a446ddcc elf: Unify symbol address run-time calculation [BZ #19818]
Wrap symbol address run-time calculation into a macro and use it
throughout, replacing inline calculations.

There are a couple of variants, most of them different in a functionally
insignificant way.  Most calculations are right following RESOLVE_MAP,
at which point either the map or the symbol returned can be checked for
validity as the macro sets either both or neither.  In some places both
the symbol and the map has to be checked however.

My initial implementation therefore always checked both, however that
resulted in code larger by as much as 0.3%, as many places know from
elsewhere that no check is needed.  I have decided the size growth was
unacceptable.

Having looked closer I realized that it's the map that is the culprit.
Therefore I have modified LOOKUP_VALUE_ADDRESS to accept an additional
boolean argument telling it to access the map without checking it for
validity.  This in turn has brought quite nice results, with new code
actually being smaller for i686, and MIPS o32, n32 and little-endian n64
targets, unchanged in size for x86-64 and, unusually, marginally larger
for big-endian MIPS n64, as follows:

i686:
   text    data     bss     dec     hex filename
 152255    4052     192  156499   26353 ld-2.27.9000-base.so
 152159    4052     192  156403   262f3 ld-2.27.9000-elf-symbol-value.so
MIPS/o32/el:
   text    data     bss     dec     hex filename
 142906    4396     260  147562   2406a ld-2.27.9000-base.so
 142890    4396     260  147546   2405a ld-2.27.9000-elf-symbol-value.so
MIPS/n32/el:
   text    data     bss     dec     hex filename
 142267    4404     260  146931   23df3 ld-2.27.9000-base.so
 142171    4404     260  146835   23d93 ld-2.27.9000-elf-symbol-value.so
MIPS/n64/el:
   text    data     bss     dec     hex filename
 149835    7376     408  157619   267b3 ld-2.27.9000-base.so
 149787    7376     408  157571   26783 ld-2.27.9000-elf-symbol-value.so
MIPS/o32/eb:
   text    data     bss     dec     hex filename
 142870    4396     260  147526   24046 ld-2.27.9000-base.so
 142854    4396     260  147510   24036 ld-2.27.9000-elf-symbol-value.so
MIPS/n32/eb:
   text    data     bss     dec     hex filename
 142019    4404     260  146683   23cfb ld-2.27.9000-base.so
 141923    4404     260  146587   23c9b ld-2.27.9000-elf-symbol-value.so
MIPS/n64/eb:
   text    data     bss     dec     hex filename
 149763    7376     408  157547   2676b ld-2.27.9000-base.so
 149779    7376     408  157563   2677b ld-2.27.9000-elf-symbol-value.so
x86-64:
   text    data     bss     dec     hex filename
 148462    6452     400  155314   25eb2 ld-2.27.9000-base.so
 148462    6452     400  155314   25eb2 ld-2.27.9000-elf-symbol-value.so

	[BZ #19818]
	* sysdeps/generic/ldsodefs.h (LOOKUP_VALUE_ADDRESS): Add `set'
	parameter.
	(SYMBOL_ADDRESS): New macro.
	[!ELF_FUNCTION_PTR_IS_SPECIAL] (DL_SYMBOL_ADDRESS): Use
	SYMBOL_ADDRESS for symbol address calculation.
	* elf/dl-runtime.c (_dl_fixup): Likewise.
	(_dl_profile_fixup): Likewise.
	* elf/dl-symaddr.c (_dl_symbol_address): Likewise.
	* elf/rtld.c (dl_main): Likewise.
	* sysdeps/aarch64/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/alpha/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/arm/dl-machine.h (elf_machine_rel): Likewise.
	(elf_machine_rela): Likewise.
	* sysdeps/hppa/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/hppa/dl-symaddr.c (_dl_symbol_address): Likewise.
	* sysdeps/i386/dl-machine.h (elf_machine_rel): Likewise.
	(elf_machine_rela): Likewise.
	* sysdeps/ia64/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/m68k/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/microblaze/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/mips/dl-machine.h (ELF_MACHINE_BEFORE_RTLD_RELOC):
	Likewise.
	(elf_machine_reloc): Likewise.
	(elf_machine_got_rel): Likewise.
	* sysdeps/mips/dl-trampoline.c (__dl_runtime_resolve): Likewise.
	* sysdeps/nios2/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/powerpc/powerpc32/dl-machine.h (elf_machine_rela):
	Likewise.
	* sysdeps/powerpc/powerpc64/dl-machine.h (elf_machine_rela):
	Likewise.
	* sysdeps/riscv/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/s390/s390-32/dl-machine.h (elf_machine_rela):
	Likewise.
	* sysdeps/s390/s390-64/dl-machine.h (elf_machine_rela):
	Likewise.
	* sysdeps/sh/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/sparc/sparc32/dl-machine.h (elf_machine_rela):
	Likewise.
	* sysdeps/sparc/sparc64/dl-machine.h (elf_machine_rela):
	Likewise.
	* sysdeps/tile/dl-machine.h (elf_machine_rela): Likewise.
	* sysdeps/x86_64/dl-machine.h (elf_machine_rela): Likewise.

Reviewed-by: Adhemerval Zanella <adhemerval.zanella@linaro.org>
2018-04-04 23:09:37 +01:00
Florian Weimer 52a01100ad elf: Remove ad-hoc restrictions on dlopen callers [BZ #22787]
This looks like a post-exploitation hardening measure: If an attacker is
able to redirect execution flow, they could use that to load a DSO which
contains additional code (or perhaps make the stack executable).

However, the checks are not in the correct place to be effective: If
they are performed before the critical operation, an attacker with
sufficient control over execution flow could simply jump directly to
the code which performs the operation, bypassing the check.  The check
would have to be executed unconditionally after the operation and
terminate the process in case a caller violation was detected.

Furthermore, in _dl_check_caller, there was a fallback reading global
writable data (GL(dl_rtld_map).l_map_start and
GL(dl_rtld_map).l_text_end), which could conceivably be targeted by an
attacker to disable the check, too.

Other critical functions (such as system) remain completely
unprotected, so the value of these additional checks does not appear
that large.  Therefore this commit removes this functionality.
2018-02-21 10:37:22 +01:00