Commit Graph

944 Commits

Author SHA1 Message Date
Edward Tomasz Napierala
152036a0f7 Plug memory leak on error case.
Reported by:	Coverity
CID:		1382112
MFC after:	2 weeks
2017-10-29 12:07:27 +00:00
Edward Tomasz Napierala
b4ed9a87f9 Remove unneeded calls to access(2) from rtld(1); just call open(2) instead.
The result looks like this:

--- przed       2017-10-21 23:19:21.445034000 +0100
+++ po  2017-10-21 23:18:50.031865000 +0100
@@ -11,7 +11,6 @@ mmap(0x0,102,PROT_READ,MAP_PRIVATE,3,0x0)      = 343665418
 close(3)                                        = 0 (0x0)
 open("/usr/local/etc/libmap.d",O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC,0165) ERR#2 'No such file or directory'
 munmap(0x80067d000,102)                                 = 0 (0x0)
-access("/usr/local/lib/libintl.so.8",F_OK)      = 0 (0x0)
 openat(AT_FDCWD,"/usr/local/lib/libintl.so.8",O_RDONLY|O_CLOEXEC|O_VERIFY,00) = 3 (0x3)
 fstat(3,{ mode=-rw-r--r-- ,inode=642560,size=55188,blksize=32768 }) = 0 (0x0)
 mmap(0x0,4096,PROT_READ,MAP_PRIVATE|MAP_PREFAULT_READ,3,0x0) = 34366541824 (0x80067d000)
