Merge "Prevent using static-allocated pthread keys before creation."
diff --git a/libc/arch-arm/arm.mk b/libc/arch-arm/arm.mk
index d72a160..6ef81bb 100644
--- a/libc/arch-arm/arm.mk
+++ b/libc/arch-arm/arm.mk
@@ -39,6 +39,7 @@
arch-arm/bionic/__bionic_clone.S \
arch-arm/bionic/_exit_with_stack_teardown.S \
arch-arm/bionic/libgcc_compat.c \
+ arch-arm/bionic/libgcc_protect_unwind.c \
arch-arm/bionic/__restore.S \
arch-arm/bionic/setjmp.S \
arch-arm/bionic/syscall.S \
diff --git a/libc/arch-arm/bionic/libgcc_protect_unwind.c b/libc/arch-arm/bionic/libgcc_protect_unwind.c
new file mode 100644
index 0000000..6d758fc
--- /dev/null
+++ b/libc/arch-arm/bionic/libgcc_protect_unwind.c
@@ -0,0 +1,93 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// TODO: This file should go away once unwinder migration to libc++.so is complete.
+
+extern char _Unwind_Backtrace __attribute((visibility("protected")));
+extern char __gnu_Unwind_Find_exidx __attribute((visibility("protected")));
+extern char __gnu_Unwind_Restore_VFP_D __attribute((visibility("protected")));
+extern char __gnu_Unwind_Restore_VFP __attribute((visibility("protected")));
+extern char __gnu_Unwind_Restore_VFP_D_16_to_31 __attribute((visibility("protected")));
+extern char __gnu_Unwind_Restore_WMMXD __attribute((visibility("protected")));
+extern char __gnu_Unwind_Restore_WMMXC __attribute((visibility("protected")));
+extern char _Unwind_GetCFA __attribute((visibility("protected")));
+extern char __gnu_Unwind_RaiseException __attribute((visibility("protected")));
+extern char __gnu_Unwind_ForcedUnwind __attribute((visibility("protected")));
+extern char __gnu_Unwind_Resume __attribute((visibility("protected")));
+extern char __gnu_Unwind_Resume_or_Rethrow __attribute((visibility("protected")));
+extern char _Unwind_Complete __attribute((visibility("protected")));
+extern char _Unwind_DeleteException __attribute((visibility("protected")));
+extern char _Unwind_VRS_Get __attribute((visibility("protected")));
+extern char _Unwind_VRS_Set __attribute((visibility("protected")));
+extern char __gnu_Unwind_Backtrace __attribute((visibility("protected")));
+extern char _Unwind_VRS_Pop __attribute((visibility("protected")));
+extern char __gnu_Unwind_Save_VFP_D __attribute((visibility("protected")));
+extern char __gnu_Unwind_Save_VFP __attribute((visibility("protected")));
+extern char __gnu_Unwind_Save_VFP_D_16_to_31 __attribute((visibility("protected")));
+extern char __gnu_Unwind_Save_WMMXD __attribute((visibility("protected")));
+extern char __gnu_Unwind_Save_WMMXC __attribute((visibility("protected")));
+extern char ___Unwind_RaiseException __attribute((visibility("protected")));
+extern char _Unwind_RaiseException __attribute((visibility("protected")));
+extern char ___Unwind_Resume __attribute((visibility("protected")));
+extern char _Unwind_Resume __attribute((visibility("protected")));
+extern char ___Unwind_Resume_or_Rethrow __attribute((visibility("protected")));
+extern char _Unwind_Resume_or_Rethrow __attribute((visibility("protected")));
+extern char ___Unwind_ForcedUnwind __attribute((visibility("protected")));
+extern char _Unwind_ForcedUnwind __attribute((visibility("protected")));
+extern char ___Unwind_Backtrace __attribute((visibility("protected")));
+extern char _Unwind_GetRegionStart __attribute((visibility("protected")));
+extern char _Unwind_GetLanguageSpecificData __attribute((visibility("protected")));
+extern char _Unwind_GetDataRelBase __attribute((visibility("protected")));
+extern char _Unwind_GetTextRelBase __attribute((visibility("protected")));
+
+void* __bionic_libgcc_unwind_symbols[] = {
+ &_Unwind_Backtrace,
+ &__gnu_Unwind_Find_exidx,
+ &__gnu_Unwind_Restore_VFP_D,
+ &__gnu_Unwind_Restore_VFP,
+ &__gnu_Unwind_Restore_VFP_D_16_to_31,
+ &__gnu_Unwind_Restore_WMMXD,
+ &__gnu_Unwind_Restore_WMMXC,
+ &_Unwind_GetCFA,
+ &__gnu_Unwind_RaiseException,
+ &__gnu_Unwind_ForcedUnwind,
+ &__gnu_Unwind_Resume,
+ &__gnu_Unwind_Resume_or_Rethrow,
+ &_Unwind_Complete,
+ &_Unwind_DeleteException,
+ &_Unwind_VRS_Get,
+ &_Unwind_VRS_Set,
+ &__gnu_Unwind_Backtrace,
+ &_Unwind_VRS_Pop,
+ &__gnu_Unwind_Save_VFP_D,
+ &__gnu_Unwind_Save_VFP,
+ &__gnu_Unwind_Save_VFP_D_16_to_31,
+ &__gnu_Unwind_Save_WMMXD,
+ &__gnu_Unwind_Save_WMMXC,
+ &___Unwind_RaiseException,
+ &_Unwind_RaiseException,
+ &___Unwind_Resume,
+ &_Unwind_Resume,
+ &___Unwind_Resume_or_Rethrow,
+ &_Unwind_Resume_or_Rethrow,
+ &___Unwind_ForcedUnwind,
+ &_Unwind_ForcedUnwind,
+ &___Unwind_Backtrace,
+ &_Unwind_GetRegionStart,
+ &_Unwind_GetLanguageSpecificData,
+ &_Unwind_GetDataRelBase,
+ &_Unwind_GetTextRelBase,
+};
diff --git a/libc/arch-arm/cortex-a15/cortex-a15.mk b/libc/arch-arm/cortex-a15/cortex-a15.mk
index cc502cf..6fa3270 100644
--- a/libc/arch-arm/cortex-a15/cortex-a15.mk
+++ b/libc/arch-arm/cortex-a15/cortex-a15.mk
@@ -1,5 +1,4 @@
libc_bionic_src_files_arm += \
- arch-arm/generic/bionic/memcmp.S \
arch-arm/cortex-a15/bionic/memcpy.S \
arch-arm/cortex-a15/bionic/memset.S \
arch-arm/cortex-a15/bionic/stpcpy.S \
@@ -10,5 +9,8 @@
arch-arm/cortex-a15/bionic/__strcpy_chk.S \
arch-arm/cortex-a15/bionic/strlen.S \
-libc_openbsd_src_files_arm += \
- upstream-openbsd/lib/libc/string/memmove.c \
+libc_bionic_src_files_arm += \
+ arch-arm/generic/bionic/memcmp.S \
+
+libc_bionic_src_files_arm += \
+ arch-arm/denver/bionic/memmove.S \
diff --git a/libc/arch-arm/cortex-a9/cortex-a9.mk b/libc/arch-arm/cortex-a9/cortex-a9.mk
index 7570567..7b38de1 100644
--- a/libc/arch-arm/cortex-a9/cortex-a9.mk
+++ b/libc/arch-arm/cortex-a9/cortex-a9.mk
@@ -1,5 +1,4 @@
libc_bionic_src_files_arm += \
- arch-arm/generic/bionic/memcmp.S \
arch-arm/cortex-a9/bionic/memcpy.S \
arch-arm/cortex-a9/bionic/memset.S \
arch-arm/cortex-a9/bionic/stpcpy.S \
@@ -10,5 +9,8 @@
arch-arm/cortex-a9/bionic/__strcpy_chk.S \
arch-arm/cortex-a9/bionic/strlen.S \
-libc_openbsd_src_files_arm += \
- upstream-openbsd/lib/libc/string/memmove.c \
+libc_bionic_src_files_arm += \
+ arch-arm/generic/bionic/memcmp.S \
+
+libc_bionic_src_files_arm += \
+ arch-arm/denver/bionic/memmove.S \
diff --git a/libc/arch-arm/krait/krait.mk b/libc/arch-arm/krait/krait.mk
index 8bd5e8b..88b4d66 100644
--- a/libc/arch-arm/krait/krait.mk
+++ b/libc/arch-arm/krait/krait.mk
@@ -1,5 +1,4 @@
libc_bionic_src_files_arm += \
- arch-arm/generic/bionic/memcmp.S \
arch-arm/krait/bionic/memcpy.S \
arch-arm/krait/bionic/memset.S \
arch-arm/krait/bionic/strcmp.S \
@@ -13,5 +12,8 @@
arch-arm/cortex-a15/bionic/strcpy.S \
arch-arm/cortex-a15/bionic/strlen.S \
-libc_openbsd_src_files_arm += \
- upstream-openbsd/lib/libc/string/memmove.c \
+libc_bionic_src_files_arm += \
+ arch-arm/generic/bionic/memcmp.S \
+
+libc_bionic_src_files_arm += \
+ arch-arm/denver/bionic/memmove.S \
diff --git a/libc/bionic/pthread_rwlock.cpp b/libc/bionic/pthread_rwlock.cpp
index 8aa40ae..934210e 100644
--- a/libc/bionic/pthread_rwlock.cpp
+++ b/libc/bionic/pthread_rwlock.cpp
@@ -28,9 +28,11 @@
#include <errno.h>
#include <stdatomic.h>
+#include <string.h>
#include "pthread_internal.h"
#include "private/bionic_futex.h"
+#include "private/bionic_lock.h"
#include "private/bionic_time_conversions.h"
/* Technical note:
@@ -53,18 +55,39 @@
* - This implementation will return EDEADLK in "write after write" and "read after
* write" cases and will deadlock in write after read case.
*
- * TODO: As it stands now, pending_readers and pending_writers could be merged into a
- * a single waiters variable. Keeping them separate adds a bit of clarity and keeps
- * the door open for a writer-biased implementation.
- *
*/
-#define RWLOCKATTR_DEFAULT 0
-#define RWLOCKATTR_SHARED_MASK 0x0010
+// A rwlockattr is implemented as a 32-bit integer which has following fields:
+// bits name description
+// 1 rwlock_kind have rwlock preference like PTHREAD_RWLOCK_PREFER_READER_NP.
+// 0 process_shared set to 1 if the rwlock is shared between processes.
+
+#define RWLOCKATTR_PSHARED_SHIFT 0
+#define RWLOCKATTR_KIND_SHIFT 1
+
+#define RWLOCKATTR_PSHARED_MASK 1
+#define RWLOCKATTR_KIND_MASK 2
+#define RWLOCKATTR_RESERVED_MASK (~3)
+
+static inline __always_inline __always_inline bool __rwlockattr_getpshared(const pthread_rwlockattr_t* attr) {
+ return (*attr & RWLOCKATTR_PSHARED_MASK) >> RWLOCKATTR_PSHARED_SHIFT;
+}
+
+static inline __always_inline __always_inline void __rwlockattr_setpshared(pthread_rwlockattr_t* attr, int pshared) {
+ *attr = (*attr & ~RWLOCKATTR_PSHARED_MASK) | (pshared << RWLOCKATTR_PSHARED_SHIFT);
+}
+
+static inline __always_inline int __rwlockattr_getkind(const pthread_rwlockattr_t* attr) {
+ return (*attr & RWLOCKATTR_KIND_MASK) >> RWLOCKATTR_KIND_SHIFT;
+}
+
+static inline __always_inline void __rwlockattr_setkind(pthread_rwlockattr_t* attr, int kind) {
+ *attr = (*attr & ~RWLOCKATTR_KIND_MASK) | (kind << RWLOCKATTR_KIND_SHIFT);
+}
int pthread_rwlockattr_init(pthread_rwlockattr_t* attr) {
- *attr = PTHREAD_PROCESS_PRIVATE;
+ *attr = 0;
return 0;
}
@@ -73,40 +96,121 @@
return 0;
}
+int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t* attr, int* pshared) {
+ if (__rwlockattr_getpshared(attr)) {
+ *pshared = PTHREAD_PROCESS_SHARED;
+ } else {
+ *pshared = PTHREAD_PROCESS_PRIVATE;
+ }
+ return 0;
+}
+
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t* attr, int pshared) {
switch (pshared) {
case PTHREAD_PROCESS_PRIVATE:
+ __rwlockattr_setpshared(attr, 0);
+ return 0;
case PTHREAD_PROCESS_SHARED:
- *attr = pshared;
+ __rwlockattr_setpshared(attr, 1);
return 0;
default:
return EINVAL;
}
}
-int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t* attr, int* pshared) {
- *pshared = *attr;
+int pthread_rwlockattr_getkind_np(const pthread_rwlockattr_t* attr, int* pref) {
+ *pref = __rwlockattr_getkind(attr);
return 0;
}
-struct pthread_rwlock_internal_t {
- atomic_int state; // 0=unlock, -1=writer lock, +n=reader lock
- atomic_int writer_thread_id;
- atomic_uint pending_readers;
- atomic_uint pending_writers;
- int32_t attr;
-
- bool process_shared() const {
- return attr == PTHREAD_PROCESS_SHARED;
+int pthread_rwlockattr_setkind_np(pthread_rwlockattr_t* attr, int pref) {
+ switch (pref) {
+ case PTHREAD_RWLOCK_PREFER_READER_NP: // Fall through.
+ case PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP:
+ __rwlockattr_setkind(attr, pref);
+ return 0;
+ default:
+ return EINVAL;
}
+}
+
+// A rwlock state is implemented as a 32-bit integer which has following rules:
+// bits name description
+// 31 owned_by_writer_flag set to 1 if the lock is owned by a writer now.
+// 30-2 reader_count the count of readers holding the lock.
+// 1 have_pending_writers set to 1 if having pending writers.
+// 0 have_pending_readers set to 1 if having pending readers.
+
+#define STATE_HAVE_PENDING_READERS_SHIFT 0
+#define STATE_HAVE_PENDING_WRITERS_SHIFT 1
+#define STATE_READER_COUNT_SHIFT 2
+#define STATE_OWNED_BY_WRITER_SHIFT 31
+
+#define STATE_HAVE_PENDING_READERS_FLAG (1 << STATE_HAVE_PENDING_READERS_SHIFT)
+#define STATE_HAVE_PENDING_WRITERS_FLAG (1 << STATE_HAVE_PENDING_WRITERS_SHIFT)
+#define STATE_READER_COUNT_CHANGE_STEP (1 << STATE_READER_COUNT_SHIFT)
+#define STATE_OWNED_BY_WRITER_FLAG (1 << STATE_OWNED_BY_WRITER_SHIFT)
+
+#define STATE_HAVE_PENDING_READERS_OR_WRITERS_FLAG \
+ (STATE_HAVE_PENDING_READERS_FLAG | STATE_HAVE_PENDING_WRITERS_FLAG)
+
+struct pthread_rwlock_internal_t {
+ atomic_int state;
+ atomic_int writer_tid;
+
+ bool pshared;
+ bool writer_nonrecursive_preferred;
+ uint16_t __pad;
+
+// When a reader thread plans to suspend on the rwlock, it will add STATE_HAVE_PENDING_READERS_FLAG
+// in state, increase pending_reader_count, and wait on pending_reader_wakeup_serial. After woken
+// up, the reader thread decreases pending_reader_count, and the last pending reader thread should
+// remove STATE_HAVE_PENDING_READERS_FLAG in state. A pending writer thread works in a similar way,
+// except that it uses flag and members for writer threads.
+
+ Lock pending_lock; // All pending members below are protected by pending_lock.
+ uint32_t pending_reader_count; // Count of pending reader threads.
+ uint32_t pending_writer_count; // Count of pending writer threads.
+ uint32_t pending_reader_wakeup_serial; // Pending reader threads wait on this address by futex_wait.
+ uint32_t pending_writer_wakeup_serial; // Pending writer threads wait on this address by futex_wait.
#if defined(__LP64__)
- char __reserved[36];
-#else
char __reserved[20];
+#else
+ char __reserved[4];
#endif
};
+static inline __always_inline bool __state_owned_by_writer(int state) {
+ return state < 0;
+}
+
+static inline __always_inline bool __state_owned_by_readers(int state) {
+ // If state >= 0, the owned_by_writer_flag is not set.
+ // And if state >= STATE_READER_COUNT_CHANGE_STEP, the reader_count field is not empty.
+ return state >= STATE_READER_COUNT_CHANGE_STEP;
+}
+
+static inline __always_inline bool __state_owned_by_readers_or_writer(int state) {
+ return state < 0 || state >= STATE_READER_COUNT_CHANGE_STEP;
+}
+
+static inline __always_inline int __state_add_writer_flag(int state) {
+ return state | STATE_OWNED_BY_WRITER_FLAG;
+}
+
+static inline __always_inline bool __state_is_last_reader(int state) {
+ return (state >> STATE_READER_COUNT_SHIFT) == 1;
+}
+
+static inline __always_inline bool __state_have_pending_writers(int state) {
+ return state & STATE_HAVE_PENDING_WRITERS_FLAG;
+}
+
+static inline __always_inline bool __state_have_pending_readers_or_writers(int state) {
+ return state & STATE_HAVE_PENDING_READERS_OR_WRITERS_FLAG;
+}
+
static_assert(sizeof(pthread_rwlock_t) == sizeof(pthread_rwlock_internal_t),
"pthread_rwlock_t should actually be pthread_rwlock_internal_t in implementation.");
@@ -115,31 +219,35 @@
static_assert(alignof(pthread_rwlock_t) == 4,
"pthread_rwlock_t should fulfill the alignment requirement of pthread_rwlock_internal_t.");
-static inline pthread_rwlock_internal_t* __get_internal_rwlock(pthread_rwlock_t* rwlock_interface) {
+static inline __always_inline pthread_rwlock_internal_t* __get_internal_rwlock(pthread_rwlock_t* rwlock_interface) {
return reinterpret_cast<pthread_rwlock_internal_t*>(rwlock_interface);
}
int pthread_rwlock_init(pthread_rwlock_t* rwlock_interface, const pthread_rwlockattr_t* attr) {
pthread_rwlock_internal_t* rwlock = __get_internal_rwlock(rwlock_interface);
- if (__predict_true(attr == NULL)) {
- rwlock->attr = 0;
- } else {
- switch (*attr) {
- case PTHREAD_PROCESS_SHARED:
- case PTHREAD_PROCESS_PRIVATE:
- rwlock->attr= *attr;
+ memset(rwlock, 0, sizeof(pthread_rwlock_internal_t));
+
+ if (__predict_false(attr != NULL)) {
+ rwlock->pshared = __rwlockattr_getpshared(attr);
+ int kind = __rwlockattr_getkind(attr);
+ switch (kind) {
+ case PTHREAD_RWLOCK_PREFER_READER_NP:
+ rwlock->writer_nonrecursive_preferred = false;
+ break;
+ case PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP:
+ rwlock->writer_nonrecursive_preferred = true;
break;
default:
return EINVAL;
}
+ if ((*attr & RWLOCKATTR_RESERVED_MASK) != 0) {
+ return EINVAL;
+ }
}
atomic_init(&rwlock->state, 0);
- atomic_init(&rwlock->writer_thread_id, 0);
- atomic_init(&rwlock->pending_readers, 0);
- atomic_init(&rwlock->pending_writers, 0);
-
+ rwlock->pending_lock.init(rwlock->pshared);
return 0;
}
@@ -152,105 +260,173 @@
return 0;
}
+static inline __always_inline bool __can_acquire_read_lock(int old_state,
+ bool writer_nonrecursive_preferred) {
+ // If writer is preferred with nonrecursive reader, we prevent further readers from acquiring
+ // the lock when there are writers waiting for the lock.
+ bool cannot_apply = __state_owned_by_writer(old_state) ||
+ (writer_nonrecursive_preferred && __state_have_pending_writers(old_state));
+ return !cannot_apply;
+}
+
+static inline __always_inline int __pthread_rwlock_tryrdlock(pthread_rwlock_internal_t* rwlock) {
+ int old_state = atomic_load_explicit(&rwlock->state, memory_order_relaxed);
+
+ while (__predict_true(__can_acquire_read_lock(old_state, rwlock->writer_nonrecursive_preferred))) {
+
+ int new_state = old_state + STATE_READER_COUNT_CHANGE_STEP;
+ if (__predict_false(!__state_owned_by_readers(new_state))) { // Happens when reader count overflows.
+ return EAGAIN;
+ }
+ if (__predict_true(atomic_compare_exchange_weak_explicit(&rwlock->state, &old_state, new_state,
+ memory_order_acquire, memory_order_relaxed))) {
+ return 0;
+ }
+ }
+ return EBUSY;
+}
+
static int __pthread_rwlock_timedrdlock(pthread_rwlock_internal_t* rwlock,
const timespec* abs_timeout_or_null) {
- if (__predict_false(__get_thread()->tid == atomic_load_explicit(&rwlock->writer_thread_id,
- memory_order_relaxed))) {
+ if (atomic_load_explicit(&rwlock->writer_tid, memory_order_relaxed) == __get_thread()->tid) {
return EDEADLK;
}
while (true) {
+ int ret = __pthread_rwlock_tryrdlock(rwlock);
+ if (ret == 0 || ret == EAGAIN) {
+ return ret;
+ }
+
int old_state = atomic_load_explicit(&rwlock->state, memory_order_relaxed);
- if (__predict_true(old_state >= 0)) {
- if (atomic_compare_exchange_weak_explicit(&rwlock->state, &old_state, old_state + 1,
- memory_order_acquire, memory_order_relaxed)) {
- return 0;
- }
- } else {
- timespec ts;
- timespec* rel_timeout = NULL;
+ if (__can_acquire_read_lock(old_state, rwlock->writer_nonrecursive_preferred)) {
+ continue;
+ }
- if (abs_timeout_or_null != NULL) {
- rel_timeout = &ts;
- if (!timespec_from_absolute_timespec(*rel_timeout, *abs_timeout_or_null, CLOCK_REALTIME)) {
- return ETIMEDOUT;
- }
- }
+ timespec ts;
+ timespec* rel_timeout = NULL;
- // To avoid losing wake ups, the pending_readers increment should be observed before
- // futex_wait by all threads. A seq_cst fence instead of a seq_cst operation is used
- // here. Because only a seq_cst fence can ensure sequential consistency for non-atomic
- // operations in futex_wait.
- atomic_fetch_add_explicit(&rwlock->pending_readers, 1, memory_order_relaxed);
-
- atomic_thread_fence(memory_order_seq_cst);
-
- int ret = __futex_wait_ex(&rwlock->state, rwlock->process_shared(), old_state,
- rel_timeout);
-
- atomic_fetch_sub_explicit(&rwlock->pending_readers, 1, memory_order_relaxed);
-
- if (ret == -ETIMEDOUT) {
+ if (abs_timeout_or_null != NULL) {
+ rel_timeout = &ts;
+ if (!timespec_from_absolute_timespec(*rel_timeout, *abs_timeout_or_null, CLOCK_REALTIME)) {
return ETIMEDOUT;
}
}
+
+ rwlock->pending_lock.lock();
+ rwlock->pending_reader_count++;
+
+ // We rely on the fact that all atomic exchange operations on the same object (here it is
+ // rwlock->state) always appear to occur in a single total order. If the pending flag is added
+ // before unlocking, the unlocking thread will wakeup the waiter. Otherwise, we will see the
+ // state is unlocked and will not wait anymore.
+ old_state = atomic_fetch_or_explicit(&rwlock->state, STATE_HAVE_PENDING_READERS_FLAG,
+ memory_order_relaxed);
+
+ int old_serial = rwlock->pending_reader_wakeup_serial;
+ rwlock->pending_lock.unlock();
+
+ int futex_ret = 0;
+ if (!__can_acquire_read_lock(old_state, rwlock->writer_nonrecursive_preferred)) {
+ futex_ret = __futex_wait_ex(&rwlock->pending_reader_wakeup_serial, rwlock->pshared,
+ old_serial, rel_timeout);
+ }
+
+ rwlock->pending_lock.lock();
+ rwlock->pending_reader_count--;
+ if (rwlock->pending_reader_count == 0) {
+ atomic_fetch_and_explicit(&rwlock->state, ~STATE_HAVE_PENDING_READERS_FLAG,
+ memory_order_relaxed);
+ }
+ rwlock->pending_lock.unlock();
+
+ if (futex_ret == -ETIMEDOUT) {
+ return ETIMEDOUT;
+ }
}
}
+static inline __always_inline bool __can_acquire_write_lock(int old_state) {
+ return !__state_owned_by_readers_or_writer(old_state);
+}
+
+static inline __always_inline int __pthread_rwlock_trywrlock(pthread_rwlock_internal_t* rwlock) {
+ int old_state = atomic_load_explicit(&rwlock->state, memory_order_relaxed);
+
+ while (__predict_true(__can_acquire_write_lock(old_state))) {
+ if (__predict_true(atomic_compare_exchange_weak_explicit(&rwlock->state, &old_state,
+ __state_add_writer_flag(old_state), memory_order_acquire, memory_order_relaxed))) {
+
+ atomic_store_explicit(&rwlock->writer_tid, __get_thread()->tid, memory_order_relaxed);
+ return 0;
+ }
+ }
+ return EBUSY;
+}
+
static int __pthread_rwlock_timedwrlock(pthread_rwlock_internal_t* rwlock,
const timespec* abs_timeout_or_null) {
- if (__predict_false(__get_thread()->tid == atomic_load_explicit(&rwlock->writer_thread_id,
- memory_order_relaxed))) {
+ if (atomic_load_explicit(&rwlock->writer_tid, memory_order_relaxed) == __get_thread()->tid) {
return EDEADLK;
}
-
while (true) {
+ int ret = __pthread_rwlock_trywrlock(rwlock);
+ if (ret == 0) {
+ return ret;
+ }
+
int old_state = atomic_load_explicit(&rwlock->state, memory_order_relaxed);
- if (__predict_true(old_state == 0)) {
- if (atomic_compare_exchange_weak_explicit(&rwlock->state, &old_state, -1,
- memory_order_acquire, memory_order_relaxed)) {
- // writer_thread_id is protected by rwlock and can only be modified in rwlock write
- // owner thread. Other threads may read it for EDEADLK error checking, atomic operation
- // is safe enough for it.
- atomic_store_explicit(&rwlock->writer_thread_id, __get_thread()->tid, memory_order_relaxed);
- return 0;
- }
- } else {
- timespec ts;
- timespec* rel_timeout = NULL;
+ if (__can_acquire_write_lock(old_state)) {
+ continue;
+ }
- if (abs_timeout_or_null != NULL) {
- rel_timeout = &ts;
- if (!timespec_from_absolute_timespec(*rel_timeout, *abs_timeout_or_null, CLOCK_REALTIME)) {
- return ETIMEDOUT;
- }
- }
+ timespec ts;
+ timespec* rel_timeout = NULL;
- // To avoid losing wake ups, the pending_writers increment should be observed before
- // futex_wait by all threads. A seq_cst fence instead of a seq_cst operation is used
- // here. Because only a seq_cst fence can ensure sequential consistency for non-atomic
- // operations in futex_wait.
- atomic_fetch_add_explicit(&rwlock->pending_writers, 1, memory_order_relaxed);
-
- atomic_thread_fence(memory_order_seq_cst);
-
- int ret = __futex_wait_ex(&rwlock->state, rwlock->process_shared(), old_state,
- rel_timeout);
-
- atomic_fetch_sub_explicit(&rwlock->pending_writers, 1, memory_order_relaxed);
-
- if (ret == -ETIMEDOUT) {
+ if (abs_timeout_or_null != NULL) {
+ rel_timeout = &ts;
+ if (!timespec_from_absolute_timespec(*rel_timeout, *abs_timeout_or_null, CLOCK_REALTIME)) {
return ETIMEDOUT;
}
}
+
+ rwlock->pending_lock.lock();
+ rwlock->pending_writer_count++;
+
+ old_state = atomic_fetch_or_explicit(&rwlock->state, STATE_HAVE_PENDING_WRITERS_FLAG,
+ memory_order_relaxed);
+
+ int old_serial = rwlock->pending_writer_wakeup_serial;
+ rwlock->pending_lock.unlock();
+
+ int futex_ret = 0;
+ if (!__can_acquire_write_lock(old_state)) {
+ futex_ret = __futex_wait_ex(&rwlock->pending_writer_wakeup_serial, rwlock->pshared,
+ old_serial, rel_timeout);
+ }
+
+ rwlock->pending_lock.lock();
+ rwlock->pending_writer_count--;
+ if (rwlock->pending_writer_count == 0) {
+ atomic_fetch_and_explicit(&rwlock->state, ~STATE_HAVE_PENDING_WRITERS_FLAG,
+ memory_order_relaxed);
+ }
+ rwlock->pending_lock.unlock();
+
+ if (futex_ret == -ETIMEDOUT) {
+ return ETIMEDOUT;
+ }
}
}
int pthread_rwlock_rdlock(pthread_rwlock_t* rwlock_interface) {
pthread_rwlock_internal_t* rwlock = __get_internal_rwlock(rwlock_interface);
-
+ // Avoid slowing down fast path of rdlock.
+ if (__predict_true(__pthread_rwlock_tryrdlock(rwlock) == 0)) {
+ return 0;
+ }
return __pthread_rwlock_timedrdlock(rwlock, NULL);
}
@@ -261,19 +437,15 @@
}
int pthread_rwlock_tryrdlock(pthread_rwlock_t* rwlock_interface) {
- pthread_rwlock_internal_t* rwlock = __get_internal_rwlock(rwlock_interface);
-
- int old_state = atomic_load_explicit(&rwlock->state, memory_order_relaxed);
-
- while (old_state >= 0 && !atomic_compare_exchange_weak_explicit(&rwlock->state, &old_state,
- old_state + 1, memory_order_acquire, memory_order_relaxed)) {
- }
- return (old_state >= 0) ? 0 : EBUSY;
+ return __pthread_rwlock_tryrdlock(__get_internal_rwlock(rwlock_interface));
}
int pthread_rwlock_wrlock(pthread_rwlock_t* rwlock_interface) {
pthread_rwlock_internal_t* rwlock = __get_internal_rwlock(rwlock_interface);
-
+ // Avoid slowing down fast path of wrlock.
+ if (__predict_true(__pthread_rwlock_trywrlock(rwlock) == 0)) {
+ return 0;
+ }
return __pthread_rwlock_timedwrlock(rwlock, NULL);
}
@@ -284,65 +456,52 @@
}
int pthread_rwlock_trywrlock(pthread_rwlock_t* rwlock_interface) {
- pthread_rwlock_internal_t* rwlock = __get_internal_rwlock(rwlock_interface);
-
- int old_state = atomic_load_explicit(&rwlock->state, memory_order_relaxed);
-
- while (old_state == 0 && !atomic_compare_exchange_weak_explicit(&rwlock->state, &old_state, -1,
- memory_order_acquire, memory_order_relaxed)) {
- }
- if (old_state == 0) {
- atomic_store_explicit(&rwlock->writer_thread_id, __get_thread()->tid, memory_order_relaxed);
- return 0;
- }
- return EBUSY;
+ return __pthread_rwlock_trywrlock(__get_internal_rwlock(rwlock_interface));
}
-
int pthread_rwlock_unlock(pthread_rwlock_t* rwlock_interface) {
pthread_rwlock_internal_t* rwlock = __get_internal_rwlock(rwlock_interface);
int old_state = atomic_load_explicit(&rwlock->state, memory_order_relaxed);
- if (__predict_false(old_state == 0)) {
- return EPERM;
- } else if (old_state == -1) {
- if (atomic_load_explicit(&rwlock->writer_thread_id, memory_order_relaxed) != __get_thread()->tid) {
+ if (__state_owned_by_writer(old_state)) {
+ if (atomic_load_explicit(&rwlock->writer_tid, memory_order_relaxed) != __get_thread()->tid) {
return EPERM;
}
- // We're no longer the owner.
- atomic_store_explicit(&rwlock->writer_thread_id, 0, memory_order_relaxed);
- // Change state from -1 to 0.
- atomic_store_explicit(&rwlock->state, 0, memory_order_release);
-
- } else { // old_state > 0
- // Reduce state by 1.
- while (old_state > 0 && !atomic_compare_exchange_weak_explicit(&rwlock->state, &old_state,
- old_state - 1, memory_order_release, memory_order_relaxed)) {
- }
-
- if (old_state <= 0) {
- return EPERM;
- } else if (old_state > 1) {
+ atomic_store_explicit(&rwlock->writer_tid, 0, memory_order_relaxed);
+ old_state = atomic_fetch_and_explicit(&rwlock->state, ~STATE_OWNED_BY_WRITER_FLAG,
+ memory_order_release);
+ if (!__state_have_pending_readers_or_writers(old_state)) {
return 0;
}
- // old_state = 1, which means the last reader calling unlock. It has to wake up waiters.
+
+ } else if (__state_owned_by_readers(old_state)) {
+ old_state = atomic_fetch_sub_explicit(&rwlock->state, STATE_READER_COUNT_CHANGE_STEP,
+ memory_order_release);
+ if (!__state_is_last_reader(old_state) || !__state_have_pending_readers_or_writers(old_state)) {
+ return 0;
+ }
+
+ } else {
+ return EPERM;
}
- // If having waiters, wake up them.
- // To avoid losing wake ups, the update of state should be observed before reading
- // pending_readers/pending_writers by all threads. Use read locking as an example:
- // read locking thread unlocking thread
- // pending_readers++; state = 0;
- // seq_cst fence seq_cst fence
- // read state for futex_wait read pending_readers for futex_wake
- //
- // So when locking and unlocking threads are running in parallel, we will not get
- // in a situation that the locking thread reads state as negative and needs to wait,
- // while the unlocking thread reads pending_readers as zero and doesn't need to wake up waiters.
- atomic_thread_fence(memory_order_seq_cst);
- if (__predict_false(atomic_load_explicit(&rwlock->pending_readers, memory_order_relaxed) > 0 ||
- atomic_load_explicit(&rwlock->pending_writers, memory_order_relaxed) > 0)) {
- __futex_wake_ex(&rwlock->state, rwlock->process_shared(), INT_MAX);
+ // Wake up pending readers or writers.
+ rwlock->pending_lock.lock();
+ if (rwlock->pending_writer_count != 0) {
+ rwlock->pending_writer_wakeup_serial++;
+ rwlock->pending_lock.unlock();
+
+ __futex_wake_ex(&rwlock->pending_writer_wakeup_serial, rwlock->pshared, 1);
+
+ } else if (rwlock->pending_reader_count != 0) {
+ rwlock->pending_reader_wakeup_serial++;
+ rwlock->pending_lock.unlock();
+
+ __futex_wake_ex(&rwlock->pending_reader_wakeup_serial, rwlock->pshared, INT_MAX);
+
+ } else {
+ // It happens when waiters are woken up by timeout.
+ rwlock->pending_lock.unlock();
}
return 0;
}
diff --git a/libc/include/elf.h b/libc/include/elf.h
index ee53ad1..801d9ff 100644
--- a/libc/include/elf.h
+++ b/libc/include/elf.h
@@ -48,6 +48,71 @@
} a_un;
} Elf64_auxv_t;
+typedef Elf32_Half Elf32_Versym;
+typedef Elf64_Half Elf64_Versym;
+
+typedef struct {
+ Elf32_Half vd_version;
+ Elf32_Half vd_flags;
+ Elf32_Half vd_ndx;
+ Elf32_Half vd_cnt;
+ Elf32_Word vd_hash;
+ Elf32_Word vd_aux;
+ Elf32_Word vd_next;
+} Elf32_Verdef;
+
+typedef struct {
+ Elf32_Word vda_name;
+ Elf32_Word vda_next;
+} Elf32_Verdaux;
+
+typedef struct {
+ Elf64_Half vd_version;
+ Elf64_Half vd_flags;
+ Elf64_Half vd_ndx;
+ Elf64_Half vd_cnt;
+ Elf64_Word vd_hash;
+ Elf64_Word vd_aux;
+ Elf64_Word vd_next;
+} Elf64_Verdef;
+
+typedef struct {
+ Elf64_Word vda_name;
+ Elf64_Word vda_next;
+} Elf64_Verdaux;
+
+typedef struct {
+ Elf32_Half vn_version;
+ Elf32_Half vn_cnt;
+ Elf32_Word vn_file;
+ Elf32_Word vn_aux;
+ Elf32_Word vn_next;
+} Elf32_Verneed;
+
+typedef struct {
+ Elf32_Word vna_hash;
+ Elf32_Half vna_flags;
+ Elf32_Half vna_other;
+ Elf32_Word vna_name;
+ Elf32_Word vna_next;
+} Elf32_Vernaux;
+
+typedef struct {
+ Elf64_Half vn_version;
+ Elf64_Half vn_cnt;
+ Elf64_Word vn_file;
+ Elf64_Word vn_aux;
+ Elf64_Word vn_next;
+} Elf64_Verneed;
+
+typedef struct {
+ Elf64_Word vna_hash;
+ Elf64_Half vna_flags;
+ Elf64_Half vna_other;
+ Elf64_Word vna_name;
+ Elf64_Word vna_next;
+} Elf64_Vernaux;
+
#define DF_ORIGIN 0x00000001
#define DF_SYMBOLIC 0x00000002
#define DF_TEXTREL 0x00000004
diff --git a/libc/include/pthread.h b/libc/include/pthread.h
index 83a56d6..26d68e4 100644
--- a/libc/include/pthread.h
+++ b/libc/include/pthread.h
@@ -85,6 +85,11 @@
#define PTHREAD_RWLOCK_INITIALIZER { { 0 } }
+enum {
+ PTHREAD_RWLOCK_PREFER_READER_NP = 0,
+ PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP = 1,
+};
+
typedef int pthread_key_t;
typedef int pthread_once_t;
@@ -178,10 +183,12 @@
int pthread_once(pthread_once_t*, void (*)(void)) __nonnull((1, 2));
+int pthread_rwlockattr_init(pthread_rwlockattr_t*) __nonnull((1));
int pthread_rwlockattr_destroy(pthread_rwlockattr_t*) __nonnull((1));
int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t*, int*) __nonnull((1, 2));
-int pthread_rwlockattr_init(pthread_rwlockattr_t*) __nonnull((1));
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t*, int) __nonnull((1));
+int pthread_rwlockattr_getkind_np(const pthread_rwlockattr_t*, int*) __nonnull((1, 2));
+int pthread_rwlockattr_setkind_np(pthread_rwlockattr_t*, int) __nonnull((1));
int pthread_rwlock_destroy(pthread_rwlock_t*) __nonnull((1));
int pthread_rwlock_init(pthread_rwlock_t*, const pthread_rwlockattr_t*) __nonnull((1));
diff --git a/libc/private/bionic_lock.h b/libc/private/bionic_lock.h
new file mode 100644
index 0000000..6a0fd06
--- /dev/null
+++ b/libc/private/bionic_lock.h
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2015 The Android Open Source Project
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the
+ * distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
+ * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+ * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
+ * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
+ * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+#ifndef _BIONIC_LOCK_H
+#define _BIONIC_LOCK_H
+
+#include <stdatomic.h>
+#include "private/bionic_futex.h"
+
+class Lock {
+ private:
+ enum LockState {
+ Unlocked = 0,
+ LockedWithoutWaiter,
+ LockedWithWaiter,
+ };
+ _Atomic(LockState) state;
+ bool process_shared;
+
+ public:
+ Lock(bool process_shared = false) {
+ init(process_shared);
+ }
+
+ void init(bool process_shared) {
+ atomic_init(&state, Unlocked);
+ this->process_shared = process_shared;
+ }
+
+ void lock() {
+ LockState old_state = Unlocked;
+ if (__predict_true(atomic_compare_exchange_strong_explicit(&state, &old_state,
+ LockedWithoutWaiter, memory_order_acquire, memory_order_relaxed))) {
+ return;
+ }
+ while (atomic_exchange_explicit(&state, LockedWithWaiter, memory_order_acquire) != Unlocked) {
+ // TODO: As the critical section is brief, it is a better choice to spin a few times befor sleeping.
+ __futex_wait_ex(&state, process_shared, LockedWithWaiter, NULL);
+ }
+ return;
+ }
+
+ void unlock() {
+ if (atomic_exchange_explicit(&state, Unlocked, memory_order_release) == LockedWithWaiter) {
+ __futex_wake_ex(&state, process_shared, 1);
+ }
+ }
+};
+
+#endif // _BIONIC_LOCK_H
diff --git a/libc/tools/zoneinfo/update-tzdata.py b/libc/tools/zoneinfo/update-tzdata.py
index d5788af..68a5ff5 100755
--- a/libc/tools/zoneinfo/update-tzdata.py
+++ b/libc/tools/zoneinfo/update-tzdata.py
@@ -33,9 +33,12 @@
CheckDirExists(bionic_libc_tools_zoneinfo_dir, 'bionic/libc/tools/zoneinfo')
print 'Found bionic in %s ...' % bionic_dir
-# Find the icu4c directory.
-icu_dir = os.path.realpath('%s/../external/icu/icu4c/source' % bionic_dir)
-CheckDirExists(icu_dir, 'external/icu/icu4c/source')
+# Find the icu directory.
+icu_dir = os.path.realpath('%s/../external/icu' % bionic_dir)
+icu4c_dir = os.path.realpath('%s/icu4c/source' % icu_dir)
+icu4j_dir = os.path.realpath('%s/icu4j' % icu_dir)
+CheckDirExists(icu4c_dir, 'external/icu/icu4c/source')
+CheckDirExists(icu4j_dir, 'external/icu/icu4j')
print 'Found icu in %s ...' % icu_dir
@@ -116,14 +119,14 @@
# Build the ICU tools.
print 'Configuring ICU tools...'
- subprocess.check_call(['%s/runConfigureICU' % icu_dir, 'Linux'])
+ subprocess.check_call(['%s/runConfigureICU' % icu4c_dir, 'Linux'])
# Run the ICU tools.
os.chdir('tools/tzcode')
# The tz2icu tool only picks up icuregions and icuzones in they are in the CWD
for icu_data_file in [ 'icuregions', 'icuzones']:
- icu_data_file_source = '%s/tools/tzcode/%s' % (icu_dir, icu_data_file)
+ icu_data_file_source = '%s/tools/tzcode/%s' % (icu4c_dir, icu_data_file)
icu_data_file_symlink = './%s' % icu_data_file
os.symlink(icu_data_file_source, icu_data_file_symlink)
@@ -134,7 +137,7 @@
subprocess.check_call(['make'])
# Copy the source file to its ultimate destination.
- icu_txt_data_dir = '%s/data/misc' % icu_dir
+ icu_txt_data_dir = '%s/data/misc' % icu4c_dir
print 'Copying zoneinfo64.txt to %s ...' % icu_txt_data_dir
shutil.copy('zoneinfo64.txt', icu_txt_data_dir)
@@ -143,7 +146,7 @@
subprocess.check_call(['make', 'INCLUDE_UNI_CORE_DATA=1', '-j32'])
# Copy the .dat file to its ultimate destination.
- icu_dat_data_dir = '%s/stubdata' % icu_dir
+ icu_dat_data_dir = '%s/stubdata' % icu4c_dir
datfiles = glob.glob('data/out/tmp/icudt??l.dat')
if len(datfiles) != 1:
print 'ERROR: Unexpectedly found %d .dat files (%s). Halting.' % (len(datfiles), datfiles)
@@ -152,6 +155,20 @@
print 'Copying %s to %s ...' % (datfile, icu_dat_data_dir)
shutil.copy(datfile, icu_dat_data_dir)
+ # Generate the ICU4J .jar files
+ os.chdir('%s/data' % icu_working_dir)
+ subprocess.check_call(['make', 'icu4j-data'])
+
+ # Copy the ICU4J .jar files to their ultimate destination.
+ icu_jar_data_dir = '%s/main/shared/data' % icu4j_dir
+ jarfiles = glob.glob('out/icu4j/*.jar')
+ if len(jarfiles) != 2:
+ print 'ERROR: Unexpectedly found %d .jar files (%s). Halting.' % (len(jarfiles), jarfiles)
+ sys.exit(1)
+ for jarfile in jarfiles:
+ print 'Copying %s to %s ...' % (jarfile, icu_jar_data_dir)
+ shutil.copy(jarfile, icu_jar_data_dir)
+
# Switch back to the original working cwd.
os.chdir(original_working_dir)
diff --git a/libc/tzcode/localtime.c b/libc/tzcode/localtime.c
index 29f605c..bf09c5e 100644
--- a/libc/tzcode/localtime.c
+++ b/libc/tzcode/localtime.c
@@ -2253,11 +2253,14 @@
}
static int __bionic_open_tzdata(const char* olson_id, int* data_size) {
- int fd = __bionic_open_tzdata_path("ANDROID_ROOT", "/usr/share/zoneinfo/tzdata", olson_id, data_size);
- if (fd == -2) {
- // The first thing that 'recovery' does is try to format the current time. It doesn't have
- // any tzdata available, so we must not abort here --- doing so breaks the recovery image!
- fprintf(stderr, "%s: couldn't find any tzdata when looking for %s!\n", __FUNCTION__, olson_id);
+ int fd = __bionic_open_tzdata_path("ANDROID_DATA", "/misc/zoneinfo/current/tzdata", olson_id, data_size);
+ if (fd < 0) {
+ fd = __bionic_open_tzdata_path("ANDROID_ROOT", "/usr/share/zoneinfo/tzdata", olson_id, data_size);
+ if (fd == -2) {
+ // The first thing that 'recovery' does is try to format the current time. It doesn't have
+ // any tzdata available, so we must not abort here --- doing so breaks the recovery image!
+ fprintf(stderr, "%s: couldn't find any tzdata when looking for %s!\n", __FUNCTION__, olson_id);
+ }
}
return fd;
}
diff --git a/libc/zoneinfo/tzdata b/libc/zoneinfo/tzdata
index b9a6621..3661b68 100644
--- a/libc/zoneinfo/tzdata
+++ b/libc/zoneinfo/tzdata
Binary files differ
diff --git a/linker/dlfcn.cpp b/linker/dlfcn.cpp
index 479e831..5ed8891 100644
--- a/linker/dlfcn.cpp
+++ b/linker/dlfcn.cpp
@@ -136,7 +136,7 @@
memset(info, 0, sizeof(Dl_info));
- info->dli_fname = si->name;
+ info->dli_fname = si->get_realpath();
// Address at which the shared object is loaded.
info->dli_fbase = reinterpret_cast<void*>(si->base);
@@ -228,23 +228,28 @@
static unsigned g_libdl_chains[] = { 0, 2, 3, 4, 5, 6, 7, 8, 9, 0 };
#endif
-static soinfo __libdl_info("libdl.so", nullptr, 0, RTLD_GLOBAL);
+static uint8_t __libdl_info_buf[sizeof(soinfo)] __attribute__((aligned(8)));
+static soinfo* __libdl_info = nullptr;
// This is used by the dynamic linker. Every process gets these symbols for free.
soinfo* get_libdl_info() {
- if ((__libdl_info.flags_ & FLAG_LINKED) == 0) {
- __libdl_info.flags_ |= FLAG_LINKED;
- __libdl_info.strtab_ = ANDROID_LIBDL_STRTAB;
- __libdl_info.symtab_ = g_libdl_symtab;
- __libdl_info.nbucket_ = sizeof(g_libdl_buckets)/sizeof(unsigned);
- __libdl_info.nchain_ = sizeof(g_libdl_chains)/sizeof(unsigned);
- __libdl_info.bucket_ = g_libdl_buckets;
- __libdl_info.chain_ = g_libdl_chains;
- __libdl_info.ref_count_ = 1;
- __libdl_info.strtab_size_ = sizeof(ANDROID_LIBDL_STRTAB);
- __libdl_info.local_group_root_ = &__libdl_info;
- __libdl_info.soname_ = "libdl.so";
+ if (__libdl_info == nullptr) {
+ __libdl_info = new (__libdl_info_buf) soinfo("libdl.so", nullptr, 0, RTLD_GLOBAL);
+ __libdl_info->flags_ |= FLAG_LINKED;
+ __libdl_info->strtab_ = ANDROID_LIBDL_STRTAB;
+ __libdl_info->symtab_ = g_libdl_symtab;
+ __libdl_info->nbucket_ = sizeof(g_libdl_buckets)/sizeof(unsigned);
+ __libdl_info->nchain_ = sizeof(g_libdl_chains)/sizeof(unsigned);
+ __libdl_info->bucket_ = g_libdl_buckets;
+ __libdl_info->chain_ = g_libdl_chains;
+ __libdl_info->ref_count_ = 1;
+ __libdl_info->strtab_size_ = sizeof(ANDROID_LIBDL_STRTAB);
+ __libdl_info->local_group_root_ = __libdl_info;
+ __libdl_info->soname_ = "libdl.so";
+#if defined(__arm__)
+ strlcpy(__libdl_info->old_name_, __libdl_info->soname_, sizeof(__libdl_info->old_name_));
+#endif
}
- return &__libdl_info;
+ return __libdl_info;
}
diff --git a/linker/linker.cpp b/linker/linker.cpp
index a9c2bc1..3c8ba76 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -153,7 +153,8 @@
// Copy the necessary fields into the debug structure.
link_map* map = &(info->link_map_head);
map->l_addr = info->load_bias;
- map->l_name = info->name;
+ // link_map l_name field is not const.
+ map->l_name = const_cast<char*>(info->get_realpath());
map->l_ld = info->dynamic;
// Stick the new library at the end of the list.
@@ -238,7 +239,7 @@
static soinfo* soinfo_alloc(const char* name, struct stat* file_stat,
off64_t file_offset, uint32_t rtld_flags) {
- if (strlen(name) >= SOINFO_NAME_LEN) {
+ if (strlen(name) >= PATH_MAX) {
DL_ERR("library name \"%s\" too long", name);
return nullptr;
}
@@ -263,7 +264,7 @@
soinfo *prev = nullptr, *trav;
- TRACE("name %s: freeing soinfo @ %p", si->name, si);
+ TRACE("name %s: freeing soinfo @ %p", si->get_soname(), si);
for (trav = solist; trav != nullptr; trav = trav->next) {
if (trav == si) {
@@ -274,7 +275,7 @@
if (trav == nullptr) {
// si was not in solist
- DL_ERR("name \"%s\"@%p is not in solist!", si->name, si);
+ DL_ERR("name \"%s\"@%p is not in solist!", si->get_soname(), si);
return;
}
@@ -324,6 +325,17 @@
parse_path(path, " :", &g_ld_preload_names);
}
+static bool realpath_fd(int fd, std::string* realpath) {
+ std::vector<char> buf(PATH_MAX), proc_self_fd(PATH_MAX);
+ snprintf(&proc_self_fd[0], proc_self_fd.size(), "/proc/self/fd/%d", fd);
+ if (readlink(&proc_self_fd[0], &buf[0], buf.size()) == -1) {
+ return false;
+ }
+
+ *realpath = std::string(&buf[0]);
+ return true;
+}
+
#if defined(__arm__)
// For a given PC, find the .so that it belongs to.
@@ -377,7 +389,7 @@
return s->st_shndx != SHN_UNDEF;
} else if (ELF_ST_BIND(s->st_info) != STB_LOCAL) {
DL_WARN("unexpected ST_BIND value: %d for '%s' in '%s'",
- ELF_ST_BIND(s->st_info), si->get_string(s->st_name), si->name);
+ ELF_ST_BIND(s->st_info), si->get_string(s->st_name), si->get_soname());
}
return false;
@@ -392,12 +404,12 @@
ElfW(Addr) bloom_word = gnu_bloom_filter_[word_num];
TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p (gnu)",
- symbol_name.get_name(), name, reinterpret_cast<void*>(base));
+ symbol_name.get_name(), get_soname(), reinterpret_cast<void*>(base));
// test against bloom filter
if ((1 & (bloom_word >> (hash % bloom_mask_bits)) & (bloom_word >> (h2 % bloom_mask_bits))) == 0) {
TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p",
- symbol_name.get_name(), name, reinterpret_cast<void*>(base));
+ symbol_name.get_name(), get_soname(), reinterpret_cast<void*>(base));
return nullptr;
}
@@ -407,7 +419,7 @@
if (n == 0) {
TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p",
- symbol_name.get_name(), name, reinterpret_cast<void*>(base));
+ symbol_name.get_name(), get_soname(), reinterpret_cast<void*>(base));
return nullptr;
}
@@ -418,14 +430,14 @@
strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
is_symbol_global_and_defined(this, s)) {
TRACE_TYPE(LOOKUP, "FOUND %s in %s (%p) %zd",
- symbol_name.get_name(), name, reinterpret_cast<void*>(s->st_value),
+ symbol_name.get_name(), get_soname(), reinterpret_cast<void*>(s->st_value),
static_cast<size_t>(s->st_size));
return s;
}
} while ((gnu_chain_[n++] & 1) == 0);
TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p",
- symbol_name.get_name(), name, reinterpret_cast<void*>(base));
+ symbol_name.get_name(), get_soname(), reinterpret_cast<void*>(base));
return nullptr;
}
@@ -434,30 +446,36 @@
uint32_t hash = symbol_name.elf_hash();
TRACE_TYPE(LOOKUP, "SEARCH %s in %s@%p h=%x(elf) %zd",
- symbol_name.get_name(), name, reinterpret_cast<void*>(base), hash, hash % nbucket_);
+ symbol_name.get_name(), get_soname(),
+ reinterpret_cast<void*>(base), hash, hash % nbucket_);
for (uint32_t n = bucket_[hash % nbucket_]; n != 0; n = chain_[n]) {
ElfW(Sym)* s = symtab_ + n;
if (strcmp(get_string(s->st_name), symbol_name.get_name()) == 0 &&
is_symbol_global_and_defined(this, s)) {
TRACE_TYPE(LOOKUP, "FOUND %s in %s (%p) %zd",
- symbol_name.get_name(), name, reinterpret_cast<void*>(s->st_value),
- static_cast<size_t>(s->st_size));
+ symbol_name.get_name(), get_soname(),
+ reinterpret_cast<void*>(s->st_value),
+ static_cast<size_t>(s->st_size));
return s;
}
}
TRACE_TYPE(LOOKUP, "NOT FOUND %s in %s@%p %x %zd",
- symbol_name.get_name(), name, reinterpret_cast<void*>(base), hash, hash % nbucket_);
+ symbol_name.get_name(), get_soname(),
+ reinterpret_cast<void*>(base), hash, hash % nbucket_);
return nullptr;
}
-soinfo::soinfo(const char* name, const struct stat* file_stat,
+soinfo::soinfo(const char* realpath, const struct stat* file_stat,
off64_t file_offset, int rtld_flags) {
memset(this, 0, sizeof(*this));
- strlcpy(this->name, name, sizeof(this->name));
+ if (realpath != nullptr) {
+ realpath_ = realpath;
+ }
+
flags_ = FLAG_NEW_SOINFO;
version_ = SOINFO_VERSION;
@@ -473,7 +491,7 @@
uint32_t SymbolName::elf_hash() {
if (!has_elf_hash_) {
- const unsigned char* name = reinterpret_cast<const unsigned char*>(name_);
+ const uint8_t* name = reinterpret_cast<const uint8_t*>(name_);
uint32_t h = 0, g;
while (*name) {
@@ -493,7 +511,7 @@
uint32_t SymbolName::gnu_hash() {
if (!has_gnu_hash_) {
uint32_t h = 5381;
- const unsigned char* name = reinterpret_cast<const unsigned char*>(name_);
+ const uint8_t* name = reinterpret_cast<const uint8_t*>(name_);
while (*name != 0) {
h += (h << 5) + *name++; // h*33 + c = h + h * 32 + c = h + h << 5 + c
}
@@ -522,7 +540,7 @@
* relocations for -Bsymbolic linked dynamic executables.
*/
if (si_from->has_DT_SYMBOLIC) {
- DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si_from->name, name);
+ DEBUG("%s: looking up %s in local scope (DT_SYMBOLIC)", si_from->get_soname(), name);
s = si_from->find_symbol_by_name(symbol_name);
if (s != nullptr) {
*si_found_in = si_from;
@@ -532,7 +550,8 @@
// 1. Look for it in global_group
if (s == nullptr) {
global_group.visit([&](soinfo* global_si) {
- DEBUG("%s: looking up %s in %s (from global group)", si_from->name, name, global_si->name);
+ DEBUG("%s: looking up %s in %s (from global group)",
+ si_from->get_soname(), name, global_si->get_soname());
s = global_si->find_symbol_by_name(symbol_name);
if (s != nullptr) {
*si_found_in = global_si;
@@ -551,7 +570,8 @@
return true;
}
- DEBUG("%s: looking up %s in %s (from local group)", si_from->name, name, local_si->name);
+ DEBUG("%s: looking up %s in %s (from local group)",
+ si_from->get_soname(), name, local_si->get_soname());
s = local_si->find_symbol_by_name(symbol_name);
if (s != nullptr) {
*si_found_in = local_si;
@@ -565,8 +585,8 @@
if (s != nullptr) {
TRACE_TYPE(LOOKUP, "si %s sym %s s->st_value = %p, "
"found in %s, base = %p, load bias = %p",
- si_from->name, name, reinterpret_cast<void*>(s->st_value),
- (*si_found_in)->name, reinterpret_cast<void*>((*si_found_in)->base),
+ si_from->get_soname(), name, reinterpret_cast<void*>(s->st_value),
+ (*si_found_in)->get_soname(), reinterpret_cast<void*>((*si_found_in)->base),
reinterpret_cast<void*>((*si_found_in)->load_bias));
}
@@ -922,7 +942,7 @@
static int open_library_on_default_path(const char* name, off64_t* file_offset) {
for (size_t i = 0; kDefaultLdPaths[i] != nullptr; ++i) {
char buf[512];
- if(!format_path(buf, sizeof(buf), kDefaultLdPaths[i], name)) {
+ if (!format_path(buf, sizeof(buf), kDefaultLdPaths[i], name)) {
continue;
}
@@ -1053,7 +1073,7 @@
si->get_st_ino() == file_stat.st_ino &&
si->get_file_offset() == file_offset) {
TRACE("library \"%s\" is already loaded under different name/path \"%s\" - "
- "will return existing soinfo", name, si->name);
+ "will return existing soinfo", name, si->get_realpath());
return si;
}
}
@@ -1064,13 +1084,19 @@
return nullptr;
}
+ std::string realpath = name;
+ if (!realpath_fd(fd, &realpath)) {
+ PRINT("cannot resolve realpath for the library \"%s\": %s", name, strerror(errno));
+ realpath = name;
+ }
+
// Read the ELF header and load the segments.
- ElfReader elf_reader(name, fd, file_offset);
+ ElfReader elf_reader(realpath.c_str(), fd, file_offset);
if (!elf_reader.Load(extinfo)) {
return nullptr;
}
- soinfo* si = soinfo_alloc(name, &file_stat, file_offset, rtld_flags);
+ soinfo* si = soinfo_alloc(realpath.c_str(), &file_stat, file_offset, rtld_flags);
if (si == nullptr) {
return nullptr;
}
@@ -1275,7 +1301,7 @@
}
if (!root->can_unload()) {
- TRACE("not unloading '%s' - the binary is flagged with NODELETE", root->name);
+ TRACE("not unloading '%s' - the binary is flagged with NODELETE", root->get_soname());
return;
}
@@ -1298,7 +1324,7 @@
if (si->has_min_version(0)) {
soinfo* child = nullptr;
while ((child = si->get_children().pop_front()) != nullptr) {
- TRACE("%s@%p needs to unload %s@%p", si->name, si, child->name, child);
+ TRACE("%s@%p needs to unload %s@%p", si->get_soname(), si, child->get_soname(), child);
if (local_unload_list.contains(child)) {
continue;
} else if (child->is_linked() && child->get_local_group_root() != root) {
@@ -1308,17 +1334,20 @@
}
}
} else {
-#ifdef __LP64__
- __libc_fatal("soinfo for \"%s\"@%p has no version", si->name, si);
+#if !defined(__arm__)
+ __libc_fatal("soinfo for \"%s\"@%p has no version", si->get_soname(), si);
#else
- PRINT("warning: soinfo for \"%s\"@%p has no version", si->name, si);
+ PRINT("warning: soinfo for \"%s\"@%p has no version", si->get_soname(), si);
for_each_dt_needed(si, [&] (const char* library_name) {
- TRACE("deprecated (old format of soinfo): %s needs to unload %s", si->name, library_name);
+ TRACE("deprecated (old format of soinfo): %s needs to unload %s",
+ si->get_soname(), library_name);
+
soinfo* needed = find_library(library_name, RTLD_NOLOAD, nullptr);
if (needed != nullptr) {
// Not found: for example if symlink was deleted between dlopen and dlclose
// Since we cannot really handle errors at this point - print and continue.
- PRINT("warning: couldn't find %s needed by %s on unload.", library_name, si->name);
+ PRINT("warning: couldn't find %s needed by %s on unload.",
+ library_name, si->get_soname());
return;
} else if (local_unload_list.contains(needed)) {
// already visited
@@ -1348,7 +1377,7 @@
soinfo_unload(si);
}
} else {
- TRACE("not unloading '%s' group, decrementing ref_count to %zd", root->name, ref_count);
+ TRACE("not unloading '%s' group, decrementing ref_count to %zd", root->get_soname(), ref_count);
}
}
@@ -1447,7 +1476,7 @@
const char* sym_name = nullptr;
ElfW(Addr) addend = get_addend(rel, reloc);
- DEBUG("Processing '%s' relocation at index %zd", this->name, idx);
+ DEBUG("Processing '%s' relocation at index %zd", get_soname(), idx);
if (type == R_GENERIC_NONE) {
continue;
}
@@ -1462,7 +1491,7 @@
// We only allow an undefined symbol if this is a weak reference...
s = &symtab_[sym];
if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
- DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
+ DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, get_soname());
return false;
}
@@ -1652,13 +1681,13 @@
/*
* ET_EXEC is not supported so this should not happen.
*
- * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
+ * http://infocenter.arm.com/help/topic/com.arm.doc.ihi0056b/IHI0056B_aaelf64.pdf
*
- * Section 4.7.1.10 "Dynamic relocations"
+ * Section 4.6.11 "Dynamic relocations"
* R_AARCH64_COPY may only appear in executable objects where e_type is
* set to ET_EXEC.
*/
- DL_ERR("%s R_AARCH64_COPY relocations are not supported", name);
+ DL_ERR("%s R_AARCH64_COPY relocations are not supported", get_soname());
return false;
case R_AARCH64_TLS_TPREL64:
TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n",
@@ -1711,11 +1740,11 @@
*
* http://infocenter.arm.com/help/topic/com.arm.doc.ihi0044d/IHI0044D_aaelf.pdf
*
- * Section 4.7.1.10 "Dynamic relocations"
+ * Section 4.6.1.10 "Dynamic relocations"
* R_ARM_COPY may only appear in executable objects where e_type is
* set to ET_EXEC.
*/
- DL_ERR("%s R_ARM_COPY relocations are not supported", name);
+ DL_ERR("%s R_ARM_COPY relocations are not supported", get_soname());
return false;
#elif defined(__i386__)
case R_386_32:
@@ -1747,7 +1776,7 @@
return;
}
- TRACE("[ Calling %s (size %zd) @ %p for '%s' ]", array_name, count, functions, name);
+ TRACE("[ Calling %s (size %zd) @ %p for '%s' ]", array_name, count, functions, get_soname());
int begin = reverse ? (count - 1) : 0;
int end = reverse ? -1 : count;
@@ -1758,7 +1787,7 @@
call_function("function", functions[i]);
}
- TRACE("[ Done calling %s for '%s' ]", array_name, name);
+ TRACE("[ Done calling %s for '%s' ]", array_name, get_soname());
}
void soinfo::call_function(const char* function_name __unused, linker_function_t function) {
@@ -1766,9 +1795,9 @@
return;
}
- TRACE("[ Calling %s @ %p for '%s' ]", function_name, function, name);
+ TRACE("[ Calling %s @ %p for '%s' ]", function_name, function, get_soname());
function();
- TRACE("[ Done calling %s @ %p for '%s' ]", function_name, function, name);
+ TRACE("[ Done calling %s @ %p for '%s' ]", function_name, function, get_soname());
}
void soinfo::call_pre_init_constructors() {
@@ -1797,14 +1826,14 @@
if (!is_main_executable() && preinit_array_ != nullptr) {
// The GNU dynamic linker silently ignores these, but we warn the developer.
PRINT("\"%s\": ignoring %zd-entry DT_PREINIT_ARRAY in shared library!",
- name, preinit_array_count_);
+ get_soname(), preinit_array_count_);
}
get_children().for_each([] (soinfo* si) {
si->call_constructors();
});
- TRACE("\"%s\": calling constructors", name);
+ TRACE("\"%s\": calling constructors", get_soname());
// DT_INIT should be called before DT_INIT_ARRAY if both are present.
call_function("DT_INIT", init_func_);
@@ -1815,7 +1844,7 @@
if (!constructors_called) {
return;
}
- TRACE("\"%s\": calling destructors", name);
+ TRACE("\"%s\": calling destructors", get_soname());
// DT_FINI_ARRAY must be parsed in reverse order.
call_array("DT_FINI_ARRAY", fini_array_, fini_array_count_, true);
@@ -1912,12 +1941,28 @@
}
}
-const char* soinfo::get_soname() {
+const char* soinfo::get_realpath() const {
+#if defined(__arm__)
+ if (has_min_version(2)) {
+ return realpath_.c_str();
+ } else {
+ return old_name_;
+ }
+#else
+ return realpath_.c_str();
+#endif
+}
+
+const char* soinfo::get_soname() const {
+#if defined(__arm__)
if (has_min_version(2)) {
return soname_;
} else {
- return name;
+ return old_name_;
}
+#else
+ return soname_;
+#endif
}
// This is a return on get_children()/get_parents() if
@@ -1950,7 +1995,8 @@
const char* soinfo::get_string(ElfW(Word) index) const {
if (has_min_version(1) && (index >= strtab_size_)) {
- __libc_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d", name, strtab_size_, index);
+ __libc_fatal("%s: strtab out of bounds error; STRSZ=%zd, name=%d",
+ get_soname(), strtab_size_, index);
}
return strtab_ + index;
@@ -2065,13 +2111,13 @@
/* We can't log anything until the linker is relocated */
bool relocating_linker = (flags_ & FLAG_LINKER) != 0;
if (!relocating_linker) {
- INFO("[ linking %s ]", name);
+ INFO("[ linking %s ]", get_soname());
DEBUG("si->base = %p si->flags = 0x%08x", reinterpret_cast<void*>(base), flags_);
}
if (dynamic == nullptr) {
if (!relocating_linker) {
- DL_ERR("missing PT_DYNAMIC in \"%s\"", name);
+ DL_ERR("missing PT_DYNAMIC in \"%s\"", get_soname());
}
return false;
} else {
@@ -2120,7 +2166,7 @@
if (!powerof2(gnu_maskwords_)) {
DL_ERR("invalid maskwords for gnu_hash = 0x%x, in \"%s\" expecting power to two",
- gnu_maskwords_, name);
+ gnu_maskwords_, get_realpath());
return false;
}
--gnu_maskwords_;
@@ -2142,7 +2188,8 @@
case DT_SYMENT:
if (d->d_un.d_val != sizeof(ElfW(Sym))) {
- DL_ERR("invalid DT_SYMENT: %zd in \"%s\"", static_cast<size_t>(d->d_un.d_val), name);
+ DL_ERR("invalid DT_SYMENT: %zd in \"%s\"",
+ static_cast<size_t>(d->d_un.d_val), get_realpath());
return false;
}
break;
@@ -2150,12 +2197,12 @@
case DT_PLTREL:
#if defined(USE_RELA)
if (d->d_un.d_val != DT_RELA) {
- DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", name);
+ DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_RELA", get_realpath());
return false;
}
#else
if (d->d_un.d_val != DT_REL) {
- DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", name);
+ DL_ERR("unsupported DT_PLTREL in \"%s\"; expected DT_REL", get_realpath());
return false;
}
#endif
@@ -2216,11 +2263,11 @@
break;
case DT_ANDROID_REL:
- DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", name);
+ DL_ERR("unsupported DT_ANDROID_REL in \"%s\"", get_realpath());
return false;
case DT_ANDROID_RELSZ:
- DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", name);
+ DL_ERR("unsupported DT_ANDROID_RELSZ in \"%s\"", get_realpath());
return false;
case DT_RELAENT:
@@ -2235,11 +2282,11 @@
break;
case DT_REL:
- DL_ERR("unsupported DT_REL in \"%s\"", name);
+ DL_ERR("unsupported DT_REL in \"%s\"", get_realpath());
return false;
case DT_RELSZ:
- DL_ERR("unsupported DT_RELSZ in \"%s\"", name);
+ DL_ERR("unsupported DT_RELSZ in \"%s\"", get_realpath());
return false;
#else
@@ -2267,11 +2314,11 @@
break;
case DT_ANDROID_RELA:
- DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", name);
+ DL_ERR("unsupported DT_ANDROID_RELA in \"%s\"", get_realpath());
return false;
case DT_ANDROID_RELASZ:
- DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", name);
+ DL_ERR("unsupported DT_ANDROID_RELASZ in \"%s\"", get_realpath());
return false;
// "Indicates that all RELATIVE relocations have been concatenated together,
@@ -2283,27 +2330,27 @@
break;
case DT_RELA:
- DL_ERR("unsupported DT_RELA in \"%s\"", name);
+ DL_ERR("unsupported DT_RELA in \"%s\"", get_realpath());
return false;
case DT_RELASZ:
- DL_ERR("unsupported DT_RELASZ in \"%s\"", name);
+ DL_ERR("unsupported DT_RELASZ in \"%s\"", get_realpath());
return false;
#endif
case DT_INIT:
init_func_ = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
- DEBUG("%s constructors (DT_INIT) found at %p", name, init_func_);
+ DEBUG("%s constructors (DT_INIT) found at %p", get_realpath(), init_func_);
break;
case DT_FINI:
fini_func_ = reinterpret_cast<linker_function_t>(load_bias + d->d_un.d_ptr);
- DEBUG("%s destructors (DT_FINI) found at %p", name, fini_func_);
+ DEBUG("%s destructors (DT_FINI) found at %p", get_realpath(), fini_func_);
break;
case DT_INIT_ARRAY:
init_array_ = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
- DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", name, init_array_);
+ DEBUG("%s constructors (DT_INIT_ARRAY) found at %p", get_realpath(), init_array_);
break;
case DT_INIT_ARRAYSZ:
@@ -2312,7 +2359,7 @@
case DT_FINI_ARRAY:
fini_array_ = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
- DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", name, fini_array_);
+ DEBUG("%s destructors (DT_FINI_ARRAY) found at %p", get_realpath(), fini_array_);
break;
case DT_FINI_ARRAYSZ:
@@ -2321,7 +2368,7 @@
case DT_PREINIT_ARRAY:
preinit_array_ = reinterpret_cast<linker_function_t*>(load_bias + d->d_un.d_ptr);
- DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", name, preinit_array_);
+ DEBUG("%s constructors (DT_PREINIT_ARRAY) found at %p", get_realpath(), preinit_array_);
break;
case DT_PREINIT_ARRAYSZ:
@@ -2330,7 +2377,7 @@
case DT_TEXTREL:
#if defined(__LP64__)
- DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", name);
+ DL_ERR("text relocations (DT_TEXTREL) found in 64-bit ELF file \"%s\"", get_realpath());
return false;
#else
has_text_relocations = true;
@@ -2348,7 +2395,7 @@
case DT_FLAGS:
if (d->d_un.d_val & DF_TEXTREL) {
#if defined(__LP64__)
- DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", name);
+ DL_ERR("text relocations (DF_TEXTREL) found in 64-bit ELF file \"%s\"", get_realpath());
return false;
#else
has_text_relocations = true;
@@ -2415,7 +2462,7 @@
default:
if (!relocating_linker) {
- DL_WARN("%s: unused DT entry: type %p arg %p", name,
+ DL_WARN("%s: unused DT entry: type %p arg %p", get_realpath(),
reinterpret_cast<void*>(d->d_tag), reinterpret_cast<void*>(d->d_un.d_val));
}
break;
@@ -2426,6 +2473,9 @@
for (ElfW(Dyn)* d = dynamic; d->d_tag != DT_NULL; ++d) {
if (d->d_tag == DT_SONAME) {
soname_ = get_string(d->d_un.d_val);
+#if defined(__arm__)
+ strlcpy(old_name_, soname_, sizeof(old_name_));
+#endif
break;
}
}
@@ -2439,15 +2489,16 @@
return false;
}
if (nbucket_ == 0 && gnu_nbucket_ == 0) {
- DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" (new hash type from the future?)", name);
+ DL_ERR("empty/missing DT_HASH/DT_GNU_HASH in \"%s\" "
+ "(new hash type from the future?)", get_soname());
return false;
}
if (strtab_ == 0) {
- DL_ERR("empty/missing DT_STRTAB in \"%s\"", name);
+ DL_ERR("empty/missing DT_STRTAB in \"%s\"", get_soname());
return false;
}
if (symtab_ == 0) {
- DL_ERR("empty/missing DT_SYMTAB in \"%s\"", name);
+ DL_ERR("empty/missing DT_SYMTAB in \"%s\"", get_soname());
return false;
}
return true;
@@ -2466,10 +2517,10 @@
// Make segments writable to allow text relocations to work properly. We will later call
// phdr_table_protect_segments() after all of them are applied and all constructors are run.
DL_WARN("%s has text relocations. This is wasting memory and prevents "
- "security hardening. Please fix.", name);
+ "security hardening. Please fix.", get_soname());
if (phdr_table_unprotect_segments(phdr, phnum, load_bias) < 0) {
DL_ERR("can't unprotect loadable segments for \"%s\": %s",
- name, strerror(errno));
+ get_soname(), strerror(errno));
return false;
}
}
@@ -2482,7 +2533,7 @@
android_relocs_[1] == 'P' &&
(android_relocs_[2] == 'U' || android_relocs_[2] == 'S') &&
android_relocs_[3] == '2') {
- DEBUG("[ android relocating %s ]", name);
+ DEBUG("[ android relocating %s ]", get_soname());
bool relocated = false;
const uint8_t* packed_relocs = android_relocs_ + 4;
@@ -2511,26 +2562,26 @@
#if defined(USE_RELA)
if (rela_ != nullptr) {
- DEBUG("[ relocating %s ]", name);
+ DEBUG("[ relocating %s ]", get_soname());
if (!relocate(plain_reloc_iterator(rela_, rela_count_), global_group, local_group)) {
return false;
}
}
if (plt_rela_ != nullptr) {
- DEBUG("[ relocating %s plt ]", name);
+ DEBUG("[ relocating %s plt ]", get_soname());
if (!relocate(plain_reloc_iterator(plt_rela_, plt_rela_count_), global_group, local_group)) {
return false;
}
}
#else
if (rel_ != nullptr) {
- DEBUG("[ relocating %s ]", name);
+ DEBUG("[ relocating %s ]", get_soname());
if (!relocate(plain_reloc_iterator(rel_, rel_count_), global_group, local_group)) {
return false;
}
}
if (plt_rel_ != nullptr) {
- DEBUG("[ relocating %s plt ]", name);
+ DEBUG("[ relocating %s plt ]", get_soname());
if (!relocate(plain_reloc_iterator(plt_rel_, plt_rel_count_), global_group, local_group)) {
return false;
}
@@ -2543,14 +2594,14 @@
}
#endif
- DEBUG("[ finished linking %s ]", name);
+ DEBUG("[ finished linking %s ]", get_soname());
#if !defined(__LP64__)
if (has_text_relocations) {
// All relocations are done, we can protect our segments back to read-only.
if (phdr_table_protect_segments(phdr, phnum, load_bias) < 0) {
DL_ERR("can't protect segments for \"%s\": %s",
- name, strerror(errno));
+ get_soname(), strerror(errno));
return false;
}
}
@@ -2559,7 +2610,7 @@
/* We can also turn on GNU RELRO protection */
if (phdr_table_protect_gnu_relro(phdr, phnum, load_bias) < 0) {
DL_ERR("can't enable GNU RELRO protection for \"%s\": %s",
- name, strerror(errno));
+ get_soname(), strerror(errno));
return false;
}
@@ -2568,14 +2619,14 @@
if (phdr_table_serialize_gnu_relro(phdr, phnum, load_bias,
extinfo->relro_fd) < 0) {
DL_ERR("failed serializing GNU RELRO section for \"%s\": %s",
- name, strerror(errno));
+ get_soname(), strerror(errno));
return false;
}
} else if (extinfo && (extinfo->flags & ANDROID_DLEXT_USE_RELRO)) {
if (phdr_table_map_gnu_relro(phdr, phnum, load_bias,
extinfo->relro_fd) < 0) {
DL_ERR("failed mapping GNU RELRO section for \"%s\": %s",
- name, strerror(errno));
+ get_soname(), strerror(errno));
return false;
}
}
@@ -2617,7 +2668,12 @@
#else
#define LINKER_PATH "/system/bin/linker"
#endif
-static soinfo linker_soinfo_for_gdb(LINKER_PATH, nullptr, 0, 0);
+
+// This is done to avoid calling c-tor prematurely
+// because soinfo c-tor needs memory allocator
+// which might be initialized after global variables.
+static uint8_t linker_soinfo_for_gdb_buf[sizeof(soinfo)] __attribute__((aligned(8)));
+static soinfo* linker_soinfo_for_gdb = nullptr;
/* gdb expects the linker to be in the debug shared object list.
* Without this, gdb has trouble locating the linker's ".text"
@@ -2627,7 +2683,9 @@
* be on the soinfo list.
*/
static void init_linker_info_for_gdb(ElfW(Addr) linker_base) {
- linker_soinfo_for_gdb.base = linker_base;
+ linker_soinfo_for_gdb = new (linker_soinfo_for_gdb_buf) soinfo(LINKER_PATH, nullptr, 0, 0);
+
+ linker_soinfo_for_gdb->base = linker_base;
/*
* Set the dynamic field in the link map otherwise gdb will complain with
@@ -2638,8 +2696,8 @@
ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_base);
ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_base + elf_hdr->e_phoff);
phdr_table_get_dynamic_section(phdr, elf_hdr->e_phnum, linker_base,
- &linker_soinfo_for_gdb.dynamic, nullptr);
- insert_soinfo_into_debug_map(&linker_soinfo_for_gdb);
+ &linker_soinfo_for_gdb->dynamic, nullptr);
+ insert_soinfo_into_debug_map(linker_soinfo_for_gdb);
}
/*
@@ -2837,7 +2895,7 @@
fflush(stdout);
#endif
- TRACE("[ Ready to execute '%s' @ %p ]", si->name, reinterpret_cast<void*>(si->entry));
+ TRACE("[ Ready to execute '%s' @ %p ]", si->get_soname(), reinterpret_cast<void*>(si->entry));
return si->entry;
}
@@ -2883,7 +2941,7 @@
ElfW(Ehdr)* elf_hdr = reinterpret_cast<ElfW(Ehdr)*>(linker_addr);
ElfW(Phdr)* phdr = reinterpret_cast<ElfW(Phdr)*>(linker_addr + elf_hdr->e_phoff);
- soinfo linker_so("[dynamic linker]", nullptr, 0, 0);
+ soinfo linker_so(nullptr, nullptr, 0, 0);
// If the linker is not acting as PT_INTERP entry_point is equal to
// _start. Which means that the linker is running as an executable and
diff --git a/linker/linker.h b/linker/linker.h
index ec3d8f0..7482581 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -39,6 +39,8 @@
#include "private/libc_logging.h"
#include "linked_list.h"
+#include <string>
+
#define DL_ERR(fmt, x...) \
do { \
__libc_format_buffer(linker_get_error_buffer(), linker_get_error_buffer_size(), fmt, ##x); \
@@ -94,7 +96,9 @@
#define SOINFO_VERSION 2
+#if defined(__arm__)
#define SOINFO_NAME_LEN 128
+#endif
typedef void (*linker_function_t)();
@@ -141,8 +145,11 @@
struct soinfo {
public:
typedef LinkedList<soinfo, SoinfoListAllocator> soinfo_list_t;
+#if defined(__arm__)
+ private:
+ char old_name_[SOINFO_NAME_LEN];
+#endif
public:
- char name[SOINFO_NAME_LEN];
const ElfW(Phdr)* phdr;
size_t phnum;
ElfW(Addr) entry;
@@ -263,8 +270,12 @@
bool can_unload() const;
bool is_gnu_hash() const;
- bool inline has_min_version(uint32_t min_version) const {
+ bool inline has_min_version(uint32_t min_version __unused) const {
+#if defined(__arm__)
return (flags_ & FLAG_NEW_SOINFO) != 0 && version_ >= min_version;
+#else
+ return true;
+#endif
}
bool is_linked() const;
@@ -279,7 +290,8 @@
soinfo* get_local_group_root() const;
- const char* get_soname();
+ const char* get_soname() const;
+ const char* get_realpath() const;
private:
ElfW(Sym)* elf_lookup(SymbolName& symbol_name);
@@ -327,6 +339,7 @@
size_t android_relocs_size_;
const char* soname_;
+ std::string realpath_;
friend soinfo* get_libdl_info();
};
diff --git a/linker/linker_mips.cpp b/linker/linker_mips.cpp
index 44d39fd..14f6a1b 100644
--- a/linker/linker_mips.cpp
+++ b/linker/linker_mips.cpp
@@ -64,7 +64,7 @@
ElfW(Addr) sym_addr = 0;
const char* sym_name = nullptr;
- DEBUG("Processing '%s' relocation at index %zd", this->name, idx);
+ DEBUG("Processing '%s' relocation at index %zd", get_soname(), idx);
if (type == R_GENERIC_NONE) {
continue;
}
@@ -77,7 +77,7 @@
s = soinfo_do_lookup(this, sym_name, &lsi, global_group,local_group);
if (s == nullptr) {
// mips does not support relocation with weak-undefined symbols
- DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
+ DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, get_soname());
return false;
} else {
// We got a definition.
diff --git a/tests/dlext_test.cpp b/tests/dlext_test.cpp
index 700abff..56a8f6f 100644
--- a/tests/dlext_test.cpp
+++ b/tests/dlext_test.cpp
@@ -134,6 +134,10 @@
TEST_F(DlExtTest, ExtInfoUseFdWithInvalidOffset) {
const std::string lib_path = std::string(getenv("ANDROID_DATA")) + LIBZIPPATH;
+ // lib_path is relative when $ANDROID_DATA is relative
+ char lib_realpath_buf[PATH_MAX];
+ ASSERT_TRUE(realpath(lib_path.c_str(), lib_realpath_buf) == lib_realpath_buf);
+ const std::string lib_realpath = std::string(lib_realpath_buf);
android_dlextinfo extinfo;
extinfo.flags = ANDROID_DLEXT_USE_LIBRARY_FD | ANDROID_DLEXT_USE_LIBRARY_FD_OFFSET;
@@ -156,9 +160,9 @@
ASSERT_SUBSTR("dlopen failed: file offset for the library \"libname_placeholder\" is negative", dlerror());
extinfo.library_fd_offset = PAGE_SIZE;
- handle_ = android_dlopen_ext("libname_placeholder", RTLD_NOW, &extinfo);
+ handle_ = android_dlopen_ext("libname_ignored", RTLD_NOW, &extinfo);
ASSERT_TRUE(handle_ == nullptr);
- ASSERT_STREQ("dlopen failed: \"libname_placeholder\" has bad ELF magic", dlerror());
+ ASSERT_EQ("dlopen failed: \"" + lib_realpath + "\" has bad ELF magic", dlerror());
close(extinfo.library_fd);
}
diff --git a/tests/dlfcn_test.cpp b/tests/dlfcn_test.cpp
index a63c070..708e2cd 100644
--- a/tests/dlfcn_test.cpp
+++ b/tests/dlfcn_test.cpp
@@ -26,9 +26,12 @@
#include <string>
+#include "utils.h"
+
#define ASSERT_SUBSTR(needle, haystack) \
ASSERT_PRED_FORMAT2(::testing::IsSubstring, needle, haystack)
+
static bool g_called = false;
extern "C" void DlSymTestFunction() {
g_called = true;
@@ -699,7 +702,7 @@
ASSERT_EQ(0, dlclose(self));
}
-TEST(dlfcn, dladdr) {
+TEST(dlfcn, dladdr_executable) {
dlerror(); // Clear any pending errors.
void* self = dlopen(NULL, RTLD_NOW);
ASSERT_TRUE(self != NULL);
@@ -720,13 +723,11 @@
rc = readlink("/proc/self/exe", executable_path, sizeof(executable_path));
ASSERT_NE(rc, -1);
executable_path[rc] = '\0';
- std::string executable_name(basename(executable_path));
// The filename should be that of this executable.
- // Note that we don't know whether or not we have the full path, so we want an "ends_with" test.
- std::string dli_fname(info.dli_fname);
- dli_fname = basename(&dli_fname[0]);
- ASSERT_EQ(dli_fname, executable_name);
+ char dli_realpath[PATH_MAX];
+ ASSERT_TRUE(realpath(info.dli_fname, dli_realpath) != nullptr);
+ ASSERT_STREQ(executable_path, dli_realpath);
// The symbol name should be the symbol we looked up.
ASSERT_STREQ(info.dli_sname, "DlSymTestFunction");
@@ -734,22 +735,16 @@
// The address should be the exact address of the symbol.
ASSERT_EQ(info.dli_saddr, sym);
- // Look in /proc/pid/maps to find out what address we were loaded at.
- // TODO: factor /proc/pid/maps parsing out into a class and reuse all over bionic.
- void* base_address = NULL;
- char line[BUFSIZ];
- FILE* fp = fopen("/proc/self/maps", "r");
- ASSERT_TRUE(fp != NULL);
- while (fgets(line, sizeof(line), fp) != NULL) {
- uintptr_t start = strtoul(line, 0, 16);
- line[strlen(line) - 1] = '\0'; // Chomp the '\n'.
- char* path = strchr(line, '/');
- if (path != NULL && strcmp(executable_path, path) == 0) {
- base_address = reinterpret_cast<void*>(start);
+ std::vector<map_record> maps;
+ ASSERT_TRUE(Maps::parse_maps(&maps));
+
+ void* base_address = nullptr;
+ for (const map_record& rec : maps) {
+ if (executable_path == rec.pathname) {
+ base_address = reinterpret_cast<void*>(rec.addr_start);
break;
}
}
- fclose(fp);
// The base address should be the address we were loaded at.
ASSERT_EQ(info.dli_fbase, base_address);
@@ -757,6 +752,32 @@
ASSERT_EQ(0, dlclose(self));
}
+#if defined(__LP64__)
+#define BIONIC_PATH_TO_LIBC "/system/lib64/libc.so"
+#else
+#define BIONIC_PATH_TO_LIBC "/system/lib/libc.so"
+#endif
+
+TEST(dlfcn, dladdr_libc) {
+#if defined(__BIONIC__)
+ Dl_info info;
+ void* addr = reinterpret_cast<void*>(puts); // well-known libc function
+ ASSERT_TRUE(dladdr(addr, &info) != 0);
+
+ // /system/lib is symlink when this test is executed on host.
+ char libc_realpath[PATH_MAX];
+ ASSERT_TRUE(realpath(BIONIC_PATH_TO_LIBC, libc_realpath) == libc_realpath);
+
+ ASSERT_STREQ(libc_realpath, info.dli_fname);
+ // TODO: add check for dfi_fbase
+ ASSERT_STREQ("puts", info.dli_sname);
+ ASSERT_EQ(addr, info.dli_saddr);
+#else
+ GTEST_LOG_(INFO) << "This test does nothing for glibc. Glibc returns path from ldconfig "
+ "for libc.so, which is symlink itself (not a realpath).\n";
+#endif
+}
+
TEST(dlfcn, dladdr_invalid) {
Dl_info info;
diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp
index 6dbd964..a299f02 100644
--- a/tests/pthread_test.cpp
+++ b/tests/pthread_test.cpp
@@ -673,6 +673,37 @@
#endif // __BIONIC__
}
+TEST(pthread, pthread_rwlockattr_smoke) {
+ pthread_rwlockattr_t attr;
+ ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
+
+ int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED};
+ for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) {
+ ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i]));
+ int pshared;
+ ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared));
+ ASSERT_EQ(pshared_value_array[i], pshared);
+ }
+
+ int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP,
+ PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP};
+ for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) {
+ ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i]));
+ int kind;
+ ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind));
+ ASSERT_EQ(kind_array[i], kind);
+ }
+
+ ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
+}
+
+TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) {
+ pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER;
+ pthread_rwlock_t lock2;
+ ASSERT_EQ(0, pthread_rwlock_init(&lock2, NULL));
+ ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1)));
+}
+
TEST(pthread, pthread_rwlock_smoke) {
pthread_rwlock_t l;
ASSERT_EQ(0, pthread_rwlock_init(&l, NULL));
@@ -708,7 +739,6 @@
ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
ASSERT_EQ(0, pthread_rwlock_unlock(&l));
-#ifdef __BIONIC__
// EDEADLK in "read after write"
ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l));
@@ -718,7 +748,6 @@
ASSERT_EQ(0, pthread_rwlock_wrlock(&l));
ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l));
ASSERT_EQ(0, pthread_rwlock_unlock(&l));
-#endif
ASSERT_EQ(0, pthread_rwlock_destroy(&l));
}
@@ -820,6 +849,111 @@
ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock));
}
+class RwlockKindTestHelper {
+ private:
+ struct ThreadArg {
+ RwlockKindTestHelper* helper;
+ std::atomic<pid_t>& tid;
+
+ ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid)
+ : helper(helper), tid(tid) { }
+ };
+
+ public:
+ pthread_rwlock_t lock;
+
+ public:
+ RwlockKindTestHelper(int kind_type) {
+ InitRwlock(kind_type);
+ }
+
+ ~RwlockKindTestHelper() {
+ DestroyRwlock();
+ }
+
+ void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) {
+ tid = 0;
+ ThreadArg* arg = new ThreadArg(this, tid);
+ ASSERT_EQ(0, pthread_create(&thread, NULL,
+ reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg));
+ }
+
+ void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) {
+ tid = 0;
+ ThreadArg* arg = new ThreadArg(this, tid);
+ ASSERT_EQ(0, pthread_create(&thread, NULL,
+ reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg));
+ }
+
+ private:
+ void InitRwlock(int kind_type) {
+ pthread_rwlockattr_t attr;
+ ASSERT_EQ(0, pthread_rwlockattr_init(&attr));
+ ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type));
+ ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr));
+ ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr));
+ }
+
+ void DestroyRwlock() {
+ ASSERT_EQ(0, pthread_rwlock_destroy(&lock));
+ }
+
+ static void WriterThreadFn(ThreadArg* arg) {
+ arg->tid = gettid();
+
+ RwlockKindTestHelper* helper = arg->helper;
+ ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock));
+ ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
+ delete arg;
+ }
+
+ static void ReaderThreadFn(ThreadArg* arg) {
+ arg->tid = gettid();
+
+ RwlockKindTestHelper* helper = arg->helper;
+ ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock));
+ ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock));
+ delete arg;
+ }
+};
+
+TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) {
+ RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP);
+ ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
+
+ pthread_t writer_thread;
+ std::atomic<pid_t> writer_tid;
+ helper.CreateWriterThread(writer_thread, writer_tid);
+ WaitUntilThreadSleep(writer_tid);
+
+ pthread_t reader_thread;
+ std::atomic<pid_t> reader_tid;
+ helper.CreateReaderThread(reader_thread, reader_tid);
+ ASSERT_EQ(0, pthread_join(reader_thread, NULL));
+
+ ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
+ ASSERT_EQ(0, pthread_join(writer_thread, NULL));
+}
+
+TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) {
+ RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
+ ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock));
+
+ pthread_t writer_thread;
+ std::atomic<pid_t> writer_tid;
+ helper.CreateWriterThread(writer_thread, writer_tid);
+ WaitUntilThreadSleep(writer_tid);
+
+ pthread_t reader_thread;
+ std::atomic<pid_t> reader_tid;
+ helper.CreateReaderThread(reader_thread, reader_tid);
+ WaitUntilThreadSleep(reader_tid);
+
+ ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock));
+ ASSERT_EQ(0, pthread_join(writer_thread, NULL));
+ ASSERT_EQ(0, pthread_join(reader_thread, NULL));
+}
+
static int g_once_fn_call_count = 0;
static void OnceFn() {
++g_once_fn_call_count;
diff --git a/tests/stdio_test.cpp b/tests/stdio_test.cpp
index 2ecfc60..62677cd 100644
--- a/tests/stdio_test.cpp
+++ b/tests/stdio_test.cpp
@@ -151,6 +151,15 @@
fclose(fp);
}
+TEST(stdio, getdelim_directory) {
+ FILE* fp = fopen("/proc", "r");
+ ASSERT_TRUE(fp != NULL);
+ char* word_read;
+ size_t allocated_length;
+ ASSERT_EQ(-1, getdelim(&word_read, &allocated_length, ' ', fp));
+ fclose(fp);
+}
+
TEST(stdio, getline) {
FILE* fp = tmpfile();
ASSERT_TRUE(fp != NULL);
diff --git a/tests/utils.h b/tests/utils.h
new file mode 100644
index 0000000..fd012a3
--- /dev/null
+++ b/tests/utils.h
@@ -0,0 +1,84 @@
+/*
+ * Copyright (C) 2012 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#ifndef __TEST_UTILS_H
+#define __TEST_UTILS_H
+#include <inttypes.h>
+#include <sys/mman.h>
+
+#include "private/ScopeGuard.h"
+
+struct map_record {
+ uintptr_t addr_start;
+ uintptr_t addr_end;
+
+ int perms;
+
+ size_t offset;
+
+ dev_t device;
+ ino_t inode;
+
+ std::string pathname;
+};
+
+class Maps {
+ public:
+ static bool parse_maps(std::vector<map_record>* maps) {
+ char path[64];
+ snprintf(path, sizeof(path), "/proc/self/task/%d/maps", getpid());
+ FILE* fp = fopen(path, "re");
+ if (fp == nullptr) {
+ return false;
+ }
+
+ auto fp_guard = make_scope_guard([&]() {
+ fclose(fp);
+ });
+
+ char line[BUFSIZ];
+ while (fgets(line, sizeof(line), fp) != nullptr) {
+ map_record record;
+ uint32_t dev_major, dev_minor;
+ char pathstr[BUFSIZ];
+ char prot[5]; // sizeof("rwxp")
+ if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %4s %" SCNxPTR " %x:%x %lu %s",
+ &record.addr_start, &record.addr_end, prot, &record.offset,
+ &dev_major, &dev_minor, &record.inode, pathstr) == 8) {
+ record.perms = 0;
+ if (prot[0] == 'r') {
+ record.perms |= PROT_READ;
+ }
+ if (prot[1] == 'w') {
+ record.perms |= PROT_WRITE;
+ }
+ if (prot[2] == 'x') {
+ record.perms |= PROT_EXEC;
+ }
+
+ // TODO: parse shared/private?
+
+ record.device = makedev(dev_major, dev_minor);
+ record.pathname = pathstr;
+ maps->push_back(record);
+ }
+ }
+
+ return true;
+ }
+};
+
+#endif
diff --git a/tools/bionicbb/gerrit.py b/tools/bionicbb/gerrit.py
index 40719b4..9c62c6a 100644
--- a/tools/bionicbb/gerrit.py
+++ b/tools/bionicbb/gerrit.py
@@ -29,6 +29,12 @@
call('/changes/{}/revisions/{}/commit'.format(change_id, revision)))
+def get_files_for_revision(change_id, revision):
+ return json.loads(
+ call('/changes/{}/revisions/{}/files'.format(
+ change_id, revision))).keys()
+
+
def call(endpoint, method='GET'):
if method != 'GET':
raise NotImplementedError('Currently only HTTP GET is supported.')
diff --git a/tools/bionicbb/gmail_listener.py b/tools/bionicbb/gmail_listener.py
index 770f0c4..dd0c008 100644
--- a/tools/bionicbb/gmail_listener.py
+++ b/tools/bionicbb/gmail_listener.py
@@ -19,6 +19,7 @@
import httplib2
import jenkinsapi
import json
+import os
import re
import requests
import termcolor
@@ -51,15 +52,41 @@
return headers
-def should_skip_message(info):
- if info['MessageType'] in ('newchange', 'newpatchset', 'comment'):
- commit = gerrit.get_commit(info['Change-Id'], info['PatchSet'])
- committer = commit['committer']['email']
- return not committer.endswith('@google.com')
- else:
- raise ValueError('should_skip_message() is only valid for new '
+def is_untrusted_committer(change_id, patch_set):
+ # TODO(danalbert): Needs to be based on the account that made the comment.
+ commit = gerrit.get_commit(change_id, patch_set)
+ committer = commit['committer']['email']
+ return not committer.endswith('@google.com')
+
+
+def contains_cleanspec(change_id, patch_set):
+ files = gerrit.get_files_for_revision(change_id, patch_set)
+ return 'CleanSpec.mk' in [os.path.basename(f) for f in files]
+
+
+def contains_bionicbb(change_id, patch_set):
+ files = gerrit.get_files_for_revision(change_id, patch_set)
+ return any('tools/bionicbb' in f for f in files)
+
+
+def should_skip_build(info):
+ if info['MessageType'] not in ('newchange', 'newpatchset', 'comment'):
+ raise ValueError('should_skip_build() is only valid for new '
'changes, patch sets, and commits.')
+ change_id = info['Change-Id']
+ patch_set = info['PatchSet']
+
+ checks = [
+ is_untrusted_committer,
+ contains_cleanspec,
+ contains_bionicbb,
+ ]
+ for check in checks:
+ if check(change_id, patch_set):
+ return True
+ return False
+
def build_service():
from apiclient.discovery import build
@@ -214,7 +241,7 @@
def handle_change(gerrit_info, _, dry_run):
- if should_skip_message(gerrit_info):
+ if should_skip_build(gerrit_info):
return True
return build_project(gerrit_info, dry_run)
handle_newchange = handle_change
@@ -246,8 +273,7 @@
if 'Verified+1' in body:
drop_rejection(gerrit_info, dry_run)
- # TODO(danalbert): Needs to be based on the account that made the comment.
- if should_skip_message(gerrit_info):
+ if should_skip_build(gerrit_info):
return True
command_map = {
@@ -290,6 +316,7 @@
gerrit_info['Change-Id'])
return True
handle_abandon = skip_handler
+handle_merge_failed = skip_handler
handle_merged = skip_handler
handle_restore = skip_handler
handle_revert = skip_handler
@@ -303,7 +330,8 @@
print termcolor.colored('No info found: {}'.format(msg['id']),
'red')
msg_type = gerrit_info['MessageType']
- handler = 'handle_{}'.format(gerrit_info['MessageType'])
+ handler = 'handle_{}'.format(
+ gerrit_info['MessageType'].replace('-', '_'))
if handler in globals():
return globals()[handler](gerrit_info, body, dry_run)
else:
diff --git a/tools/bionicbb/test_gmail_listener.py b/tools/bionicbb/test_gmail_listener.py
index 6545cdc..f8b9ab6 100644
--- a/tools/bionicbb/test_gmail_listener.py
+++ b/tools/bionicbb/test_gmail_listener.py
@@ -3,61 +3,90 @@
import unittest
-class TestShouldSkipMessage(unittest.TestCase):
- def test_accepts_googlers(self):
+class TestShouldSkipBuild(unittest.TestCase):
+ @mock.patch('gmail_listener.contains_bionicbb')
+ @mock.patch('gmail_listener.contains_cleanspec')
+ @mock.patch('gerrit.get_commit')
+ def test_accepts_googlers(self, mock_commit, *other_checks):
+ mock_commit.return_value = {
+ 'committer': {'email': 'googler@google.com'}
+ }
+
+ for other_check in other_checks:
+ other_check.return_value = False
+
for message_type in ('newchange', 'newpatchset', 'comment'):
- with mock.patch('gerrit.get_commit') as mock_commit:
- mock_commit.return_value = {
- 'committer': {'email': 'googler@google.com'}
- }
+ self.assertFalse(gmail_listener.should_skip_build({
+ 'MessageType': message_type,
+ 'Change-Id': '',
+ 'PatchSet': '',
+ }))
- self.assertFalse(gmail_listener.should_skip_message({
- 'MessageType': message_type,
- 'Change-Id': '',
- 'PatchSet': '',
- }))
+ @mock.patch('gmail_listener.contains_bionicbb')
+ @mock.patch('gmail_listener.contains_cleanspec')
+ @mock.patch('gerrit.get_commit')
+ def test_rejects_googlish_domains(self, mock_commit, *other_checks):
+ mock_commit.return_value = {
+ 'committer': {'email': 'fakegoogler@google.com.fake.com'}
+ }
- def test_rejects_non_googlers(self):
+ for other_check in other_checks:
+ other_check.return_value = False
+
for message_type in ('newchange', 'newpatchset', 'comment'):
- with mock.patch('gerrit.get_commit') as mock_commit:
- mock_commit.return_value = {
- 'committer': {'email': 'fakegoogler@google.com.fake.com'}
- }
+ self.assertTrue(gmail_listener.should_skip_build({
+ 'MessageType': message_type,
+ 'Change-Id': '',
+ 'PatchSet': '',
+ }))
- self.assertTrue(gmail_listener.should_skip_message({
- 'MessageType': message_type,
- 'Change-Id': '',
- 'PatchSet': '',
- }))
+ @mock.patch('gmail_listener.contains_bionicbb')
+ @mock.patch('gmail_listener.contains_cleanspec')
+ @mock.patch('gerrit.get_commit')
+ def test_rejects_non_googlers(self, mock_commit, *other_checks):
+ mock_commit.return_value = {
+ 'committer': {'email': 'johndoe@example.com'}
+ }
- with mock.patch('gerrit.get_commit') as mock_commit:
- mock_commit.return_value = {
- 'committer': {'email': 'johndoe@example.com'}
- }
+ for other_check in other_checks:
+ other_check.return_value = False
- self.assertTrue(gmail_listener.should_skip_message({
- 'MessageType': message_type,
- 'Change-Id': '',
- 'PatchSet': '',
- }))
-
- def test_calls_gerrit_get_commit(self): # pylint: disable=no-self-use
for message_type in ('newchange', 'newpatchset', 'comment'):
- with mock.patch('gerrit.get_commit') as mock_commit:
- gmail_listener.should_skip_message({
- 'MessageType': message_type,
- 'Change-Id': 'foo',
- 'PatchSet': 'bar',
- })
- mock_commit.assert_called_once_with('foo', 'bar')
+ self.assertTrue(gmail_listener.should_skip_build({
+ 'MessageType': message_type,
+ 'Change-Id': '',
+ 'PatchSet': '',
+ }))
- with mock.patch('gerrit.get_commit') as mock_commit:
- gmail_listener.should_skip_message({
- 'MessageType': message_type,
- 'Change-Id': 'baz',
- 'PatchSet': 'qux',
- })
- mock_commit.assert_called_once_with('baz', 'qux')
+ @mock.patch('gmail_listener.contains_bionicbb')
+ @mock.patch('gmail_listener.is_untrusted_committer')
+ @mock.patch('gerrit.get_files_for_revision')
+ def test_skips_cleanspecs(self, mock_files, *other_checks):
+ mock_files.return_value = ['foo/CleanSpec.mk']
+ for other_check in other_checks:
+ other_check.return_value = False
+
+ for message_type in ('newchange', 'newpatchset', 'comment'):
+ self.assertTrue(gmail_listener.should_skip_build({
+ 'MessageType': message_type,
+ 'Change-Id': '',
+ 'PatchSet': '',
+ }))
+
+ @mock.patch('gmail_listener.contains_cleanspec')
+ @mock.patch('gmail_listener.is_untrusted_committer')
+ @mock.patch('gerrit.get_files_for_revision')
+ def test_skips_bionicbb(self, mock_files, *other_checks):
+ mock_files.return_value = ['tools/bionicbb/common.sh']
+ for other_check in other_checks:
+ other_check.return_value = False
+
+ for message_type in ('newchange', 'newpatchset', 'comment'):
+ self.assertTrue(gmail_listener.should_skip_build({
+ 'MessageType': message_type,
+ 'Change-Id': '',
+ 'PatchSet': '',
+ }))
if __name__ == '__main__':