@@ -20,14 +19,13 @@ mmap(0x800877000,40960,PROT_READ|PROT_EXEC,MAP_PRIVATE
 mmap(0x800a81000,4096,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_FIXED|MAP_PREFAULT_READ,3,0xa000) = 34370752512 (0x800a81000)
 munmap(0x80067d000,4096)                        = 0 (0x0)
 close(3)                                        = 0 (0x0)
-access("/usr/local/lib/libc.so.7",F_OK)                 ERR#2 'No such file or directory'
+openat(AT_FDCWD,"/usr/local/lib/libc.so.7",O_RDONLY|O_CLOEXEC|O_VERIFY,00) ERR#2 'No such file or directory'
 openat(AT_FDCWD,"/var/run/ld-elf.so.hints",O_RDONLY|O_CLOEXEC,00) = 3 (0x3)
 read(3,"Ehnt\^A\0\0\0\M^@\0\0\0\M-2\0\0"...,128) = 128 (0x80)
 fstat(3,{ mode=-r--r--r-- ,inode=970684,size=306,blksize=32768 }) = 0 (0x0)
 lseek(3,0x80,SEEK_SET)                          = 128 (0x80)
 read(3,"/lib:/usr/lib:/usr/lib/compat:/u"...,178) = 178 (0xb2)
 close(3)                                        = 0 (0x0)
-access("/lib/libc.so.7",F_OK)                   = 0 (0x0)
 openat(AT_FDCWD,"/lib/libc.so.7",O_RDONLY|O_CLOEXEC|O_VERIFY,00) = 3 (0x3)
 fstat(3,{ mode=-r--r--r-- ,inode=1605239,size=1910320,blksize=32768 }) = 0 (0x0)
 mmap(0x0,4096,PROT_READ,MAP_PRIVATE|MAP_PREFAULT_READ,3,0x0) = 34366541824 (0x80067d000)

Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	DARPA, AFRL
Differential Revision:	https://reviews.freebsd.org/D12766
2017-10-24 12:56:08 +00:00
Edward Tomasz Napierala
2fe071d971 Replace lseek(2)/read(2) pair with pread(2), removing yet another syscall
from the binary startup code.

MFC after:	2 weeks
Sponsored by:	DARPA, AFRL
2017-10-24 12:04:07 +00:00
Edward Tomasz Napierala
1689a3c4ac Make find_library() conform to style(9). No functional changes.
Suggested by:	kib
MFC after:	2 weeks
Sponsored by:	DARPA, AFRL
2017-10-24 11:24:54 +00:00
Edward Tomasz Napierala
e65ad973b2 Reword the conditional; it was ugly, and adding another parameter,
which I'm going to do in a subsequent commit, would make it even uglier.
No functional changes.

MFC after:	2 weeks
Sponsored by:	DARPA, AFRL
2017-10-24 11:16:38 +00:00
Edward Tomasz Napierala
a8b31c14d2 Use xmalloc and read(2) instead of mmap(2) to read in libmap.conf(5).
This removes the need to call munmap(2) afterwards.

MFC after:	2 weeks
Sponsored by:	DARPA, AFRL
Differential Revision:	https://reviews.freebsd.org/D12767
2017-10-24 10:48:26 +00:00
Edward Tomasz Napierala
6b61e3e47a Don't call realpath(3) from libmap rtld code. This gets rid of a few calls
to fstatat(2) at binary startup; the difference looks like this:

--- przed       2017-10-14 13:55:49.983528000 +0100
+++ po  2017-10-14 14:10:39.134343000 +0100
@@ -1,15 +1,10 @@
 mmap(0x0,32768,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0x0) = 34366173184 (0x800623000)
 issetugid()                                     = 0 (0x0)
-fstatat(AT_FDCWD,"/etc",{ mode=drwxr-xr-x ,inode=1364352,size=2560,blksize=32768 },AT_SYMLINK_NOFOLLOW) = 0 (0x0)
-fstatat(AT_FDCWD,"/etc/libmap.conf",{ mode=-rw-r--r-- ,inode=1373288,size=102,blksize=32768 },AT_SYMLINK_NOFOLLOW) = 0 (0x0)
 openat(AT_FDCWD,"/etc/libmap.conf",O_RDONLY|O_CLOEXEC,00) = 3 (0x3)
 fstat(3,{ mode=-rw-r--r-- ,inode=1373288,size=102,blksize=32768 }) = 0 (0x0)
 mmap(0x0,102,PROT_READ,MAP_PRIVATE,3,0x0)       = 34366205952 (0x80062b000)
 close(3)                                        = 0 (0x0)
-fstatat(AT_FDCWD,"/usr",{ mode=drwxr-xr-x ,inode=561792,size=512,blksize=32768 },AT_SYMLINK_NOFOLLOW) = 0 (0x0)
-fstatat(AT_FDCWD,"/usr/local",{ mode=drwxr-xr-x ,inode=561800,size=512,blksize=32768 },AT_SYMLINK_NOFOLLOW) = 0 (0x0)
-fstatat(AT_FDCWD,"/usr/local/etc",{ mode=drwxr-xr-x ,inode=653279,size=1536,blksize=32768 },AT_SYMLINK_NOFOLLOW) = 0 (0x0)
-fstatat(AT_FDCWD,"/usr/local/etc/libmap.d",0x7fffffffcf50,AT_SYMLINK_NOFOLLOW) ERR#2 'No such file or directory'
+open("/usr/local/etc/libmap.d",O_RDONLY|O_NONBLOCK|O_DIRECTORY|O_CLOEXEC,0165) ERR#2 'No such file or directory'
 munmap(0x80062b000,102)                                 = 0 (0x0)
 openat(AT_FDCWD,"/var/run/ld-elf.so.hints",O_RDONLY|O_CLOEXEC,00) = 3 (0x3)
 read(3,"Ehnt\^A\0\0\0\M^@\0\0\0\M-2\0\0"...,128) = 128 (0x80)

Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	DARPA, AFRL
Differential Revision:	https://reviews.freebsd.org/D12741
2017-10-22 10:32:40 +00:00
John Baldwin
b4e9a36bf7 Handle relocations for newer non-PIC MIPS ABI.
Newer binutils supports extensions to the MIPS ABI for non-PIC code
that is used when compiling O32 binaries with clang 5 (but not used
for N64 oddly enough).  These extensions require support for
R_MIPS_COPY relocations as well as a second PLT GOT using
R_MIPS_JUMP_SLOT relocations.

For R_MIPS_COPY, use the same approach as on other architectures where
fixups are deferred to the MD do_copy_relocations.

The additional PLT GOT for jump slots is located in a .got.plt section
which is identified by a DT_MIPS_PLTGOT dynamic entry.  This GOT also
requires fixups for the first two GOT entries just as the normal GOT.
However, the entry point for this second GOT uses a different calling
convention. Rather than passing an offset into the GOT, it passes an
offset into the .rel.plt section.  This requires a second entry point
(_rtld_pltbind_start) which calls the normal _rtld_bind() rather than
_mips_rtld_bind().  This also means providing a real version of
reloc_jmpslot() which is used by _rtld_bind().

In addition, add real implementions of reloc_plt() and
reloc_jmpslots() which walk .rel.plt handling R_MIPS_JUMP_SLOT
relocations.

Reviewed by:	kib
Sponsored by:	DARPA / AFRL
Differential Revision:	https://reviews.freebsd.org/D12326
2017-09-12 17:46:30 +00:00
Warner Losh
08d1c5b152 End softfp->hardfp transition period for arm
On hard-float 32-bit arm platforms, always search for the soft float
binaries in the alternative locations.

Sponsored by: Netflix
Differential Review: https://reviews.freebsd.org/D12274
MFC After: 1 week
2017-09-12 17:06:35 +00:00
John Baldwin
21a8b38698 Add CFI directives for _rtld_bind_start.
This allows debuggers to unwind back into the caller when stopped in the
runtime linker.

Sponsored by:	DARPA / AFRL
2017-09-11 22:18:01 +00:00
Konstantin Belousov
cf551abc8b Add serial comma.
Submitted by:	wblock
MFC after:	3 days
2017-09-01 16:56:37 +00:00
John Baldwin
f4711b38fd Compile reloc.o with -fno-jump-tables on MIPS.
In particular, the switch statement on the type of dynamic entries
in _rtld_relocate_nonplt_self() needs to not use a jump table since
jump tables on MIPS use local GOT entries which aren't initialized
until after this loop.

Suggested by:	arichardson
Reviewed by:	emaste
Sponsored by:	DARPA / AFRL
2017-08-30 20:00:15 +00:00
John Baldwin
83d33b2bb5 Read max_stack_flags from correct object.
'obj' is not initialized here.

Reviewed by:	kib
MFC after:	1 week
Sponsored by:	DARPA / AFRL
2017-08-30 18:22:52 +00:00
Enji Cooper
188e46ab03 Add supporting changes for Add limited sandbox capability to "make check"
Non-tests/... changes:
- Add HAS_TESTS= to Makefiles with libraries and programs to enable iteration
  and propagate the appropriate environment down to *.test.mk.

tests/... changes:
- Add appropriate support Makefile.inc's to set HAS_TESTS in a minimal manner,
  since tests/... is a special subdirectory tree compared to the others.

MFC after:	2 months
MFC with:	r322511
Reviewed by:	arch (silence), testing (silence)
Differential Revision:	D12014
2017-08-14 19:21:37 +00:00
Ruslan Bukin
af19cc59ca Support for v1.10 (latest) of RISC-V privilege specification.
New version is not compatible on supervisor mode with v1.9.1
(previous version).

Highlights:
    o BBL (Berkeley Boot Loader) provides no initial page tables
      anymore allowing us to choose VM, to build page tables manually
      and enable MMU in S-mode.
    o SBI interface changed.
    o GENERIC kernel.
      FDT is now chosen standard for RISC-V hardware description.
      DTB is now provided by Spike (golden model simulator). This
      allows us to introduce GENERIC kernel. However, description
      for console and timer devices is not provided in DTB, so move
      these devices temporary to nexus bus.
    o Supervisor can't access userspace by default. Solution is to
      set SUM (permit Supervisor User Memory access) bit in sstatus
      register.
    o Compressed extension is now turned on by default.
    o External GCC 7.1 compiler used.
    o _gp renamed to __global_pointer$
    o Compiler -march= string is now in use allowing us to choose
      required extensions (compressed, FPU, atomic, etc).

Sponsored by:	DARPA, AFRL
Differential Revision:	https://reviews.freebsd.org/D11800
2017-08-10 14:18:09 +00:00
Ruslan Bukin
ca20f8ec29 o Replace __riscv__ with __riscv
o Replace __riscv64 with (__riscv && __riscv_xlen == 64)

This is required to support new GCC 7.1 compiler.
This is compatible with current GCC 6.1 compiler.

RISC-V is extensible ISA and the idea here is to have built-in define
per each extension, so together with __riscv we will have some subset
of these as well (depending on -march string passed to compiler):

__riscv_compressed
__riscv_atomic
__riscv_mul
__riscv_div
__riscv_muldiv
__riscv_fdiv
__riscv_fsqrt
__riscv_float_abi_soft
__riscv_float_abi_single
__riscv_float_abi_double
__riscv_cmodel_medlow
__riscv_cmodel_medany
__riscv_cmodel_pic
__riscv_xlen

Reviewed by:	ngie
Sponsored by:	DARPA, AFRL
Differential Revision:	https://reviews.freebsd.org/D11901
2017-08-07 14:09:57 +00:00
Enji Cooper
d511b20a69 Add HAS_TESTS to all Makefiles that are currently using the
`SUBDIR.${MK_TESTS}+= tests` idiom.

This is a follow up to r321912.
2017-08-02 08:50:42 +00:00
Enji Cooper
4b330699f8 Convert traditional ${MK_TESTS} conditional idiom for including test
directories to SUBDIR.${MK_TESTS} idiom

This is being done to pave the way for future work (and homogenity) in
^/projects/make-check-sandbox .

No functional change intended.

MFC after:	1 weeks
2017-08-02 08:35:51 +00:00
Konstantin Belousov
dd269a0bf4 Allow to specify targets by absolute paths in libmap.conf.
Submitted by:	Tatu Kilappa <tatu.kilappa@iki.fi>
PR:	221032
MFC after:	2 weeks
2017-07-27 08:33:31 +00:00
Konstantin Belousov
9152cb3868 Language improvements.
Submitted by:	wblock
MFC after:	3 days
Differential revision:	https://reviews.freebsd.org/D10826
2017-07-14 15:42:12 +00:00
Xin LI
2bbd226f5a In open_binary_fd: when using buffer size for strl* and snprintf,
always use >= instead of > to avoid truncation.

Reviewed by:	kib
Differential Revision:	https://reviews.freebsd.org/D11474
MFC after:	3 days
2017-07-05 06:12:21 +00:00
Konstantin Belousov
84de44d3f2 When reporting undefined symbol, note the version, if specified.
Use the standard syntax of name@version, I do not expect a confusion
due to unlikely possibility of the name containing the '@' character.

Requested by:	emaste
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2017-07-04 20:19:36 +00:00
Konstantin Belousov
a36deee3d3 Use address space guard to implement inter-segment gap.
Rtld checks and use old MAP_ANON/PROT_NONE method of creating gap if
running on old kernel.

Reviewed by:	alc, markj
Tested by:	pho, Qualys
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2017-06-24 17:04:27 +00:00
Konstantin Belousov
109f3b8c69 Document direct execution mode for rtld.
Reviewed by:	emaste, jonathan (previous version)
Sponsored by:	The FreeBSD Foundation
MFC after:	3 days
Differential Revision:	https://reviews.freebsd.org/D10826
2017-05-29 13:38:26 +00:00
Konstantin Belousov
18934eb6b8 Correct explanation of the dynamic tokens handling.
Reviewed by:	emaste, jonathan
Sponsored by:	The FreeBSD Foundation
X-Differential Revision:	https://reviews.freebsd.org/D10826
2017-05-29 13:36:32 +00:00
Eric van Gyzen
7fb37371e8 rtld: fix warnings about redundant declarations
Fix warnings about redundant declarations in rtld
when libthr in increased to WARNS=6.

Reviewed by:	kib
MFC after:	3 days
Sponsored by:	Dell EMC
Differential Revision:	https://reviews.freebsd.org/D10934
2017-05-26 15:55:03 +00:00
Konstantin Belousov
9e5e0e8850 For ld.so direct execution mode, implement -p option: search for the
binary in $PATH.

Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
Differential revision:	https://reviews.freebsd.org/D10790
2017-05-23 10:00:52 +00:00
Konstantin Belousov
ce9600b12e Update my copyright, note The FreeBSD Foundation involvement.
While tweaking copyright block, switch to use __FBSDID for tag.

Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2017-05-18 09:34:26 +00:00
Konstantin Belousov
591986a8da Fix style [1], add static keyword before static function definition.
Noted by:	bapt [1]
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2017-05-18 09:31:30 +00:00
Jonathan Anderson
dc902dbd60 Fix some nroff syntax in rtld.1.
When I originally documented the LD_LIBRARY_PATH_FDS environment variable,
I used `.Ev` rather than `.It Ev` to introduce it; this led to the
documentation being embedded in the previous paragraph (LD_LIBRARY_PATH).
2017-05-18 00:32:05 +00:00
Jonathan Anderson
d5a5e50d3b Allow rtld direct-exec to take a file descriptor.
When executing rtld directly, allow a file descriptor to be explicitly
specified rather than opened from the given path. This, together with the
LD_LIBRARY_PATH_FDS environment variable, allows dynamically-linked
applications to be executed from within capability mode.

Also add some rudimentary argument parsing (without pulling in getopt or
the like) to accept this file descriptor, a help (-h) option and a basic
usage string.

Reviewed by:	kib
Sponsored by:	NSERC, RDC
Differential Revision:	https://reviews.freebsd.org/D10751
2017-05-17 22:51:28 +00:00
Konstantin Belousov
da403aea11 Pretend that there is some security when executing in direct mode.
Do not allow direct exec if we the process is suid. Try to follow Unix
permission checks for DACs, ignore ACLs.

Reviewed by:	emaste
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
Differential revision:	https://reviews.freebsd.org/D10750
2017-05-16 19:53:38 +00:00
Jonathan Anderson
7a36bd9ffd Rename rtld's parse_libdir to parse_integer.
This is a more accurate name, as the integer doesn't have to be a library
directory descriptor. It is also a prerequisite for more argument parsing
coming in the near future (e.g., parsing explicit binary descriptors).

Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	NSERC
2017-05-16 13:27:44 +00:00
Konstantin Belousov
0fc65b0ab8 Make ld-elf.so.1 directly executable.
Check if passed phdr is actually phdr of the interpreter itself, and
decide that this is the case of direct execution.  In this case, the
binary to activate is specified in the argv[1].  After opening it,
shift down on-stack structure with argv, env and aux vectors to
emulate execution of the binary and not of the interpreter.

Reviewed by:	emaste
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
Differential revision:	https://reviews.freebsd.org/D10701
2017-05-15 18:48:58 +00:00
Konstantin Belousov
9104191924 Fix the AT_EXECFD functionality.
If the mapped object is linked at specific address, we must obey it.
If AT_EXECFD is not used, only in-kernel ELF image activator needed to
keep the mapping address, since only binaries are linked at the fixed
address, and binaries are mapped by kernel in this case.

Reviewed by:	emaste
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
X-Differential revision:	https://reviews.freebsd.org/D10701
2017-05-15 18:47:25 +00:00
Konstantin Belousov
c4f7cccbe7 In _rtld(), reorder local declarations to compact the block and
partially sort them by style(9).  Move locals declarations from nested
blocks into the block at function start.

Discussed with:	emaste
MFC after:	1 week
2017-05-13 18:59:27 +00:00
Jilles Tjoelker
2d6acb22fe rtld(1): Document that LD_BIND_NOT is unset for setugid processes.
MFC after:	2 weeks
2017-03-16 22:15:43 +00:00
Konstantin Belousov
018865f8e8 Disable LD_BIND_NOT for setugid processes.
Requested by:	jilles
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2017-03-15 23:47:19 +00:00
Konstantin Belousov
e35ddbe448 Implement LD_BIND_NOT knob for rtld.
From the manpage:
When set to a nonempty string, prevents modifications of the PLT slots
when doing bindings.  As result, each call of the PLT-resolved
function is resolved.  In combination with debug output, this provides
complete account of all bind actions at runtime.

Same feature exists on Linux and Solaris.

Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2017-03-15 21:11:57 +00:00
Alan Somers
35804720ec Increase WARNS for rtld-elf tests
ATF tests have a default WARNS of 0, unlike other usermode programs.

Reviewed by:  ngie, julian
MFC after:    3 weeks
Sponsored by: Spectra Logic Corporation
Differential Revision:        https://reviews.freebsd.org/D9933
2017-03-11 00:10:40 +00:00
Konstantin Belousov
12c81769b6 Avoid bind lock recursion.
When dlclose(3) unloads an object with filtees, it recursively calls
dlclose(3) on each filtee in free_needed_filtees().  Introduce
dlclose_locked() helper, called from free_needed_filtees() instead of
dlclose(), and pass the bind lockstate down to avoid recursing.

Reported and tested by:	jhibbits
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2017-03-09 21:05:47 +00:00
Rodney W. Grimes
ce9f2d31b3 Convert absolute links to relative links.
Style.Makefile(9) has been ignored to produce minimal diffs.

Approved by:	grehan (mentor)
MFC after:	1 week
2017-03-07 05:10:38 +00:00
Warner Losh
fbbd9655e5 Renumber copyright clause 4
Renumber cluase 4 to 3, per what everybody else did when BSD granted
them permission to remove clause 3. My insistance on keeping the same
numbering for legal reasons is too pedantic, so give up on that point.

Submitted by:	Jan Schaumann <jschauma@stevens.edu>
Pull Request:	https://github.com/freebsd/freebsd/pull/96
2017-02-28 23:42:47 +00:00
John Baldwin
e278d94bca Fully handle the special encoding of GOT[1] on mips64.
The MIPS ABI does not require the second GOT entry to be reserved for use
by the runtime linker as on other architectures.  Instead, static linkers
use a special value in the second GOT entry to indicate if the entry is
reserved.  This value is supposed to consist of an address with the MSB
set and the rest of the bits all zero which is an invalid user address.

However, the old binutils currently in the tree uses the 32-bit mask value
(2^31) on 64-bit MIPS instead of 2^63.  This was fixed in upstream
binutils in 2008 to use 2^63 on 64-bit MIPS.

The first part of this change changes the runtime check in init_pltgot()
to check for both values (2^31 and 2^63) when deciding whether to store
the current object pointer in GOT[1] which fixes dynamic N64 binaries
compiled with modern binutils.

However, the initial version of this fix exposed another related bug in
that _rtld_relocate_nonplt_self() was only checking for the new value
(2^63) in GOT[1] and incorrectly treated GOT[1] as a local GOT entry
(and did not relocate the final local GOT entry).  To handle this, fix
all of the places that check for GOT[1]'s status to use the same macro
that checks for both values on N64.

Reviewed by:	kan, imp
Sponsored by:	DARPA / AFRL
Differential Revision:	https://reviews.freebsd.org/D9708
2017-02-23 00:02:49 +00:00
Konstantin Belousov
6d20836aa7 Handle protected symbols in rtld.
Protected symbol reference in GOT of the defining object must be
resolved to itself, same as -Bsymbolic globally.

Discussed with:	emaste
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
Differential revision:	https://reviews.freebsd.org/D9317
2017-02-09 23:33:06 +00:00
John Baldwin
2a7278307b Remove a duplicate store when performing REL32 relocations in rtld.
The duplicate call to store_ptr() was added in r204687, but it should
have no effect as it only stores an Elf_Sword and the later store_ptr()
does a write that is at least as large if not larger.

Reviewed by:	jmallett
Obtained from:	CheriBSD (sort of)
Sponsored by:	DARPA / AFRL
2017-01-30 23:13:41 +00:00
Peter Jeremy
8787928589 Extend LD_UTRACE by also generating utrace(2) log events for runtime linker
errors.

Reviewed by:	kib, jhb
Approved by:	jhb(mentor)
MFC after:	1 week
Differential Revision:	 D9347
2017-01-30 08:38:32 +00:00
Andrew Turner
02dbdb1677 Pull the R_AARCH64_TLSDESC code out into a common function and use them in
both the plt and non-plt case.

This fixes an issue where libraries built with LLD can fail with
"Unhandled relocation 1031"

PR:		214971
Obtained from:	1 week
Sponsored by:	DARPA, AFRL
2017-01-25 17:35:11 +00:00
Ed Maste
ebf8934652 rtld: do not rely on a populated GOT on amd64
On rela architectures GNU BFD ld and gold store the relocation addend
in GOT entries (in addition to the relocation's r_addend field).
rtld previously relied on this to access its own _DYNAMIC symbol in
order to apply its own relocations.

However, recording addends in the GOT is not specified by the ABI,
and some versions of LLVM's LLD linker leave the GOT uninitialized on
rela architectures.

BFD ld does not populate the GOT on sparc64, and sparc64 rtld has a
machine-dependent rtld_dynamic_addr() function that returns the
_DYNAMIC address. Use the same approach on amd64, obtaining the %rip-
relative _DYNAMIC address following a suggestion from Rafael Espíndola.

Architectures other than amd64 should be addressed in future work.

PR:		214972
Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D9180
2017-01-16 14:49:29 +00:00
Konstantin Belousov
f8adf1a784 For the main binary, postpone enforcing relro read-only protection
until copy relocations are done.

Newer binutils and lld seems to output copy into relro-protected range.

Reported by: Rafael Espц╜ndola via emaste
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2017-01-12 15:54:03 +00:00
Konstantin Belousov
b88a8d3d1d Fix acquisition of nested write compat rtld locks.
Obtaining compat rtld lock in write mode sets process signal mask to
block all signals.  Previous mask is stored in the global variable
oldsigmask.  If a lock is write-locked while another lock is already
write-locked, oldsigmask is overwritten by the total mask and on the
last unlock, all signals except traps appear to be blocked.

Fix this by counting the write-lock nested level, and only storing to
oldsigmask/restoring from it at the outermost level.

Masking signals disables involuntary preemption for libc_r, and there
could be no voluntary context switches in the locked code
(dl_iterate_phdr(3) keeps a lock around user callback, but it was
added long after libc_r was renounced).  Due to this, remembering the
level in the global variable after the lock is obtained should be
safe, because no two libc_r threads can acquire different write locks
in parallel.

PR:	215826
Reported by:	kami
Tested by:	yamagi@yamagi.org (previous version)
To be reviewed by:	kan
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2017-01-10 19:26:55 +00:00
Konstantin Belousov
e7bfd34bdf Use ANSI C definitions, update comment.
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2017-01-10 17:05:34 +00:00
Mark Johnston
57a9273f93 rtld: Fix a couple of bugs around the unloading of ELF filters.
- Pass the correct object to unload_filtees().
- Use a marker to restart iteration after unload_filtees() has returned.
  It calls dlclose() and may recursively remove entries from the global
  object list, so TAILQ_FOREACH_SAFE is not sufficient.

Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	Dell EMC Isilon
2016-12-22 17:44:27 +00:00
Mark Johnston
510fe58c82 rtld: Ensure that dlopen() cannot obtain a reference on a doomed object.
rtld drops the bind lock to call fini functions in an object prior to
unmapping it. The new "doomed" state flag prevents the acquisition of new
references for an object while the lock is dropped.

Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	Dell EMC Isilon
2016-12-22 17:41:32 +00:00
Mark Johnston
c02741759f rtld: Fix a race between dl_iterate_phdr() and dlclose().
Add a transient reference count to ensure that the phdr argument to the
callback remains valid while the bind lock is dropped.

Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	Dell EMC Isilon
2016-12-22 17:37:39 +00:00
Konstantin Belousov
3931b59fad Fix typo.
MFC after:	3 days
2016-12-16 14:23:08 +00:00
Bryan Drewery
9d9b69b373 Take write lock for rtld_bind before modifying obj_list in dl_iterate_phdr().
This avoids a race with readers such as dladdr(3)/dlinfo(3)/dlsym(3) and
the atexit(3) handler.  This race was introduced in r294373.

Reviewed by:	markj, kib, kan
MFC after:	2 weeks
Sponsored by:	Dell EMC Isilon
2016-12-13 18:05:14 +00:00
Ed Maste
eeef183376 Retire long-broken/unused static rtld support
rtld-elf has some vestigial support for building as a static executable.
r45501 introduced a partial implementation with a prescient note that it
"might never be enabled." r153515 introduced ELF symbol versioning
support, and removed part of the unused build infrastructure for static
rtld.

GNU ld populates rela relocation addends and GOT entries with the same
values, and rtld's run-time dynamic executable check relied on this.
Alternate toolchains may not populate the GOT entries, which caused
RTLD_IS_DYNAMIC to return false. Simplify rtld by just removing the
unused check.

If we want to restore static rtld support later on we ought to introduce
a build-time #ifdef flag.

PR:		214972
Reviewed by:	kan
MFC after:	1 month
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D8687
2016-12-02 14:23:26 +00:00
John Baldwin
6a368d16c8 Fix _mips_rtld_bind() to handle ELF filters.
MIPS does not use the common _rtld_bind() to handle runtime binding.
Instead, it uses a private _mips_rtld_bind().  Update _mips_rtld_bind()
to include the changes made to _rtld_bind() in r216695 and r218476 to
support upgrading the read-locked rtld_bind_lock to a write lock when
an object with a filter is encountered.

While here, add a 'where' variable to track the location of the fixup
in the GOT to make the code flow more closely match _rtld_bind().

Reviewed by:	kib
Obtained from:	CheriBSD
Sponsored by:	DARPA / AFRL
Differential Revision:	https://reviews.freebsd.org/D8625
2016-11-23 20:21:53 +00:00
Konstantin Belousov
d27078f990 Adjust r308689 to make rtld compilable with either in-tree or
(hopefully) stock gcc 4.2.1 on i386 and other arches.

In particular:
- Do not use %ebx in the asm constraints on i386, since rtld is
  compiled with -fPIC and gcc cannot handle GOT-base register reload
  (clang and newer gcc can).
- Avoid direct use of [static N] construct in the function
  declaration/definion.  In-tree gcc was patched to support this, but
  stock 4.2.1 cannot handle the feature.

Requested by:	bde
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2016-11-21 14:13:57 +00:00
Konstantin Belousov
4352999e0e Pass CPUID[1] %edx (cpu_feature), %ecx (cpu_feature2) and
CPUID[7].%ebx (cpu_stdext_feature), %ecx (cpu_stdext_feature2) to the
ifunc resolvers on x86.

It is much more clean to use CPUID instruction in usermode to retrieve
this information than to pass AT_HWCAP aux vector from kernel, on
x86.  Still, the change does allow for use of AT_HWCAP on arches where it is
needed, by passing aux array to ifunc_init() initializer which should
prepare arguments for ifunc resolvers.

Current signature for resolvers on x86 is
	func_t iresolve(uint32_t cpu_feature, uint32_t cpu_feature2,
	    uint32_t cpu_stdext_feature, uint32_t cpu_stdext_feature2);
where arguments have identical meaning as the kernel variables of the
same name.  The ABIs allow to use resolvers with the void or shortened
list of arguments.

Reviewed by:	jhb
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
Differential revision:	https://reviews.freebsd.org/D8448
2016-11-15 09:43:26 +00:00
Konstantin Belousov
4562cfc40e Assert that there is no unresolved symbols during rtld linking.
Reviewed by:	emaste, jhb
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
X-Differential revision:	https://reviews.freebsd.org/D8448
2016-11-15 09:40:03 +00:00
Konstantin Belousov
093513c76b Update hint to utilize user variable.
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2016-11-15 09:37:35 +00:00
John Baldwin
b5b4f379e0 Pass the correct flag to find_symdef() from _rtld_bind().
When symbol versioning was added to rtld, the boolean 'in_plt' argument
to find_symdef() was converted to a bitmask of flags.  The first flag
added was 'SYMLOOK_IN_PLT' which replaced the 'in_plt' bool.  This
happened to still work by accident as SYMLOOK_IN_PLT had the value of 1
which is the same as 'true', so there should be no functional change.

Tested on:	amd64
Reviewed by:	kan
MFC after:	2 weeks
Sponsored by:	DARPA / AFRL
2016-11-08 22:41:11 +00:00
Bryan Drewery
1eb4ec9c62 DIRDEPS_BUILD: Add some missing dirctories to the build.
Sponsored by:	EMC / Isilon Storage Division
2016-08-31 19:30:59 +00:00
Adrian Chadd
6f9dab906e [mips] flip from =v to =r - let the compiler choose a temp register.
=v is some ye olde gcc "use this specific register as the temp register"
thing that they've deprecated and clang/llvm doesn't implement.

Poked again and again by: sbruno
2016-08-25 22:32:10 +00:00
Konstantin Belousov
f214036e99 Move defines common between rtld and libsysdecode into the header,
instead of copying inline into sources.

Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2016-08-12 19:31:41 +00:00
Konstantin Belousov
09944776b5 Fill phdr and phsize for rtld object. It is needed for
dl_iterate_phdr() reporting the correct values.

PR:	211367
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2016-08-12 18:31:44 +00:00
Konstantin Belousov
20ee0f7112 Remove all remaining uses of TAILQ_FOREACH_FROM() from rtld-elf.
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2016-08-12 18:29:11 +00:00
Adrian Chadd
b812fe4d6b [mips] add support for using the MIPS user register for TLS data.
This work, originally from Stacey Son, uses the MIPS UserReg for
reading the TLS data, and will fall back to the normal syscall path
when it isn't supported.

This code dynamically patches cpu_switch() to bypass the UserReg
instruction so to avoid generating a machine exception.

Thanks to sson for the original work, and to Dan Nelson for
bringing it to date and testing it on MIPS32 with me.

Tested:

* mips64 (sson)
* mips74k (dnelson_1901@yahoo.com) - AR9344 SoC, UserReg support
* mips24k (adrian) - AR9331 SoC, no UserReg support

Obtained from:	sson, dnelson_1901@yahoo.com
2016-08-07 01:29:55 +00:00
Bryan Drewery
1c1093d6d6 Fix dlsym(RTLD_NEXT) handling to only return the next library in last library cases.
The root of the problem here is that TAILQ_FOREACH_FROM will default to
the head of the list if passed NULL, which will be the case if there are
no libraries loaded after this one.  Thus all libraries, including the
current, were iterated in that case rather than none.

This was broken in r294373.

Reviewed by:	markj (earlier version), cem, kib, ngie
MFC after:	1 week
Sponsored by:	EMC / Isilon Storage Division
Differential Revision:	https://reviews.freebsd.org/D7216
2016-07-15 19:07:00 +00:00
Bryan Drewery
e7debdcb15 Fix race for incrementally rebuilding VERSION_MAP.
The dependency is needed in PROG_FULL since only the build of PROG_FULL
is using the LDFLAGS and depending on VERSION_MAP.  This was not a problem
with MK_DEBUG_FILES==no since it only builds PROG.

This should probably be using bsd.lib.mk instead [1]

Reported by:	swills, gjb
Reviewed by:	emaste
Noted by:	rgrimes [1]
Sponsored by:	EMC / Isilon Storage Division
Approved by:	re (kib)
2016-07-03 17:28:39 +00:00
Konstantin Belousov
360ba6bc13 Fix issues found by Coverity in the rtld-elf.c:gethints().
Check that the dirlist path string specification does not cause
overflow and is fully contained in the hints file.
Check that the dirlist string is nul-terminated.
Make 'hdr' static variable, so that hdr.dirlistlen is available when
hints cached value is used on next function calls.  Reset hdr.dirlistlen
to zero if error was detected, so that allocations use reasonable size.
Use 'hints', and not 'p' in the body, since p is only initialized on the
first call.

Reported and reviewed by:	truckman (previous version)
Sponsored by:	The FreeBSD Foundation
CIDs:	1006503, 1006504, 1006676, 1008488, 1007263
MFC after:	2 weeks
2016-05-25 18:10:44 +00:00
Enji Cooper
430f7286a5 Merge ^/user/ngie/release-pkg-fix-tests to unbreak how test files are installed
after r298107

Summary of changes:

- Replace all instances of FILES/TESTS with ${PACKAGE}FILES. This ensures that
  namespacing is kept with FILES appropriately, and that this shouldn't need
  to be repeated if the namespace changes -- only the definition of PACKAGE
  needs to be changed
- Allow PACKAGE to be overridden by callers instead of forcing it to always be
  `tests`. In the event we get to the point where things can be split up
  enough in the base system, it would make more sense to group the tests
  with the blocks they're a part of, e.g. byacc with byacc-tests, etc
- Remove PACKAGE definitions where possible, i.e. where FILES wasn't used
  previously.
- Remove unnecessary TESTSPACKAGE definitions; this has been elided into
  bsd.tests.mk
- Remove unnecessary BINDIRs used previously with ${PACKAGE}FILES;
  ${PACKAGE}FILESDIR is now automatically defined in bsd.test.mk.
- Fix installation of files under data/ subdirectories in lib/libc/tests/hash
  and lib/libc/tests/net/getaddrinfo
- Remove unnecessary .include <bsd.own.mk>s (some opportunistic cleanup)

Document the proposed changes in share/examples/tests/tests/... via examples
so it's clear that ${PACKAGES}FILES is the suggested way forward in terms of
replacing FILES. share/mk/bsd.README didn't seem like the appropriate method
of communicating that info.

MFC after: never probably
X-MFC with: r298107
PR: 209114
Relnotes: yes
Tested with: buildworld, installworld, checkworld; buildworld, packageworld
Sponsored by: EMC / Isilon Storage Division
2016-05-04 23:20:53 +00:00
Pedro F. Giffuni
ec489d64bb libexec: minor spelling fixes in comments.
No functional change.
2016-05-01 19:39:23 +00:00
Pedro F. Giffuni
260111ffce rtld-elf: use our roundup2() macro when param.h is available. 2016-04-19 20:12:46 +00:00
Pedro F. Giffuni
a5d5e8dd7c rtld-elf: use NULL instead of zero for pointers. 2016-04-19 19:03:55 +00:00
Glen Barber
d60840138f MFH
Sponsored by:	The FreeBSD Foundation
2016-04-04 23:55:32 +00:00
Bryan Drewery
c0f5aeb032 WITHOUT_TOOLCHAIN: Fix build of rtld.
MK_TOOLCHAIN==no disables building and installing of pic archives.
c_pic.a is still needed for rtld though so force it to build in lib/libc
and link directly to the objdir version of it for rtld.

Somehow this has been broken since r148725.

Sponsored by:	EMC / Isilon Storage Division
2016-03-31 17:27:01 +00:00
Glen Barber
7d536dc855 MFH
Sponsored by:	The FreeBSD Foundation
2016-03-10 21:16:01 +00:00
Bryan Drewery
15c433351f DIRDEPS_BUILD: Connect MK_TESTS.
Sponsored by:	EMC / Isilon Storage Division
2016-03-09 22:46:01 +00:00
Glen Barber
42d27ee343 MFH
Sponsored by:	The FreeBSD Foundation
2016-03-02 23:53:08 +00:00
Konstantin Belousov
ca8c8dc3eb Fix handling of DT_TEXTREL for an object with more than one read-only
segment.  According to gABI spec, presence of the tag indicates that
dynamic linker must be prepared to handle relocations against any
read-only segment, not only the segment which we, somewhat arbitrary,
declared the text.

For each read-only segment, add write permission before relocs are
processed, and return to the mapping mode requested by the phdr, after
relocs are done.

Reported, tested, and reviewed by:	emaste
PR:	207631
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2016-03-02 16:36:24 +00:00
Glen Barber
52259a98ad MFH
Sponsored by:	The FreeBSD Foundation
2016-03-02 16:14:46 +00:00
Mariusz Zaborski
c501d73c7e Convert casperd(8) daemon to the libcasper.
After calling the cap_init(3) function Casper will fork from it's original
process, using pdfork(2). Forking from a process has a lot of advantages:
1. We have the same cwd as the original process.
2. The same uid, gid and groups.
3. The same MAC labels.
4. The same descriptor table.
5. The same routing table.
6. The same umask.
7. The same cpuset(1).
From now services are also in form of libraries.
We also removed libcapsicum at all and converts existing program using Casper
to new architecture.

Discussed with:		pjd, jonathan, ed, drysdale@google.com, emaste
Partially reviewed by:	drysdale@google.com, bdrewery
Approved by:		pjd (mentor)
Differential Revision:	https://reviews.freebsd.org/D4277
2016-02-25 18:23:40 +00:00
Glen Barber
72c3aa02dc MFH
Sponsored by:	The FreeBSD Foundation
2016-02-18 00:37:58 +00:00
Bryan Drewery
fb99179af4 Fix build race after r295643.
Sponsored by:	EMC / Isilon Storage Division
2016-02-17 00:30:28 +00:00
Glen Barber
c389411c8a Remove libc, librtld_db, libthr packages, and further increase
the constraints on what needs to be installed in a specific to
maintain consistency during upgrades.

Create a new clibs package containing libraries that are needed
as a bare minimum for consistency.

With much help and input from:	kib
Sponsored by:	The FreeBSD Foundation
2016-02-05 21:01:08 +00:00
Glen Barber
393303e317 Include ld-elf.so and ld-elf32.so in the librtld_db
package.

Sponsored by:	The FreeBSD Foundation
2016-02-05 02:29:41 +00:00
Glen Barber
221b349912 MFH
Sponsored by:	The FreeBSD Foundation
2016-02-02 22:27:48 +00:00
Glen Barber
43faedc133 First pass to fix the 'tests' packages.
Sponsored by:	The FreeBSD Foundation
2016-02-02 22:26:49 +00:00
Maxim Sobolev
7fd852f860 This seems like a very trivial bug that should have been squashed a long
time ago, but for some reason it was not. Basically, without this change
dlopen(3)'ing an empty .so file would just cause application to dump core
with SIGSEGV.

Make sure the file has enough data for at least the ELF header before
mmap'ing it.

Add a test case to check that dlopen an empty file return an error.

There were a separate discussion as to whether it should be SIGBUS
instead when you try to access region mapped from an empty file,
but it's definitely SIGSEGV now, so if anyone want to check that please
be my guest.
Reviewed by:	mjg, cem
MFC after:	1 week
Differential Revision:	https://reviews.freebsd.org/D5112
2016-01-30 04:16:05 +00:00
Alexander Kabaev
ef2c2a692b Do not unlock rtld_phdr_lock over callback invocations.
The dl_iterate_phdr consumer code in libgcc does not expect multiple
callbacks running concurrently. This was fixed once already in r178807,
but accidentally got reverted in r294373.
2016-01-27 20:20:37 +00:00
Ruslan Bukin
e07528700a Follow r293066 adding a generalized exec hook for RISC-V as well. 2016-01-23 11:46:52 +00:00
Alexander Kabaev
832b947305 Fix initlist_add_object invocation parameters.
The tail parameter should point to the last object for
which dependencies should be processed. In most cases,
this is the object itself.
2016-01-20 23:26:35 +00:00
Konstantin Belousov
9fee0541f2 Do not call callbacks for dl_iterate_phdr(3) with the rtld bind and
phdr locks locked.  This allows to call rtld services from the
callback, which is only reasonable for dlopen(path, RTLD_NOLOAD) to
test existence of the library in the image, and for dlsym().  The
later might still be not quite safe, due to the lazy resolution of
filters.

To allow dropping the locks around iteration in dl_iterate_phdr(3), we
insert markers to track current position between relocks.  The global
objects list is converted to tailq and all iterators skip markers,
globallist_next() and globallist_curr() helpers are added.

Reported and tested by:	davide
Reviewed by:	kan
Sponsored by:	The FreeBSD Foundation
MFC after:	3 weeks
2016-01-20 07:21:33 +00:00
Warner Losh
3dda93b9a7 Restore ABI variants now that ldconfig groks -soft. In addition, as a
transition mechanism, if we don't have /usr/libsoft, assume that soft
float ABI binaries are the default, so treat them as default binaries.
When we've fully transitioned, it will make no sense to do this stat,
and it will be removed.
2016-01-18 21:40:20 +00:00
Andrew Turner
fafb1ee7bd Remove the compat code to handle the kernel passing us an unalinged
stackpointer. Userland expects the kernel to pass it an aligned sp and
pass a pointer to the arguments in x0. The kernel side was updated in
r289502, 3 months ago.

Sponsored by:	ABT Systems Ltd
2016-01-13 15:54:17 +00:00
Ed Maste
b873436a30 Revert r293201, r293202 (rtld: populate DT_DEBUG iff DYNAMIC segment is writable)
It turns out MIPS binaries may have other oddities that can trigger a
fault at startup.

PR:		206017
Reported by:	ray
2016-01-08 00:56:41 +00:00
Warner Losh
11cf751df2 Disable abi variant hook until strangeness with packages can be sorted
out.
2016-01-05 21:20:46 +00:00
Ed Maste
16ef2e1a9b rtld: populate DT_DEBUG iff DYNAMIC segment is writable
rtld.h was accidentally missed in r293201
2016-01-05 15:55:45 +00:00
Ed Maste
7a2ff73d68 rtld: populate DT_DEBUG iff DYNAMIC segment is writable
MIPS has/had a read-only DYNAMIC segment, and uses an extra level of
indirection (through MIPS_RLD_MAP) to locate the debugger rendezvous
data.

Some linkers (e.g. LLVM's lld) may produce MIPS binaries with a writable
DYNAMIC segment, which would allow us to eventually drop a special case.

Therefore, instead of hardcoding knowledge that DYNAMIC is not writable
on MIPS just check the permissions on the segment.

Reviewed by:	kib
MFC after:	2 weeks
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D4791
2016-01-05 15:52:16 +00:00
Ed Maste
d88def534e rtld: wrap a comment to 80 columns 2016-01-05 02:21:57 +00:00
Warner Losh
c333c74aef If md_exec_hook is defined, provide a way to create the strings
for the environment variables we look up at runtime. Otherwise,
there's no way they will change, optimize it at compile time.

Differential Review: https://reviews.freebsd.org/D2718
2016-01-03 04:32:13 +00:00
Warner Losh
8fd53f4577 Create a generalized exec hook that different architectures can hook
into if they need to, but default to no action.

Differential Review: https://reviews.freebsd.org/D2718
2016-01-03 04:32:02 +00:00
Nathan Whitehorn
a4c5dfc0fa Unify the ELFv1 and ELFv2 code paths and make ELFv1 (the normal ABI) more
correct in the process.

MFC after:	2 weeks
2016-01-01 00:11:29 +00:00
Warner Losh
95b56c0eb8 Use a macro to create the names for the library path names. This will
allow later substitution at run time instead of compile time of the
environment variable name prefix.

Differential Review: https://reviews.freebsd.org/D2718
2015-12-27 23:04:12 +00:00
Ed Maste
18010b98c2 rtld: remove old XXX comment missed in r35529
Sponsored by:	The FreeBSD Foundation
2015-12-24 18:53:17 +00:00
Ruslan Bukin
4b1859c0e9 Add support for RISC-V architecture.
Reviewed by:	andrew, kib
Sponsored by:	DARPA, AFRL
Sponsored by:	HEIF5
Differential Revision:	https://reviews.freebsd.org/D4679
2015-12-24 15:47:51 +00:00
Ed Maste
66963b3cef rtld: Use common NT_FREEBSD_* note types introduced in r291909
Sponsored by:	The FreeBSD Foundation
2015-12-21 22:40:29 +00:00
Warner Losh
d1e1c4de15 Use variable names that aren't as prone to dyslexic confusion.
Suggested by: jmallet@
2015-12-18 05:45:49 +00:00
Bryan Drewery
eacae6dc66 Fix LDADD/DPADD that should be LIBADD.
Sponsored by:	EMC / Isilon Storage Division
2015-12-04 03:17:47 +00:00
Nathan Whitehorn
4cce0e9868 Follow-on to r291666: use -ffreestanding instead of -fno-builtin.
Requested by:	kib
2015-12-03 21:25:59 +00:00
Nathan Whitehorn
29ba9b6124 Provide support for ELFv2 userland if using a newer compiler (recent clang
or gcc) and binutils >= 2.24. Not enabled by default.
2015-12-03 00:10:57 +00:00
Nathan Whitehorn
50ea11fc87 Fix build on GCC 5.2 where, at least on PPC64, the compiler would "optimize"
the malloc() + memset() in the local implementation of calloc() into a call
to calloc(), helpfully turning it into an infinite loop. Clean up some
unneeded flags on PPC64 while here.

MFC after:	1 month
2015-12-03 00:06:59 +00:00
Bryan Drewery
056b7d85a4 Fix build after r291620.
"don't know how to make /Versions.def. Stop"

This was trying to define a target in bsd.symver.mk based on LIBCDIR which was
not yet defined.  Switching the order of inclusion of bsd.prog.mk and
bsd.symver.mk fixes it and seems fine.

Pointyhat to:	bdrewery
Sponsored by:	EMC / Isilon Storage Division
2015-12-01 22:50:32 +00:00
Bryan Drewery
3c89d6b0e3 Don't override LIB*DIR variables from src.libnames.mk.
In some cases switch to the LIB*SRCDIR value.

These recently were defined in r291327 and r291619.

Sponsored by:	EMC / Isilon Storage Division
2015-12-01 22:20:04 +00:00
Bryan Drewery
7fdd45b091 Use LIBEXECDIR for /usr/libexec.
MFC after:	1 week
Sponsored by:	EMC / Isilon Storage Division
2015-11-26 01:14:40 +00:00
Warner Losh
3deca56f3f Rather than using the #define for path names, indirect through a char *
variable that could change for different executable types detected.
2015-10-31 04:39:55 +00:00
Warner Losh
b2a4014cbb Move all the paths into a new path.h to centralize them. 2015-10-31 04:39:28 +00:00
Konstantin Belousov
bd56d410c4 Allow PT_NOTES segments to be located anywhere in the executable
image.

The dynamic linker still requires that program headers of the
executable or dso are mapped by a PT_LOAD segment.

Reviewed by:	emaste, jhb
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
Differential revision:	https://reviews.freebsd.org/D3871
2015-10-14 18:29:21 +00:00
Enji Cooper
b2d48be1bc Refactor the test/ Makefiles after recent changes to bsd.test.mk (r289158) and
netbsd-tests.test.mk (r289151)

- Eliminate explicit OBJTOP/SRCTOP setting
- Convert all ad hoc NetBSD test integration over to netbsd-tests.test.mk
- Remove unnecessary TESTSDIR setting
- Use SRCTOP where possible for clarity

MFC after: 2 weeks
Sponsored by: EMC / Isilon Storage Divison
2015-10-12 08:16:03 +00:00
Alexander Kabaev
b3ac02ca48 Remove some trailing space. 2015-10-09 18:39:52 +00:00
Konstantin Belousov
96cdb0ab9d Annotate arm userspace assembler sources stating their tolerance to
the non-executable stack.

Reviewed by:	andrew
Sponsored by:	The FreeBSD Foundation
2015-09-29 16:09:58 +00:00
Bryan Drewery
1508ab98e5 META_MODE: No need to fix the link in this case.
The exists(${DESTDIR}...) check runs with DESTDIR being blank.  When the
target runs it does have DESTDIR=${STAGE_OBJTOP} via bsd.sys.mk.  This
results in the first execution warning that the symlink is missing.  The
second run does run fine.  However, this chflags is not needed at all
for META_MODE/STAGING since we never had this path being a schg file
while using META_MODE.

Sponsored by:	EMC / Isilon Storage Division
2015-09-18 23:12:38 +00:00
Andrew Turner
7c81294224 Fix how we place each objects thread local data. The code used was based
on the Variant II code, however arm64 uses Variant I. The former placed the
thread pointer after the data, pointing at the thread control block, while
the latter places these before said data.

Because of this we need to use the size of the previous entry to calculate
where to place the current entry. We also need to reserve 16 bytes at the
start for the thread control block.

This also fixes the value of TLS_TCB_SIZE to be correct. This is the size
of two unsigned longs, i.e. 2 * 8 bytes.

While here remove the bogus adjustment of the pointer in the
R_AARCH64_TLS_TPREL64 case. It should be the offset of the data relative
to the thread pointer, including the thread control block.

Sponsored by:	ABT Systems Ltd
2015-09-01 15:57:03 +00:00
Andrew Turner
878165d2ef Ensure we use calculate_first_tls_offset, even if the main program doesn't
have TLS program header. This is needed on architectures with Variant I
tls, that is arm, arm64, mips, and powerpc. These place the thread control
block at the start of the buffer and, without this, this data may be
trashed.

This appears to not be an issue on mips or powerpc as they include a second
adjustment to move the thread local data, however this is on arm64 (with a
future change to fix placing this data), and should be on arm. I am unable
to trigger this on arm, even after changing the code to move the data
around to make it more likely to be hit. This is most likely because my
tests didn't use the variable in offset 0.

Reviewed by:	kib
MFC after:	1 week
Sponsored by:	ABT Systems Ltd
2015-09-01 15:43:56 +00:00
Eric van Gyzen
ddab052725 Disable SSE in libthr
Clang emits SSE instructions on amd64 in the common path of
pthread_mutex_unlock.  If the thread does not otherwise use SSE,
this usage incurs a context-switch of the FPU/SSE state, which
reduces the performance of multiple real-world applications by a
non-trivial amount (3-5% in one application).

Instead of this change, I experimented with eagerly switching the
FPU state at context-switch time.  This did not help.  Most of the
cost seems to be in the read/write of memory--as kib@ stated--and
not in the #NM handling.  I tested on machines with and without
XSAVEOPT.

One counter-argument to this change is that most applications already
use SIMD, and the number of applications and amount of SIMD usage
are only increasing.  This is absolutely true.  I agree that--in
general and in principle--this change is in the wrong direction.
However, there are applications that do not use enough SSE to offset
the extra context-switch cost.  SSE does not provide a clear benefit
in the current libthr code with the current compiler, but it does
provide a clear loss in some cases.  Therefore, disabling SSE in
libthr is a non-loss for most, and a gain for some.

I refrained from disabling SSE in libc--as was suggested--because
I can't make the above argument for libc.  It provides a wide variety
of code; each case should be analyzed separately.

https://lists.freebsd.org/pipermail/freebsd-current/2015-March/055193.html

Suggestions from:	dim, jmg, rpaulo
Approved by:	kib (mentor)
MFC after:	2 weeks
Sponsored by:	Dell Inc.
2015-08-05 12:53:55 +00:00
Andrew Turner
3cf00397ad Add on the addend when in the R_AARCH64_ABS64 and R_AARCH64_GLOB_DAT cases.
This fixes at least sshd, and some of the boehm-gc tests.

Sponsored by:	ABT Systems Ltd
2015-07-05 11:42:01 +00:00
Andrew Turner
aeb8eeb590 Save & restore the floating-pont argument registers before calling
_rtld_bind. The compiler may generate code using these registers and not
save them. Unfortunately, as we make use of libc, we are unable to disallow
rtld from using floating-point register without also doing the same for the
parts of libc we use, or by limiting what _rtld_bind is able to call.

Obtained from:	ABT Systems Ltd
Sponsored by:	The FReeBSD Foundation
2015-07-02 14:00:07 +00:00
Andrew Turner
ff8a3cb6e2 Also save x8. It may be passed into a function as the indirect result
location pointer when the return value doesn't fit in a register, e.g. when
returning a struct.

Obtained from:	ABT Systems Ltd
Sponsored by:	The FreeBSD Foundation
2015-06-23 10:32:26 +00:00
Andrew Turner
65706c12b2 Add a workaround to correctly align the stack before calling into C code.
When enough time has passed for users to update their userland the kernel
fix will be applied. This will change the ABI to have x0 point to the args
and sp be correctly aligned.

It is expected this compatibility code can be removed when the kernel and
qemu usermode emulation have both been updated for the new ABI.

This fixes clang failures, and most likely other crashes.

Obtained from:	ABT Systems Ltd
Sponsored by:	The FreeBSD Foundation
2015-06-22 19:43:08 +00:00
Simon J. Gerraty
2ef6d5a7b9 new depends 2015-06-16 23:37:19 +00:00
Simon J. Gerraty
ccfb965433 Add META_MODE support.
Off by default, build behaves normally.
WITH_META_MODE we get auto objdir creation, the ability to
start build from anywhere in the tree.

Still need to add real targets under targets/ to build packages.

Differential Revision:       D2796
Reviewed by: brooks imp
2015-06-13 19:20:56 +00:00
Simon J. Gerraty
44d314f704 dirdeps.mk now sets DEP_RELDIR 2015-06-08 23:35:17 +00:00
Simon J. Gerraty
98e0ffaefb Merge sync of head 2015-05-27 01:19:58 +00:00
Ed Maste
244f6b3ec3 Remove historical GNUC test
The requirement is for a GCC-compatible compiler and not necessarily
GCC itself. However, we currently expect any compiler used for building
the whole of FreeBSD to be GCC-compatible and many things will break if
not; there's no longer a need to have an explicit test for this in rtld.

Reviewed by:	imp, kib
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D2422
2015-05-06 15:29:11 +00:00
Konstantin Belousov
b3ff02bf85 Change interpretation of the DF_ORIGIN and DF_1_ORIGIN flags.
According to standard, the presence of the flags only means that the
object path must be resolved at the time object loading, instead of my
reading that the flag is required to enable token substitution at all.

The consequence is that -z origin linker flag is no longer required
for the token substitution in the run/rpath or the needed library
soname.  It is only recommended if token substition is needed at
dlopen(3) time, since namecache might drop the required entries at the
time of resolution.

Found, reviewed and tested by:	emaste
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2015-04-27 18:41:31 +00:00
Craig Rodrigues
d5fec48956 Support file verification in MAC.
* Add VCREAT flag to indicate when a new file is being created
* Add VVERIFY to indicate verification is required
* Both VCREAT and VVERIFY are only passed on the MAC method vnode_check_open
  and are removed from the accmode after
* Add O_VERIFY flag to rtld open of objects
* Add 'v' flag to __sflags to set O_VERIFY flag.

Submitted by:		Steve Kiernan <stevek@juniper.net>
Obtained from:		Juniper Networks, Inc.
GitHub Pull Request:	https://github.com/freebsd/freebsd/pull/27
Relnotes:		yes
2015-04-22 01:54:25 +00:00
Andrew Turner
899b27a318 Use the correct value to get the offset of the objects tls data.
Sponsored by:	The FreeBSD Foundation
2015-04-15 14:20:12 +00:00
Konstantin Belousov
3de3815469 Implement support -z global linker option. It marks the shared object
as always participating in the global symbols namespace, regardless of
the way the object was brought into the process address space.

Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2015-04-15 08:16:34 +00:00
Ed Maste
ba29f2ddfb MIPS rtld: report missing symbol rather than segfaulting
This is only an interim fix; MIPS should be using the MI code instead,
which does not have this issue.

Reviewed by:	imp
Differential Revision:	https://reviews.freebsd.org/D661
2015-04-05 14:06:11 +00:00
Andrew Turner
a97120d61e Add support for thread local storage on arm64 to the runtime linker. The
ABI specifies that, for R_AARCH64_TLSDESC relocations, we use the symbol
value, addend, and object tls offset to calculate the offset from the tls
base. We then cache this value for future reference.

Differential Revision:	https://reviews.freebsd.org/D2183
Reviewed by:	kib
Sponsored by:	The FreeBSD Foundation
2015-04-03 09:35:52 +00:00
Ed Maste
29f36d0bf8 Make die available as rtld_die for use by MD relocation code
Reviewed by:	kib
Sponsored by:	The FreeBSD Foundation
Differential Revision:	https://reviews.freebsd.org/D2213
2015-04-02 21:35:36 +00:00
Ed Maste
f5f299c30b Correct copyright typo 2015-03-31 12:53:07 +00:00
Andrew Turner
047c6e3ae6 Add the arm64 code to the runtime linker. It's not able to be built as we
still need libc_pic for a few things, but this is expected to be ready
soon.

Differential Revision:	https://reviews.freebsd.org/D2136
Reviewed by:	kib
Sponsored by:	The FreeBSD Foundation
2015-03-31 09:51:19 +00:00
Konstantin Belousov
0c4f9ecde3 Change compiler setting to make default visibility of the symbols for
rtld on x86 to be hidden.  This is a micro-optimization, which allows
intrinsic references inside rtld to be handled without indirection
through PLT.  The visibility of rtld symbols for other objects in the
symbol namespace is controlled by a version script.

Reviewed by:	kan, jilles
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2015-03-29 18:53:21 +00:00
Jung-uk Kim
0461326c01 When a file is executed and the path starts with `/', AT_EXECPATH is set
without any translation.  If the file is a symbolic link, $ORIGIN may not be
expanded to the actual origin.  Use realpath(3) to properly expand $ORIGIN
to its absolute path.

Reviewed by:	kib
MFC after:	1 week
2015-02-27 19:05:23 +00:00
Konstantin Belousov
803fc2ca26 Use powerof2(). Remove single-use variable.
Submitted by:	Conrad Meyer
Differential Revision:	https://reviews.freebsd.org/D1724
MFC after:	1 week
2015-01-30 15:32:35 +00:00
Dag-Erling Smørgrav
4ac1e0a9fc Allow tracing dlfunc() / dlsym() events.
MFC after:	1 week
2015-01-25 12:11:50 +00:00
Justin Hibbits
8c29a9824b Apply r246556 to powerpc:
Avoid use of register variables, which some compilers (e.g. clang)
don't like. It makes the code a little clearer as well.

This allows a clang 3.5 built powerpc world to run (tested in a jail).

MFC after:	1 week
2015-01-06 03:49:22 +00:00
Konstantin Belousov
0c5cba543b Do not erronously export 'openat' symbol from rtld.
The symbol leaked after r276630 since lib/libc/sys/openat.c defines
versions for openat using .symver (version script cannot assign two
versions to one symbol), and rtld uses openat.  Instead, directly use
__sys_openat().

Reported and tested by:	antoine
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2015-01-04 00:33:41 +00:00
Konstantin Belousov
0e521992a4 Add rtld private interface for dso to detect dynamic loading
vs. static linking.

Tested by:	pho, antoine (exp-run)
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2015-01-03 18:09:53 +00:00
Dimitry Andric
918428b837 Fix the following -Werror warning from clang 3.5.0, while building
rtld-elf for powerpc 32 bit:

libexec/rtld-elf/powerpc/reloc.c:486:6: error: taking the absolute value of unsigned type 'Elf_Addr' (aka 'unsigned int') has no effect [-Werror,-Wabsolute-value]
        if (abs(offset) < 32*1024*1024) {     /* inside 32MB? */
            ^
libexec/rtld-elf/powerpc/reloc.c:486:6: note: remove the call to 'abs' since unsigned values cannot be negative
        if (abs(offset) < 32*1024*1024) {     /* inside 32MB? */
            ^~~
1 error generated.

Cast 'offset' to int, since that was intended, and should be safe to do
on architectures with 32-bit two's complement ints.

Reviewed by:	kib
Differential Revision: https://reviews.freebsd.org/D1387
2014-12-28 19:55:44 +00:00
John Baldwin
9abeb029d4 The runtime linker needs to include a path to itself in the link map
it exports to the debugger.  It currently has two choices: it can use
a compiled-in path (/libexec/ld-elf.so.1) or it can use the path stored
in the interpreter path in the binary being executed.  The runtime linker
currently prefers the second.  However, this is usually wrong for compat32
binaries since the binary specifies the path of rtld on a 32-bit system
(/libexec/ld-elf.so.1) instead of the actual path (/libexec/ld-elf32.so.1).
For now, always assume the compiled in path (/libexec/ld-elf32.so.1) as
the rtld path and ignore the path in the binary for the 32-bit runtime
linker.

Differential Revision:	https://reviews.freebsd.org/D1236
Reviewed by:	kib
2014-12-02 16:22:08 +00:00
Baptiste Daroussin
ee5a34ecba Convert to LIBADD
Reduce overlinking
2014-11-25 21:18:18 +00:00
Ed Maste
294246bb7d Revert r274772: it is not valid on MIPS
Reported by:	sbruno
2014-11-25 03:50:31 +00:00
Ed Maste
688fd61ae8 Use canonical __PIC__ flag
It is automatically set when -fPIC is passed to the compiler.

Reviewed by:	dim, kib
Sponsored by:	The FreeBSD Foundation
Differential Revision: https://reviews.freebsd.org/D1179
2014-11-21 02:05:48 +00:00
Simon J. Gerraty
9268022b74 Merge from head@274682 2014-11-19 01:07:58 +00:00
Ed Maste
54ac10780f Always return pathname in dl_iterate_phdr's dlpi_name, as Linux does
Linux LD_ITERATE_PHDR(3):
    The dlpi_name field is a null-terminated string giving the
    pathname from which the shared object was loaded.

That functionality is much more useful than returning just the short
name.

Approved by:	kan
Sponsored by:	The FreeBSD Foundation
2014-10-09 20:39:18 +00:00
Andrew Turner
6d4766c1b8 Remove MK_ARM_EABI, the armeb issues have been fixed. The code to support
the oabi is still in the tree, but it is expected this will be removed
as developers work on surrounding code.

With this commit the ARM EABI is the only supported supported ABI by
FreeBSD on ARMa 32-bit processors.

X-MFC after:	never
Relnotes:	yes
Differential Revision: https://reviews.freebsd.org/D876
2014-10-01 08:26:51 +00:00
Konstantin Belousov
d3b06cf2be Document the whole settings needed to build a debug version of rtld.
Sponsored by:	The FreeBSD Foundation
MFC after:	3 days
2014-08-29 10:44:58 +00:00
Konstantin Belousov
74b0daf4f9 Optimize r270798, only do the second pass over non-plt relocations
when the first pass found IFUNCs.

Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2014-08-29 10:43:56 +00:00
Konstantin Belousov
14c3564759 IFUNC symbol type shall be processed for non-PLT relocations,
e.g. when a global variable is initialized with a pointer to ifunc.
Add symbol type check and call resolver for STT_GNU_IFUNC symbol types
when processing non-PLT relocations, but only after non-IFUNC
relocations are done.  The two-phase proceessing is required since
resolvers may reference other symbols, which must be ready to use when
resolver calls are done.

Restructure reloc_non_plt() on x86 to call find_symdef() and handle
IFUNC in single place.

For non-x86 reloc_non_plt(), check for call for IFUNC relocation and
do nothing, to avoid processing relocs twice.

PR:	193048
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2014-08-29 09:29:10 +00:00
Konstantin Belousov
e404dc33e2 Remove stray newline. 2014-08-27 00:48:09 +00:00
Enji Cooper
35829c84f1 Fix "make checkdpadd" by "spoofing" DPADD
Approved by: jmmv (mentor)
Phabric: D631
PR: 192769
2014-08-26 09:01:11 +00:00
Pedro F. Giffuni
0fa46a4231 Always check the limits of array index variables before using them.
Obtained from:	DragonFlyBSD
MFC after:	1 week
2014-08-21 02:40:33 +00:00
Bryan Drewery
5608fd23c2 Revert r267233 for now. PIE support needs to be reworked.
1. 50+% of NO_PIE use is fixed by adding -fPIC to INTERNALLIB and other
   build-only utility libraries.
2. Another 40% is fixed by generating _pic.a variants of various libraries.
3. Some of the NO_PIE use is a bit absurd as it is disabling PIE (and ASLR)
   where it never would work anyhow, such as csu or loader. This suggests
   there may be better ways of adding support to the tree. Many of these
   cases can be fixed such that -fPIE will work but there is really no
   reason to have it in those cases.
4. Some of the uses are working around hacks done to some Makefiles that are
   really building libraries but have been using bsd.prog.mk because the code
   is cleaner. Had they been using bsd.lib.mk then NO_PIE would not have
   been needed.

We likely do want to enable PIE by default (opt-out) for non-tree consumers
(such as ports). For in-tree though we probably want to only enable PIE
(opt-in) for common attack targets such as remote service daemons and setuid
utilities. This is also a great performance compromise since ASLR is expected
to reduce performance. As such it does not make sense to enable it in all
utilities such as ls(1) that have little benefit to having it enabled.

Reported by:	kib
2014-08-19 15:04:32 +00:00
Simon J. Gerraty
ee7b0571c2 Merge head from 7/28 2014-08-19 06:50:54 +00:00
Enji Cooper
fd5c99b51e Similar to r269506, fix LIBDIR to not duplicate TESTSDIR
Phabric: D536
Reviewed by: jmmv
Approved by: jmmv (mentor)
Sponsored by: EMC / Isilon Storage Division
2014-08-05 18:09:39 +00:00
Enji Cooper
522da0b0ad Remove unnecessary .PATH directive
All of the sources for the tests are contained in the
current working directory and the subdirectories

Phabric: D537
Reviewed by: jmmv
Approved by: jmmv (mentor)
Sponsored by: EMC / Isilon Storage Division
2014-08-05 18:05:31 +00:00
Enji Cooper
2db8752cef Fix BINDIR to not duplicate "${TESTSDIR}
This should fix 'make release' with MK_TESTS != no

Phabric: D525 (part of a larger patch)

Reviewed by: jmmv
Approved by: jmmv (co-mentor)
2014-08-04 05:50:21 +00:00
Enji Cooper
07014efe94 Move a -L argument from LDADD to LDFLAGS
Phabric: D525 (part of a larger patch)

Reviewed by: jmmv
Approved by: jmmv (co-mentor)
2014-08-04 05:49:13 +00:00
Enji Cooper
35e8923e7e Fix a -Wsecurity warning with clang
Phabric: D525 (part of a larger patch)

Reviewed by: jmmv
Approved by: jmmv (co-mentor)
2014-08-04 05:46:10 +00:00
Enji Cooper
1a49685c28 Remove hardcoded path to TESTSDIR (Makefile, ld_library_pathfds.c) at
build time by using atf_tc_get_config_var(tc, "srcdir"))

This will allow end-users to move the binaries to different locations
after they've been built without having to rebuild the binaries with
the new paths

Phabric: D525 (part of a larger patch)

Reviewed by: jmmv
Approved by: jmmv (co-mentor)
2014-08-04 05:45:09 +00:00
Julio Merino
2504a6af6b libpythagoras needs libm.
This fixes "make tinderbox" failures on various architectures when
WITH_TESTS=yes is enabled.  Problem introduced in r267679.
2014-07-16 16:42:58 +00:00
Marcel Moolenaar
e7d939bda2 Remove ia64.
This includes:
o   All directories named *ia64*
o   All files named *ia64*
o   All ia64-specific code guarded by __ia64__
o   All ia64-specific makefile logic
o   Mention of ia64 in comments and documentation

This excludes:
o   Everything under contrib/
o   Everything under crypto/
o   sys/xen/interface
o   sys/sys/elf_common.h

Discussed at: BSDcan
2014-07-07 00:27:09 +00:00
Andrew Turner
0685d955d6 Align the stack in _rtld_bind_start. Normally this is called with the
correct stack alignment, however when we have a leaf function that uses
thread local storage it calls __aeabi_read_tp to get the thread pointer.
Neither GCC or clang see this as a function call so will align the stack
to a 4-byte boundary. This may be a problem as _rtld_bind expects to be
on an 8-byte boundary.

The solution is to store a copy of the stack pointer and force the
alignment before calling _rtld_bind.

This fixes a problem with armeb where applications would crash in odd ways.
It should also remove the need for a local patch to clang to force the
stack alignment to an 8-byte boundary, even for leaf functions. Further
testing will be needed before reverting this local change to clang as we
may rely on it in other places.

Reviewed by:	jmg@
2014-07-06 10:24:06 +00:00
Marcel Moolenaar
97ef768914 Fix r264346 for ia64. We need to allocate memory for the function
descriptors in order to relocate RTLD itself. To allocate memory,
we need the pagesizes array initialized, but that happens after
RTLD is relocated. This ordering is important for amd64, but it's
opposite of what ia64 needs. Handle this conflict with the define
called RTLD_INIT_PAGESIZES_EARLY. When defined, obtain the page
sizes before relocating rtld, otherwise do it after.
2014-07-02 22:04:12 +00:00
Joel Dahl
df2d82e003 mdoc: remove superfluous paragraph macros. 2014-06-23 18:40:21 +00:00
Jonathan Anderson
6b22f423cf Test RTLD's new LD_LIBRARY_PATH_FDS variable.
Test LD_LIBRARY_PATH_FDS by linking a binary that requires a shared
library that isn't in any of the usual search paths.  Ensure this fails
when we don't supply LD_LIBRARY_PATH_FDS or we pass invalid information
in it.  Ensure it works when we pass the correct directory in various
places in the variable.

Approved by:	rwatson (mentor)
MFC after:	3 weeks
Sponsored by:	DARPA/AFRL
2014-06-20 17:14:59 +00:00
Jonathan Anderson
02d3b38e0a Add the LD_LIBRARY_PATH_FDS environmental variable.
This variable allows the loading of shared libraries via directory descriptors
rather than via library paths.  If LD_LIBRARY_PATH_FDS=3:4:12, the directories
represented by file descriptors 3, 4 and 12 will searched for shared libraries
before the normal path-based mechanisms are used.  This allows us to execute
unprivileged binaries from within a Capsicum sandbox even if they require
shared libraries.

Approved by:	rwatson (mentor)
Reviewed by:	kib
MFC after:	3 weeks
Sponsored by:	DARPA/AFRL
2014-06-20 17:08:32 +00:00
Bryan Drewery
864c53ead8 In preparation for ASLR [1] support add WITH_PIE to support building with -fPIE.
This is currently an opt-in build flag. Once ASLR support is ready and stable
it should changed to opt-out and be enabled by default along with ASLR.

Each application Makefile uses opt-out to ensure that ASLR will be enabled by
default in new directories when the system is compiled with PIE/ASLR. [2]

Mark known build failures as NO_PIE for now.

The only known runtime failure was rtld.

[1] http://www.bsdcan.org/2014/schedule/events/452.en.html
Submitted by:		Shawn Webb <lattera@gmail.com>
Discussed between:	des@ and Shawn Webb [2]
2014-06-08 17:29:31 +00:00
Konstantin Belousov
1c70d00733 Right now, the rtld prefork hook locks the rtld bind lock in the read
mode.  This allows the binder to be functional in the child after the
fork (assuming no lazy loading of a filter is needed), but other rtld
services which require write lock on rtld_bind_lock cause deadlock, if
called by child.

Change the _rtld_atfork() to lock the bind lock in write mode, making
the rtld fully functional after the fork.

Pre-resolve the symbols which are called by the libthr' fork()
interposer, since dynamic resolution causes deadlock due to the
rtld_bind_lock already owned in the write mode.

Reported and tested by:	pho
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2014-05-24 10:23:06 +00:00
Konstantin Belousov
490c68de98 Fix LD_LIBMAP.
The r232862 passed the pointer to end of string to lmc_parse() and free().

Submitted by:	Wolfgang Jenkner <wjenkner@inode.at>
MFC after:	1 week
2014-05-18 17:14:08 +00:00
Simon J. Gerraty
cc3f4b9965 Merge from head 2014-05-08 23:54:15 +00:00
Mark Johnston
7a61fc5a8e - Export the function added in r265456 rather than the non-existent
_rtld_debug_postinit(). [1]
- Use __compiler_membar() instead of inline asm in _r_debug_state() and
  _r_debug_postinit(). [2]

Pointy hat to:	markj [1]
Reported by:	attilio [2]
Discussed with:	kib
X-MFC-With:	r265456
2014-05-07 17:21:22 +00:00
Mark Johnston
a8509eb20e Add a postinit debugger hook to rtld. This will be used by dtrace(1) to halt
the victim process before its entry point is called, at which point probes
and DOF data are registered with the kernel. The r_debug_state hook cannot
be used for this purpose, as it is called before the program's init routines
are invoked and in particular before DOF data is registered (via drti.o).

Reviewed by:	kib
MFC after:	2 weeks
2014-05-06 18:07:58 +00:00
Warner Losh
c6063d0da8 Use src.opts.mk in preference to bsd.own.mk except where we need stuff
from the latter.
2014-05-06 04:22:01 +00:00
Simon J. Gerraty
3b8f084595 Merge head 2014-04-28 07:50:45 +00:00
Konstantin Belousov
8cc5663495 Add dwarf annotations to the amd64 _rtld_bind_start to allow debuggers
to unwind around the calls from PLT to binder.

Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2014-04-14 22:44:50 +00:00
Alan Cox
ea8577c712 Before calling mmap() on a shared library's text and data sections, rtld
first calls mmap() with the arguments PROT_NONE and MAP_ANON to reserve a
single, contiguous range of virtual addresses for the entire shared library.
Later, rtld calls mmap() with the the shared library's file descriptor
and the argument MAP_FIXED to place the text and data sections within the
reserved range.  The rationale for mapping shared libraries in this way is
explained in the commit message for Revision 190885.  However, this approach
does have an unintended, negative consequence.  Since the first call to
mmap() specifies MAP_ANON and not the shared library's file descriptor, the
kernel has no idea what alignment the vm object backing the file prefers.
As a result, the reserved range's alignment is unlikely to be the same as
the vm object's, and so mapping with superpages becomes impossible.  To
address this problem, this revision adds the argument MAP_ALIGNED_SUPER to
the first call to mmap() if the text section is larger than the smallest
superpage size.

To determine if the text section is larger than the smallest superpage
size, rtld must always fetch the page size information.  As a result, the
private code for fetching the base page size in rtld's builtin malloc is
redundant.  Eliminate it.  Requested by: kib

Tested by:	zbb (on arm)
Reviewed by:	kib (an earlier version)
Discussed with:	jhb
2014-04-11 16:55:25 +00:00
David Xu
eab68f795a Increase alignment to size of pointer if the alignment is too small.
Some modules do not align data at least to size of pointer, they uses a
smaller alignment, but our pointer should be aligned to its native
boundary, otherwise on some platforms, hardware alignment checking
will cause bus error.
2014-02-22 11:06:48 +00:00
David Xu
209782e06f malloc_aligned() may not leave enough space for pointer to allocated memory,
saving the pointer will overwrite bytes belongs to another memory block
unexpectly, to fix the problem, use (allocated address + sizeof(void *)) as
initial value, and slip to next aligned address, so maximum extra bytes is
sizeof(void *) + align - 1.

Tested by: Andre Albsmeier < mail at ma17 dot ata dot myota dot orgndre >
2014-02-21 03:36:16 +00:00
Christian Brueffer
5efaea4cc6 Remove the 3rd clause ("advertising clause") of the BSD license as
permitted by the University of Berkeley on July 22, 1999.

Reviewed by:	imp
MFC after:	1 week
2014-02-17 22:27:32 +00:00
Ed Schouten
37656b872b Replace LIBGCC by LIBCOMPILER_RT.
We now use libcompiler_rt on all platforms now. Instead of referring
directly to -lgcc and LIBGCC, use -lcompiler_rt and LIBCOMPILER_RT.
2014-01-18 14:22:56 +00:00
Konstantin Belousov
6cd2b1dc63 Cast Elf_Addr to void * to match the free_aligned() argument type.
Found by:	gcc
Sponsored by:	The FreeBSD Foundation
MFC after:	6 days
2013-12-07 15:49:16 +00:00
Konstantin Belousov
16a93df7eb For variant II static TLS, properly align tls segments. Pre-calculate
the max required alignment for the static tls segments, and honor it
when carving the pieces for next module, from the static space.  Use
aligned allocator to get properly-aligned dynamic blocks.

Reported by:	dt71@gmx.com
Reviewed by:	kan
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2013-12-06 21:39:45 +00:00
Konstantin Belousov
dfe296c43a Build an allocator for the aligned memory on top of the rtld-private
malloc.

Reviewed by:	kan
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
2013-12-06 21:30:31 +00:00
Mark Johnston
7a89ddd40f Include rtld itself when iterating over loaded ELF objects in
dl_iterate_phdr(3).

Reviewed by:	kib
2013-11-07 20:45:50 +00:00
Simon J. Gerraty
3caf0790a8 Merge head@256284 2013-10-13 02:35:19 +00:00
Konstantin Belousov
3cf98c19e8 Implement support for the interpose dso flag.
Requested by:	bf
Reviewed by:	kan
Sponsored by:	The FreeBSD Foundation
MFC after:	1 week
Approved by:	re (glebius)
2013-10-07 08:19:30 +00:00
Ed Maste
d24aca1b00 Populate .rld_map on MIPS for debuggers
On MIPS the .dynamic section is read-only, so the pointer to rtld
information for debuggers cannot be stored there (in DT_DEBUG).
Instead, a special section .rld_map is used.

Sponsored by:	DARPA, AFRL
Approved by:	re (delphij)
2013-10-02 02:32:58 +00:00
Dag-Erling Smørgrav
8182b3bee1 Make the directory mapping functionality, which was previously only
available in 32-bit compatibility mode, unconditional.

Overhaul the man page, which had evolved more by accretion than by design.

Approved by:	re (gjb)
MFC after:	3 weeks
2013-09-21 21:03:52 +00:00
Simon J. Gerraty
d1d0158641 Merge from head 2013-09-05 20:18:59 +00:00
Andriy Gapon
a29cc9a34b Revert r253748,253749
This WIP should not have been committed yet.

Pointyhat to:	avg
2013-07-28 18:44:17 +00:00
Andriy Gapon
c722ec3a51 remove needless inclusion of machine/cpu.h in userland
MFC after:	21 days
2013-07-28 18:35:43 +00:00
Konstantin Belousov
3c9cb0c6c9 Properly terminate the result string for intermediate results, to
allow the final strcpy() to start at the intended place.

Reported and tested by:	pgj
Pointy hat to:	kib
MFC after:	3 days
2013-04-29 21:12:25 +00:00
Konstantin Belousov
32e1d8010b The origin_subst_one() function limits the length of the string to
PATH_MAX after the token substitution.  This is wrong, because
origin_subst_one() performs the substitution on the whole rpath and
similar strings, which contain several pathes separated by colon.  As
result, long (but correct) rpath consisting of many path elements is
rejected by the function.

Correct the problem by rewriting the origin_subst_one() to perform two
passes, first pass to calculate the number of substitutions to be
performed, and second pass to generate the resulting string.  Second
pass allocates the memory for the result based on the count from the
first pass, without enforcing a limit.

Reported and tested by:	pgj
Sponsored by:	The FreeBSD Foundation
MFC after:	2 weeks
2013-04-15 20:06:56 +00:00
Simon J. Gerraty
69e6d7b75e sync from head 2013-04-12 20:48:55 +00:00
Tijl Coosemans
157895135a Map libraries linked with -Ttext-segment=base_addr at base_addr.
Normal libraries have base address 0 and are unaffected by this change.

PR:		176216
Submitted by:	Damjan Jovanovic <damjan.jov@gmail.com>
Reviewed by:	kib
MFC after:	1 week
2013-02-27 09:34:09 +00:00
Simon J. Gerraty
f5f7c05209 Updated dependencies 2013-02-16 01:23:54 +00:00
Nathan Whitehorn
746ae9df1f Avoid use of register variables, which some compilers (e.g. clang)
don't like. It makes the code a little clearer as well.

MFC after:	1 week
2013-02-08 17:44:44 +00:00
David E. O'Brien
d9a447559b Sync with HEAD. 2013-02-08 16:10:16 +00:00
Andrew Turner
de2be60c4f When building for ARM EABI link against libgcc for the __aeabi_* functions. 2013-01-19 04:34:33 +00:00
Pawel Jakub Dawidek
456b64c443 Use absolute path for /usr/libexec/ld-elf.so.1 symlink.
Requested by:	kan, kib

Use -h flags for chflags, so we won't remove 'schg' flag from system's
/libexec/ld-elf.so.1.

MFC after:	2 weeks
2012-12-04 14:36:01 +00:00
Pawel Jakub Dawidek
f31c1e3fd3 Do not change entire BINDIR, it might be needed later, just change
symlink target.

MFC after:	2 weeks
2012-12-04 12:51:33 +00:00
Pawel Jakub Dawidek
dee6306480 Change /usr/libexec/ld-elf.so.1 to point at ../../libexec/ld-elf.so.1
instead of /libexec/ld-elf.so.1. Below in the Makefile we execute
'chflags noschg ${DESTDIR}/usr/libexec/ld-elf.so.1', which follows
symlink and removes 'schg' flag from system's /libexec/ld-elf.so.1
instead of the one in DESTDIR. It is also more friendly to use
replative paths in symlink in case of jail/chroot environments.

Obtained from:	WHEEL Systems
MFC after:	2 weeks
2012-12-04 12:39:26 +00:00
Jilles Tjoelker
e194282943 rtld: Fix fd leak with parallel dlopen and fork/exec.
Rtld did not set FD_CLOEXEC on its internal file descriptors; therefore,
such a file descriptor may be passed to a process created by another thread
running in parallel to dlopen() or fdlopen().

No other threads are expected to be running during parsing of the hints
and libmap files but the file descriptors need not be passed to child
processes so add O_CLOEXEC there as well.

This change will break fdlopen() (as used by OpenPAM) on kernels without
F_DUPFD_CLOEXEC (added in July). Note that running new userland on old
kernels is not supported.

Reviewed by:	kib
2012-11-04 21:42:24 +00:00
Simon J. Gerraty
23090366f7 Sync from head 2012-11-04 02:52:03 +00:00
Konstantin Belousov
1a4f1f697c Do not reference z_nodeflib for !objgiven case, thus fixing LD_PRELOAD
for a non-absolute path.

PR:	bin/171604
MFC after:	3 days
2012-09-19 05:11:25 +00:00
Marcel Moolenaar
7750ad47a9 Sync FreeBSD's bmake branch with Juniper's internal bmake branch.
Requested by: Simon Gerraty <sjg@juniper.net>
2012-08-22 19:25:57 +00:00
Alexander Kabaev
5763679b4d Do not call process_nodelete with NULL object pointer.
The place where the function is called can be reached if object loading
and relocation fails too, in which case obj pointer will be NULL. Do not
call process_nodelete then, or crash will follow.

Pointy hat to: kan
2012-08-20 23:43:03 +00:00
Oleksandr Tymoshenko
c9e95645f6 Merging of projects/armv6, part 2
Handle TLS for ARMv6 and ARMv7
2012-08-15 03:07:41 +00:00
Alexander Kabaev
207eee57b1 Pospone the DF_1_NODELETE processing until object DAG is fully loaded.
Trying to up the reference from the load loop risks missing dependencies
that have not been loaded yet.

MFC afer: 1 week
Reported by: nox
Reviewd by: kib
2012-08-14 13:28:30 +00:00
Andrew Turner
782b05f96b Ensure we align the stack to 8 bytes in rtld.
This is not strictly required with the current ABI but will be when we
switch to the ARM EABI. The aapcs requires the stack to be 4 byte aligned
at all times and 8 byte aligned when calling a public subroutine where the
current ABI only requires sp to be a multiple of 4.
2012-08-04 05:30:20 +00:00
Alexander Kabaev
d958a71be2 Parse notes only after object structure had been allocated.
Reported by: kargl
Reviewed by: kib (sans whitespace)
2012-08-03 17:04:41 +00:00
Konstantin Belousov
bca2f6239d Import the DragonFly BSD commit 4f0bc915b65fcf5a23214f6d221d65c80be68ad4
by John Marino <draco@marino.st>, with the following (edited) commit
message
Date: Sat, 24 Mar 2012 06:40:50 +0100
Subject: [PATCH 1/1] rtld: Implement DT_RUNPATH and -z nodefaultlib

DT_RUNPATH is incorrectly being considered as an alias of DT_RPATH.  The
purpose of DT_RUNPATH is to have two different types of rpath: one that
can be overridden by the environment variable LD_LIBRARY_PATH and one that
can't.  With the currently implementation, LD_LIBRARY_PATH will always
trump any embedded rpath or runpath tags.

Current path search order by rtld:
==================================
LD_LIBRARY_PATH
DT_RPATH / DT_RUNPATH (always the same)
ldconfig hints file (default: /var/run/ld-elf.so.hints)
/usr/lib

New path search order by rtld:
==============================
DT_RPATH of the calling object if no DT_RUNPATH
DT_RPATH of the main binary if no DT_RUNPATH and binary isn't calling obj
LD_LIBRARY_PATH
DT_RUNPATH
ldconfig hints file
/usr/lib

The new path search matches how the linux runtime loader works.  The other
major added feature is support for linker flag "-z nodefaultlib".  When
this flag is passed to the linker, rtld will skip all references to the
standard library search path ("/usr/lib" in this case but it could handle
more color delimited paths) except in DT_RPATH and DT_RUNPATH.

New path search order by rtld with -z nodefaultlib flag set:
============================================================
DT_RPATH of the calling object if no DT_RUNPATH
DT_RPATH of the main binary if no DT_RUNPATH and binary isn't calling obj
LD_LIBRARY_PATH
DT_RUNPATH
ldconfig hints file (skips all references to /usr/lib)

FreeBSD notes:
- we fixed some bugs which were submitted to DragonFly and merged there
  as commit 1ff8a2bd3eb6e5587174c6a983303ea3a79e0002;
- we added LD_LIBRARY_PATH_RPATH environment variable to switch to
  the previous behaviour of considering DT_RPATH a synonym for DT_RUNPATH;
- the FreeBSD default search path is /lib:/usr/lib and not /usr/lib.

Reviewed by:   kan
MFC after:     1 month
MFC note:      flip the ld_library_path_rpath default value for stable/9
2012-07-15 10:53:48 +00:00
Konstantin Belousov
a33cb5feab Ensure that for the object which is a dependency for some filtee,
relocations are performed before the object's initializer is called.
When dlopen()ing an object, relocate the whole DAG rooted in the
object instead of only relocating the object itself and list of newly
loaded dependencies.

Reversed sequence currently can occur if the same object is a
dependency for both filtee and filter, since filtees are loaded
typically during the relocation processing, when some filter
dependencies might be already loaded but not relocated yet.

Reported and tested by:	swills
Reviewed by:	kan
MFC after:	1 week
2012-06-27 20:24:25 +00:00
Konstantin Belousov
e474e51e07 Eliminate the static buffer used to read the first page of the mapped
object, and eliminate the pread(2) call as well [1]. Mmap the first
page of the object temporaly, and unmap it on error or last use.
Potentially, this leaves one-page gap between succeeding dlopen(3),
but there are other mmap(2) consumers as well.

Fix several cases were the whole mapping of the object leaked on error.

Use MAP_PREFAULT_READ for mmap(2) calls which map real object pages [2].

Insipired by the patch by:	Ian Lepore <freebsd damnhippie dyndns org> [1]
Suggested by:	alc [2]
MFC after:	2 weeks
2012-06-14 11:20:22 +00:00
Baptiste Daroussin
5c98f30724 open the resolved path
fix debug message

Submitted by:	John Marino <draco@marino.st>
Approved by:	des (mentor)
2012-05-05 16:37:14 +00:00
Konstantin Belousov
eb6910ccca Work around a situation where symlook_obj() could be called for the
object for which digest_dynamic1() was not done yet. Just return
EINVAL and do not try to dereference NULL buckets hash array.

This seems to happen on ia64 for rtld object itself, where the
R_IA_64_FPTR64LSB relocations require symbol lookup. The dynamic
linker itself does not rely on identity of the C-level function
pointers (i.e. function descriptors).

Reported and reviewed by:	marcel
MFC after:   8 days
2012-05-05 11:26:08 +00:00
Baptiste Daroussin
faf66437f8 Add two special directives to libmap.conf:
include <file>:
  Parse the contents of file before continuing with the current file.
includedir <dir>:
  Parse the contents of every file in dir that ends in .conf before continuing
  with the current file.
Any file or directory encountered while processing include or includedir
directives will be parsed exactly once, even if it is encountered multiple
times.

Reviewed by:	kib, des
Approved by:	des (mentor)
MFC after:	1 month
2012-04-30 21:26:35 +00:00
Konstantin Belousov
f62651920d Add GNU hash support for rtld.
Based on dragonflybsd support for GNU hash by John Marino <draco marino st>
Reviewed by:	kan
Tested by:	bapt
MFC after:	2 weeks
2012-04-30 13:31:10 +00:00
Konstantin Belousov
34cb87ba95 Split the symlook_obj1 into a loop iterating over the ELF object symbol
hash elements, and a helper matched_symbol() which match the given hash
entry and request, performing needed type and version checks.

Based on dragonflybsd support for GNU hash by John Marino <draco marino st>
Reviewed by:	kan
Tested by:	bapt
MFC after:	2 weeks
2012-04-30 13:29:21 +00:00
Nathan Whitehorn
c606eab458 Fix a missed file in r234580: replace the now-obsolete powerpc_mb() with
regular mb().
2012-04-23 00:54:06 +00:00
Konstantin Belousov
fdfc035be6 Propagate the current state of rtld_bind_lock to dlopen_object() calls
through the filter loading call chain. This fixes attempts to
write-lock the already locked rtld_bind_lock when filter loading is
initiated by relocation of dlopening dso.

Reported and tested by:	Taku YAMAMOTO <taku tackymt homeip net>
MFC after:	1 week
2012-04-12 10:32:22 +00:00
Konstantin Belousov
3f4e35f752 Properly handle absent AT_CANARY aux entry.
Submitted by:	Andrey Zonov <andrey zonov org>
MFC after:	3 days
2012-04-05 18:47:54 +00:00
Alexander Kabaev
4aed2ce86e Remove extra blank line from revious commit.
Submitted by:	trema
2012-04-02 11:59:13 +00:00
Alexander Kabaev
7605b428c9 Do not try to adjust stacks if dlopen_object is called too early.
This is a follow-up to r233231, which fixed similar issue with
object initialization code.

Reviewed by:	kib
MFC after:	1 week (with 233231)
2012-04-02 11:50:14 +00:00
Konstantin Belousov
5b7a7b02b8 Fix ia64 build after r233655.
MFC after:	1 week
2012-03-29 17:50:01 +00:00
Konstantin Belousov
5ceeeba90c Import DragonFly BSD commit
From: Sascha Wildner <saw@online.de>
  Date: Fri, 2 Mar 2012 09:15:56 +0000 (+0100)
  Subject: rtld: Add a special case in do_dlsym() for TLS stored symbols.
  X-Git-Url: http://gitweb.dragonflybsd.org/dragonfly.git/commitdiff_plain/1388aaafe730c85693936aaf9bc6d83fc2d981be?hp=bca4412595a8979ab9f1bf36068c806ce88a667a

  rtld: Add a special case in do_dlsym() for TLS stored symbols.

  Submitted-by: Markus Pfeiffer <markus.pfeiffer@morphism.de>

Discussed with:	kan
MFC after:	1 week
2012-03-29 10:32:34 +00:00
Konstantin Belousov
ff17bc61e2 Prevent rtld_verify_object_versions() from being called several times
for the same object. This can happen when object is a dependency of the
dlopen()ed dso. When called several times, we waste time due to unneeded
processing, and memory, because obj->vertab is allocated anew on each
iteration.

Reviewed by:	kan
MFC after:	2 weeks
2012-03-27 14:10:15 +00:00
Konstantin Belousov
2aa3a46729 Remove libssp_nonshared from the rtld linking set. The only use for the
library was definition for the weak alias of __stack_chk_fail.

No objections from:	kan
MFC after:	2 weeks
2012-03-24 19:14:44 +00:00
Konstantin Belousov
83dd177761 Provide short-circuit exit(3) implementation for rtld.
There is no atexit finalizers in rtld to call on rtld exiting (due to errors).

Submitted by:	bde
No objections from:	kan
MFC after:	2 weeks
2012-03-24 19:13:10 +00:00
Oleksandr Tymoshenko
bbc54af80e Before jumping to application's entry point set ra == pc in order
to let backtracing routine know to go no further.
2012-03-23 17:54:06 +00:00
Konstantin Belousov
e24348df7f Remove superfluous extern keywords.
MFC after:	   2 weeks
2012-03-23 12:13:31 +00:00
Konstantin Belousov
f7c419f22d Centralize the calculation of the top source directory. This
simplifies the build of rtld with partial checkout, allowing to
override only one place to reference other tree.

Submitted by:	bde
MFC after:	2 weeks
2012-03-23 12:10:12 +00:00
Konstantin Belousov
f7b343037f Implement xstrdup() using strlen()/xmalloc()/memcpy() already
presented in rtld, instead of pulling in libc strdup().

Submitted by:	   bde
MFC after:	   2 weeks
2012-03-23 12:04:44 +00:00
Konstantin Belousov
758ffbfa3b Use xmalloc() instead of malloc() in the places where malloc() calls
are assumed to not fail.

Make the xcalloc() calling conventions follow the calloc(3) calling
conventions and replace unchecked calls to calloc() with calls to
xcalloc().

Remove redundand declarations from xmalloc.c, which are already
present in rtld.h.

Reviewed by:	kan
Discussed with:	bde
MFC after:	2 weeks
2012-03-22 14:20:51 +00:00
Konstantin Belousov
ff6cd33319 Remove the fragments which are not needed on FreeBSD. The caltech
malloc hardly would ever be updated.

Reviewed by:  bde, kan
MFC after:    2 weeks
2012-03-22 14:11:10 +00:00
Konstantin Belousov
082f959ac8 Fix several problems with our ELF filters implementation.
Do not relocate twice an object which happens to be needed by loaded
binary (or dso) and some filtee opened due to symbol resolution when
relocating need objects.  Record the state of the relocation
processing in Obj_Entry and short-circuit relocate_objects() if
current object already processed.

Do not call constructors for filtees loaded during the early
relocation processing before image is initialized enough to run
user-provided code.  Filtees are loaded using dlopen_object(), which
normally performs relocation and initialization.  If filtee is
lazy-loaded during the relocation of dso needed by the main object,
dlopen_object() runs too earlier, when most runtime services are not
yet ready.

Postpone the constructors call to the time when main binary and
depended libraries constructors are run, passing the new flag
RTLD_LO_EARLY to dlopen_object().  Symbol lookups callers inform
symlook_* functions about early stage of initialization with
SYMLOOK_EARLY.  Pass flags through all functions participating in
object relocation.

Use the opportunity and fix flags argument to find_symdef() in
arch-specific reloc.c to use proper name SYMLOOK_IN_PLT instead of
true, which happen to have the same numeric value.

Reported and tested by:	theraven
Reviewed by:	kan
MFC after:	2 weeks
2012-03-20 13:20:49 +00:00
Konstantin Belousov
31f7a2032e Remove write-only variable.
MFC after:	3 days
2012-03-16 19:09:34 +00:00
Konstantin Belousov
6fea10fb9f Rtld on diet 3.
Stop using strerror(3) in rtld, which brings in msgcat and stdio.
Directly access sys_errlist array of errno messages with private
rtld_strerror() function.

Now,
$ size /libexec/ld-elf.so.1
   text    data     bss     dec     hex filename
  96983    2480    8744  108207   1a6af /libexec/ld-elf.so.1

Reviewed by:	dim, kan
MFC after:	2 weeks
2012-03-14 15:39:59 +00:00
Oleksandr Tymoshenko
0bf1897832 Use PTR_SUBU instead of subu (missed this one) 2012-03-12 20:59:18 +00:00
Oleksandr Tymoshenko
7730e5971e Use PTR_(ADD|SUB)U macrosses instead of hardcoded addu/subu
Spotted by: juli
2012-03-12 20:58:09 +00:00
Oleksandr Tymoshenko
33ddd0f61a - Although we pass first 4 arguments in registers, function callinf ABI requires
space to be reserved for them in stack. _rtld() prologue saves a1 and a2 in
   this space.

- Whitespace cleanup while I'm at it
2012-03-12 20:24:59 +00:00
Konstantin Belousov
68f1db20b3 Rtld on diet part 2:
Do not use stdio for libmap.conf read.  Directly map the file and
parse lines from the mappings.

Reviewed by:	kan
MFC after:	3 weeks
2012-03-12 12:16:08 +00:00
Konstantin Belousov
ef5cdcbd69 Rtld on diet part 1:
Provide rtld-private implementations of __stack_chk_guard,
__stack_chk_fail() and __chk_fail() symbols, to be used by functions
linked from libc_pic.a.  This avoids use of libc stack_protector.c,
which pulls in syslog(3) and stdio as dependency.

Also, do initialize rtld-private copy __stack_chk_guard, previously
libc-provided one was not initialized, since we do not call rtld
object _init() methods.

Reviewed by:	kan
MFC after:	3 weeks
2012-03-12 12:15:47 +00:00
Dimitry Andric
3c5b7c6fb9 Amend r232857, now dropping the casts entirely, as they were not
necessary at all.

Submitted by:	stefanf
2012-03-12 11:22:23 +00:00
Dimitry Andric
addfbd03b7 Fix the following warning/error with clang:
libexec/rtld-elf/rtld.c:1898:22: error: comparison between pointer and integer ('Elf_Addr *' (aka 'unsigned int *') and 'Elf_Addr' (aka 'unsigned int')) [-Werror]
    if (preinit_addr == (Elf_Addr)NULL)
        ~~~~~~~~~~~~ ^  ~~~~~~~~~~~~~~
libexec/rtld-elf/rtld.c:2039:16: error: comparison between pointer and integer ('Elf_Addr *' (aka 'unsigned int *') and 'Elf_Addr' (aka 'unsigned int')) [-Werror]
        if (init_addr != (Elf_Addr)NULL) {
            ~~~~~~~~~ ^  ~~~~~~~~~~~~~~

Reviewed by:	kib
2012-03-12 11:04:48 +00:00
Konstantin Belousov
5eab36f290 When iterating over the dso program headers, the object is not initialized
yet, and object segments are not yet mapped.  Only parse the notes that
appear in the first page of the dso (as it should be anyway), and use
the preloaded page content.

Reported and tested by:	stass
MFC after:	20 days
2012-03-12 10:36:03 +00:00
Konstantin Belousov
83aa9cc00c Add support for preinit, init and fini arrays. Some ABIs, in
particular on ARM, do require working init arrays.

Traditional FreeBSD crt1 calls _init and _fini of the binary, instead
of allowing runtime linker to arrange the calls.  This was probably
done to have the same crt code serve both statically and dynamically
linked binaries.  Since ABI mandates that first is called preinit
array functions, then init, and then init array functions, the init
have to be called from rtld now.

To provide binary compatibility to old FreeBSD crt1, which calls _init
itself, rtld only calls intializers and finalizers for main binary if
binary has a note indicating that new crt was used for linking.  Add
parsing of ELF notes to rtld, and cache p_osrel value since we parsed
it anyway.

The patch is inspired by init_array support for DragonflyBSD, written
by John Marino.

Reviewed by:	kan
Tested by:	andrew (arm, previous version), flo (sparc64, previous version)
MFC after:	3 weeks
2012-03-11 20:03:09 +00:00
Konstantin Belousov
6bfe9e8ccf Optimize tls_get_addr_common(). The change provides around 30% speedup
for TLS microbenchmark using global-dynamic TLS model on amd64 (which is
default for PIC dso objects).

Split the slow path into tls_get_addr_slow(), for which inlining is
disabled. This prevents the registers spill on tls_get_addr_common()
entry.

Provide static branch hint to the compiler, indicating that slow path
is not likely to be taken.

While there, do some minimal style adjustments.

Reported and tested by:	davidxu
MFC after:	1 week
2012-03-10 08:49:44 +00:00
Konstantin Belousov
5983b87199 Remove the use of toupper() from rtld_printf.c. Use of the libc function
relies on working TLS, which is particulary not true for LD_DEBUG uses.

MFC after:	1 week
2012-03-09 16:21:40 +00:00
Sergey Kandaurov
44976acae3 Cosmetic nit:
- rename isspace1() macro to the more appropriate rtld_isspace().

Discussed with:	kib
2012-03-06 09:34:30 +00:00
Oleksandr Tymoshenko
0a0f480835 - Switch to saving non-offseted pointer to TLS block in order too keep things simple 2012-03-06 03:27:08 +00:00
Konstantin Belousov
b36070f555 The libmap.conf initialization is performed before TLS is functional.
Since after r232498 the ctype macros require working access to
thread-local variables, rtld crashes when libmap.conf is present.

Use hand-made isspace1() macro which is enough to detect spaces in
libmap.conf.

Reported by:	alc, lme, many on current@
Tested by:	lme
Reviewed by:	dim, kan
MFC after:	1 week
2012-03-05 20:43:06 +00:00
Oleksandr Tymoshenko
dc3b6c3aa0 Add thread-local storage support for ARM to rtld-elf
Reviewed by:    cognet
Obtained from:  NetBSD
2012-02-14 00:16:34 +00:00
Konstantin Belousov
0eddfb0608 Add missed EOL when die() was converted to use rtld_fdputstr() instead
of errx().

Reported by:	amdmi3
PR:	bin/165075
MFC after:	3 days
2012-02-13 11:15:29 +00:00
Oleksandr Tymoshenko
b098345b9e Add handlers for TLS-related relocation entries 2012-02-11 00:54:57 +00:00
Oleksandr Tymoshenko
9b4f251484 Remove debug output 2012-02-10 19:58:04 +00:00
Oleksandr Tymoshenko
20c390af63 Switch MIPS TLS implementation to Variant I 2012-02-10 06:42:50 +00:00
Oleksandr Tymoshenko
cf9c1f8158 Fix debug output for MIPS part of rtld 2012-02-10 03:30:57 +00:00
Konstantin Belousov
6d7610d75a Add support for GNU RELRO.
Submitted by:	John Marino <draco marino st>
MFC after:	2 weeks
2012-01-30 19:52:17 +00:00
Ed Schouten
581f58e7a3 Remove unneeded dtv variable.
It is only assigned and not used at all. The object files stay identical
when the variables are removed.

Approved by:	kib
2012-01-17 21:55:20 +00:00
Ulrich Spörlein
1acf0dba17 Spelling fixes for libexec/ 2012-01-07 16:09:54 +00:00
Konstantin Belousov
5d8aec9c02 Implement fdlopen(3), an rtld interface to load shared object by file
descriptor.

Requested and tested by:	des (previous version)
Reviewed by:  des, kan (previous version)
MFC after:    2 weeks
2012-01-07 10:33:01 +00:00
Konstantin Belousov
68266d5aba Postpone the resolution of IRELATIVE relocations and IFUNC-targeted
relocations until tls is initialized and stacks permissions correctly
set. This allows the ifunc to call malloc(3) and some other heavy
services.

Add debug banner.

MFC after:	3 days
2012-01-04 17:17:11 +00:00
Nathan Whitehorn
4b51c69976 Additional icache paranoia: non-PLT relocations can modify the text segment.
It is then important to make sure the icache is synchronized again to
prevent (rare) random seg faults and illegal instructions.

MFC after:	3 days
2011-12-17 16:20:27 +00:00
Nathan Whitehorn
17bbcc52d1 Fix RTLD on PowerPC after r228435. Changing the order of init_pltgot()
caused the icache to be invalidated at the wrong time, resulting in
an icache full of nonsense in the PLT section.
2011-12-17 15:31:00 +00:00
Konstantin Belousov
5734c46c68 _rtld_bind() read-locks the bind lock, and possible plt resolution
from the dispatcher would also acquire bind lock in read mode, which
is the supported operation. plt is explicitely designed to allow safe
multithreaded updates, so the shared lock do not cause problems.

The error in r228435 is that it allows read lock acquisition after the
write lock for the bind block.  If we dlopened the shared object that
contains IRELATIVE or jump slot which target is STT_GNU_IFUNC, then
possible recursive plt resolve from the dispatcher would cause it.

Postpone the resolution for irelative/ifunc right before initializers
are called, and drop bind lock around calls to dispatcher.  Use
initlist to iterate over the objects instead of the ->next, due to
drop of the bind lock in iteration.

For i386/reloc.c:reloc_iresolve(), fix calculation of the dispatch
function address for dso, by taking into account possible non-zero
relocbase.

MFC after:	3 weeks
2011-12-14 16:47:53 +00:00
Konstantin Belousov
6be4b69715 Add support for STT_GNU_IFUNC and R_MACHINE_IRELATIVE GNU extensions to
rtld on 386 and amd64. This adds runtime bits neccessary for the use
of the dispatch functions from the dynamically-linked executables and
shared libraries.

To allow use of external references from the dispatch function, resolution
of the R_MACHINE_IRESOLVE relocations in PLT is postponed until GOT entries
for PLT are prepared, and normal resolution of the GOT entries is finished.
Similar to how it is done by GNU, IRELATIVE relocations are resolved in
advance, instead of normal lazy handling for PLT.

Move the init_pltgot() call before the relocations for the object are
processed.

MFC after:	3 weeks
2011-12-12 11:03:14 +00:00
Konstantin Belousov
5b646fa11c Typo.
MFC after:	3 days
2011-12-09 20:40:24 +00:00
Konstantin Belousov
953cc85489 Fix fd leak.
Reported by:	slonoman2011 yandex ru
MFC after:	1 week
2011-11-18 09:55:47 +00:00
Eitan Adler
36daf0495a - change "is is" to "is" or "it is"
- change "the the" to "the"

Approved by:	lstewart
Approved by:	sahil (mentor)
MFC after:	3 days
2011-10-16 14:30:28 +00:00
Konstantin Belousov
ef9cbd91d0 Handle the R_386_TLS_TPOFF32 relocation, which is similar to R_386_TLS_TPOFF,
but with negative relocation value.

Found by:	mpfr test suite, pointed to by ale
Reviewed by:	kan
MFC after:	1 week
2011-10-08 12:42:19 +00:00
Konstantin Belousov
4e63ea7386 Setting up TLS block for the main thread must be done after the
relocations are processed, since tls initialization section might be
itself subject for relocations. Only set up of the block is postponed,
the tls block offsets are allocated before relocation processing, since
TLS-related relocations may need offsets ready.

Reported by:	ale
PR:	threads/161344
Reviewed by:	kan
MFC after:	1 week
2011-10-08 12:39:47 +00:00
Konstantin Belousov
750b5e3134 Restore the writing of the .bss sections of the dsos (not the main
executable) after r190885. The whole region for the dso is mmaped with
MAP_NOCORE flag, doing only mprotect(2) over .bss prevented it from
writing .bss to core files.

Revert the optimization of using mprotect(2) to establish .bss, overlap
the section with mmap(2).

Reported by:	attilio
Reviewed by:	attilio, emaste
Approved by:	re (bz)
MFC after:	2 weeks
2011-09-20 21:49:54 +00:00
Konstantin Belousov
f785588713 Use the proper dynamic tls block to calculate the tls variable address
in case tls data generation was updated.

PR:	misc/160721
Submitted by:	"Thinker K.F. Li" <thinker codemud net>
Tested by:	flo
Approved by:	re (bz)
MFC after:	1 week
2011-09-15 11:50:09 +00:00
Konstantin Belousov
b236731716 Do not use the function pointers for the internal operation of rtld_printf()
functions. The _rtld_error() function might be called early during the rtld
bootstrap, in which case function pointers are not yet functional on ia64
due to required relocations not yet performed.

Reported, reviewed and tested by:	marcel
Approved by:	re (bz)
2011-09-06 10:21:33 +00:00
Dimitry Andric
cce0f33cda When libexec/rtld-elf/rtld.c is compiled with clang, the r_debug_state()
function (a hook necessary for gdb support), is inlined, but since the
function contains no code, no calls to it are generated.  When gdb is
debugging a dynamically linked program, this causes backtraces to be
corrupted.

Fix it by marking the function __noinline, and inserting an empty asm
statement, that pretends to clobber memory.  This forces the compiler to
emit calls to r_debug_state() throughout rtld.c.

Approved by:	re (kib)
2011-09-03 11:41:00 +00:00
Konstantin Belousov
0e9a260520 Rtld links with the specially built pic static libc library to get some
C runtime services, like printf(). Unfortunately, the multithread-safeness
measures in the libc do not work in rtld environment.

Rip the kernel printf() implementation and use it in the rtld instead of
libc version. This printf does not require any shared global data and thus
is mt-safe. Systematically use rtld_printf() and related functions, remove
the calls to err(3).

Note that stdio is still pulled from libc due to libmap implementaion using
fopen(). This is safe but unoptimal, and can be changed later.

Reported and tested by:	pgj
Diagnosed and reviewed by:	kan (previous version)
Approved by:	re (bz)
2011-08-24 20:05:13 +00:00
Ben Laurie
5f301949ef Fix clang warnings.
Approved by:	philip (mentor)
2011-06-18 13:56:33 +00:00
Nathan Whitehorn
f33b8de1dc Compile RTLD with global dot symbols on 64-bit PowerPC, as a crutch for
GDB's ability to locate r_debug_state (which is actually the only function
that need be compiled this way).
2011-06-08 13:23:35 +00:00
Andriy Gapon
6014c8de1d rtld: eliminate double call to close(2) that may occur in load_object
The second close(2) call resulted in heisenbugs in some multi-threaded
applications where e.g. dlopen(3) call in one thread could close a file
descriptor for a file having been opened in other thread concurrently.

My litmus test for this issue was an openoffice.org build.

Reviewed by:	jhb
MFC after:	2 weeks
2011-03-25 18:23:10 +00:00
Marius Strobl
080ca1a51b - Add support for TLS relocations.
- Emitt an error when encountering an unsupported and in case of the
  kernel also for unaligned relocations.
- Fix R_SPARC_LOX10 relocations. Apparently these are hardly ever used.
2011-03-11 21:08:02 +00:00
Marius Strobl
cb32ba5229 - Remove clause 3 and 4 from TNF licenses. [1]
- Add the _RF_X committed in r212998 also to the tables in the sparc64
  reloc.c in order reduce differences between the kernel and the userland
  source. This results in no functional change though.
- Fix further inconsistencies in the abbreviations of the names of the
  relocations.
- Further whitespace fixes.

Obtained from:	NetBSD [1]
2011-03-11 20:30:58 +00:00
Nathan Whitehorn
a43ce960b5 Remove dead code that snuck in from the 32-bit PowerPC version of this
file. The error being checked for does not exist on 64-bit systems.
2011-03-07 20:32:46 +00:00
Marius Strobl
25b31a9496 - With the addition of TLS support binutils started to make the addend
values for resolved symbols relative to relocbase instead of sections
  so detect this case and handle as appropriate, which allows using
  kernel modules linked with affected versions of binutils. Actually I
  think this is a bug in binutils but given that apparently nobody
  complained for nearly six years and powerpc has basically the same
  workaround I decided to put it in for the sparc64 kernel, too.
- Fix R_SPARC_HIX22 relocations. Apparently these are hardly ever used.
2011-03-06 15:20:11 +00:00