Merge "Improve <stdio_ext.h> testing."
diff --git a/benchmarks/Android.mk b/benchmarks/Android.mk
index 5ce8542..8f5fd41 100644
--- a/benchmarks/Android.mk
+++ b/benchmarks/Android.mk
@@ -19,6 +19,27 @@
LOCAL_PATH := $(call my-dir)
# -----------------------------------------------------------------------------
+# Benchmarks library, usable by projects outside this directory.
+# -----------------------------------------------------------------------------
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libbenchmark
+LOCAL_CFLAGS += -O2 -Wall -Wextra -Werror
+LOCAL_SRC_FILES := benchmark_main.cpp
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+include $(BUILD_STATIC_LIBRARY)
+
+include $(CLEAR_VARS)
+LOCAL_MODULE := libbenchmark
+LOCAL_CFLAGS += -O2 -Wall -Wextra -Werror
+LOCAL_SRC_FILES := benchmark_main.cpp
+LOCAL_C_INCLUDES := $(LOCAL_PATH)/include
+LOCAL_EXPORT_C_INCLUDE_DIRS := $(LOCAL_PATH)/include
+LOCAL_MULTILIB := both
+include $(BUILD_HOST_STATIC_LIBRARY)
+
+# -----------------------------------------------------------------------------
# Benchmarks.
# -----------------------------------------------------------------------------
@@ -30,7 +51,6 @@
-std=gnu++11 \
benchmark_src_files = \
- benchmark_main.cpp \
math_benchmark.cpp \
pthread_benchmark.cpp \
semaphore_benchmark.cpp \
@@ -47,10 +67,9 @@
LOCAL_MODULE_STEM_32 := bionic-benchmarks32
LOCAL_MODULE_STEM_64 := bionic-benchmarks64
LOCAL_MULTILIB := both
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
LOCAL_CFLAGS += $(benchmark_c_flags)
LOCAL_SRC_FILES := $(benchmark_src_files) property_benchmark.cpp
-LOCAL_CXX_STL := libc++
+LOCAL_STATIC_LIBRARIES += libbenchmark
include $(BUILD_EXECUTABLE)
# We don't build a static benchmark executable because it's not usually
@@ -65,11 +84,10 @@
LOCAL_MODULE_STEM_32 := bionic-benchmarks-glibc32
LOCAL_MODULE_STEM_64 := bionic-benchmarks-glibc64
LOCAL_MULTILIB := both
-LOCAL_ADDITIONAL_DEPENDENCIES := $(LOCAL_PATH)/Android.mk
LOCAL_CFLAGS += $(benchmark_c_flags)
LOCAL_LDFLAGS += -lrt
LOCAL_SRC_FILES := $(benchmark_src_files)
-LOCAL_CXX_STL := libc++
+LOCAL_STATIC_LIBRARIES += libbenchmark
include $(BUILD_HOST_EXECUTABLE)
ifeq ($(HOST_OS)-$(HOST_ARCH),$(filter $(HOST_OS)-$(HOST_ARCH),linux-x86 linux-x86_64))
diff --git a/benchmarks/benchmark_main.cpp b/benchmarks/benchmark_main.cpp
index 815d56b..fae09be 100644
--- a/benchmarks/benchmark_main.cpp
+++ b/benchmarks/benchmark_main.cpp
@@ -14,7 +14,7 @@
* limitations under the License.
*/
-#include "benchmark.h"
+#include <benchmark.h>
#include <regex.h>
#include <stdio.h>
@@ -22,19 +22,57 @@
#include <time.h>
#include <string>
-#include <map>
+#include <vector>
#include <inttypes.h>
static int64_t g_bytes_processed;
static int64_t g_benchmark_total_time_ns;
static int64_t g_benchmark_start_time_ns;
-
-typedef std::map<std::string, ::testing::Benchmark*> BenchmarkMap;
-typedef BenchmarkMap::iterator BenchmarkMapIt;
-static BenchmarkMap g_benchmarks;
static int g_name_column_width = 20;
+typedef std::vector<::testing::Benchmark*> BenchmarkList;
+
+static BenchmarkList& Benchmarks() {
+ static BenchmarkList benchmarks;
+ return benchmarks;
+}
+
+// Similar to the code in art, but supporting both binary and decimal prefixes.
+static std::string PrettyInt(uint64_t count, size_t base) {
+ if (base != 2 && base != 10) abort();
+
+ // The byte thresholds at which we display amounts. A count is displayed
+ // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
+ static const uint64_t kUnitThresholds2[] = {
+ 1024*1024*1024 /* Gi */, 2*1024*1024 /* Mi */, 3*1024 /* Ki */, 0,
+ };
+ static const uint64_t kUnitThresholds10[] = {
+ 1000*1000*1000 /* G */, 2*1000*1000 /* M */, 3*1000 /* k */, 0,
+ };
+ static const uint64_t kAmountPerUnit2[] = { 1024*1024*1024, 1024*1024, 1024, 1 };
+ static const uint64_t kAmountPerUnit10[] = { 1000*1000*1000, 1000*1000, 1000, 1 };
+ static const char* const kUnitStrings2[] = { "Gi", "Mi", "Ki", "" };
+ static const char* const kUnitStrings10[] = { "G", "M", "k", "" };
+
+ // Which set are we using?
+ const uint64_t* kUnitThresholds = ((base == 2) ? kUnitThresholds2 : kUnitThresholds10);
+ const uint64_t* kAmountPerUnit = ((base == 2) ? kAmountPerUnit2 : kAmountPerUnit10);
+ const char* const* kUnitStrings = ((base == 2) ? kUnitStrings2 : kUnitStrings10);
+
+ size_t i = 0;
+ for (; kUnitThresholds[i] != 0; ++i) {
+ if (count >= kUnitThresholds[i]) {
+ break;
+ }
+ }
+ char* s = NULL;
+ asprintf(&s, "%" PRId64 "%s", count / kAmountPerUnit[i], kUnitStrings[i]);
+ std::string result(s);
+ free(s);
+ return result;
+}
+
static int Round(int n) {
int base = 1;
while (base*10 < n) {
@@ -98,7 +136,7 @@
exit(EXIT_FAILURE);
}
- g_benchmarks.insert(std::make_pair(name, this));
+ Benchmarks().push_back(this);
}
void Benchmark::Run() {
@@ -130,44 +168,46 @@
}
void Benchmark::RunWithArg(int arg) {
- // run once in case it's expensive
+ // Run once in case it's expensive.
int iterations = 1;
+ int64_t realStartTime = NanoTime();
RunRepeatedlyWithArg(iterations, arg);
- while (g_benchmark_total_time_ns < 1e9 && iterations < 1e9) {
+ int64_t realTotalTime = NanoTime() - realStartTime;
+ while (realTotalTime < 1e9 && iterations < 1e8) {
int last = iterations;
- if (g_benchmark_total_time_ns/iterations == 0) {
+ if (realTotalTime/iterations == 0) {
iterations = 1e9;
} else {
- iterations = 1e9 / (g_benchmark_total_time_ns/iterations);
+ iterations = 1e9 / (realTotalTime/iterations);
}
iterations = std::max(last + 1, std::min(iterations + iterations/2, 100*last));
iterations = Round(iterations);
+ realStartTime = NanoTime();
RunRepeatedlyWithArg(iterations, arg);
+ realTotalTime = NanoTime() - realStartTime;
}
char throughput[100];
throughput[0] = '\0';
+
if (g_benchmark_total_time_ns > 0 && g_bytes_processed > 0) {
- double mib_processed = static_cast<double>(g_bytes_processed)/1e6;
+ double gib_processed = static_cast<double>(g_bytes_processed)/1e9;
double seconds = static_cast<double>(g_benchmark_total_time_ns)/1e9;
- snprintf(throughput, sizeof(throughput), " %8.2f MiB/s", mib_processed/seconds);
+ snprintf(throughput, sizeof(throughput), " %8.3f GiB/s", gib_processed/seconds);
}
char full_name[100];
if (fn_range_ != NULL) {
- if (arg >= (1<<20)) {
- snprintf(full_name, sizeof(full_name), "%s/%dM", name_, arg/(1<<20));
- } else if (arg >= (1<<10)) {
- snprintf(full_name, sizeof(full_name), "%s/%dK", name_, arg/(1<<10));
- } else {
- snprintf(full_name, sizeof(full_name), "%s/%d", name_, arg);
- }
+ snprintf(full_name, sizeof(full_name), "%s/%s", name_, PrettyInt(arg, 2).c_str());
} else {
snprintf(full_name, sizeof(full_name), "%s", name_);
}
- printf("%-*s %10d %10" PRId64 "%s\n", g_name_column_width, full_name,
- iterations, g_benchmark_total_time_ns/iterations, throughput);
+ printf("%-*s %10s %10" PRId64 "%s\n",
+ g_name_column_width, full_name,
+ PrettyInt(iterations, 10).c_str(),
+ g_benchmark_total_time_ns/iterations,
+ throughput);
fflush(stdout);
}
@@ -191,19 +231,18 @@
}
int main(int argc, char* argv[]) {
- if (g_benchmarks.empty()) {
+ if (Benchmarks().empty()) {
fprintf(stderr, "No benchmarks registered!\n");
exit(EXIT_FAILURE);
}
- for (BenchmarkMapIt it = g_benchmarks.begin(); it != g_benchmarks.end(); ++it) {
- int name_width = static_cast<int>(strlen(it->second->Name()));
+ for (auto& b : Benchmarks()) {
+ int name_width = static_cast<int>(strlen(b->Name()));
g_name_column_width = std::max(g_name_column_width, name_width);
}
bool need_header = true;
- for (BenchmarkMapIt it = g_benchmarks.begin(); it != g_benchmarks.end(); ++it) {
- ::testing::Benchmark* b = it->second;
+ for (auto& b : Benchmarks()) {
if (b->ShouldRun(argc, argv)) {
if (need_header) {
printf("%-*s %10s %10s\n", g_name_column_width, "", "iterations", "ns/op");
@@ -217,8 +256,8 @@
if (need_header) {
fprintf(stderr, "No matching benchmarks!\n");
fprintf(stderr, "Available benchmarks:\n");
- for (BenchmarkMapIt it = g_benchmarks.begin(); it != g_benchmarks.end(); ++it) {
- fprintf(stderr, " %s\n", it->second->Name());
+ for (auto& b : Benchmarks()) {
+ fprintf(stderr, " %s\n", b->Name());
}
exit(EXIT_FAILURE);
}
diff --git a/benchmarks/benchmark.h b/benchmarks/include/benchmark.h
similarity index 95%
rename from benchmarks/benchmark.h
rename to benchmarks/include/benchmark.h
index d7af50f..7e134a0 100644
--- a/benchmarks/benchmark.h
+++ b/benchmarks/include/benchmark.h
@@ -14,8 +14,10 @@
* limitations under the License.
*/
-#include <stdint.h>
+#ifndef BENCHMARKS_BENCHMARK_H_
+#define BENCHMARKS_BENCHMARK_H_
+#include <stdint.h>
#include <vector>
namespace testing {
@@ -59,3 +61,5 @@
#define BENCHMARK(f) \
static ::testing::Benchmark* _benchmark_##f __attribute__((unused)) = \
(new ::testing::Benchmark(#f, f))
+
+#endif
diff --git a/benchmarks/stdio_benchmark.cpp b/benchmarks/stdio_benchmark.cpp
index 386ea04..fe25d76 100644
--- a/benchmarks/stdio_benchmark.cpp
+++ b/benchmarks/stdio_benchmark.cpp
@@ -65,3 +65,13 @@
ReadWriteTest(iters, chunk_size, fwrite, false);
}
BENCHMARK(BM_stdio_fwrite_unbuffered)->AT_COMMON_SIZES;
+
+static void BM_stdio_fopen_fgets_fclose(int iters) {
+ char buf[1024];
+ for (int i = 0; i < iters; ++i) {
+ FILE* fp = fopen("/proc/version", "re");
+ fgets(buf, sizeof(buf), fp);
+ fclose(fp);
+ }
+}
+BENCHMARK(BM_stdio_fopen_fgets_fclose);
diff --git a/libc/bionic/pthread_detach.cpp b/libc/bionic/pthread_detach.cpp
index 715acf1..c800660 100644
--- a/libc/bionic/pthread_detach.cpp
+++ b/libc/bionic/pthread_detach.cpp
@@ -27,29 +27,32 @@
*/
#include <errno.h>
+#include <pthread.h>
#include "pthread_accessor.h"
int pthread_detach(pthread_t t) {
- pthread_accessor thread(t);
- if (thread.get() == NULL) {
+ {
+ pthread_accessor thread(t);
+ if (thread.get() == NULL) {
return ESRCH;
+ }
+
+ if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
+ return EINVAL; // Already detached.
+ }
+
+ if (thread->attr.flags & PTHREAD_ATTR_FLAG_JOINED) {
+ return 0; // Already being joined; silently do nothing, like glibc.
+ }
+
+ // If the thread has not exited, we can detach it safely.
+ if ((thread->attr.flags & PTHREAD_ATTR_FLAG_ZOMBIE) == 0) {
+ thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
+ return 0;
+ }
}
- if (thread->attr.flags & PTHREAD_ATTR_FLAG_DETACHED) {
- return EINVAL; // Already detached.
- }
-
- if (thread->attr.flags & PTHREAD_ATTR_FLAG_JOINED) {
- return 0; // Already being joined; silently do nothing, like glibc.
- }
-
- if (thread->tid == 0) {
- // Already exited; clean up.
- _pthread_internal_remove_locked(thread.get(), true);
- return 0;
- }
-
- thread->attr.flags |= PTHREAD_ATTR_FLAG_DETACHED;
- return 0;
+ // The thread is in zombie state, use pthread_join to clean it up.
+ return pthread_join(t, NULL);
}
diff --git a/libc/bionic/pthread_exit.cpp b/libc/bionic/pthread_exit.cpp
index 9603a79..d0d64b0 100644
--- a/libc/bionic/pthread_exit.cpp
+++ b/libc/bionic/pthread_exit.cpp
@@ -99,6 +99,9 @@
// pthread_internal_t is freed below with stack, not here.
_pthread_internal_remove_locked(thread, false);
free_mapped_space = true;
+ } else {
+ // Mark the thread as exiting without freeing pthread_internal_t.
+ thread->attr.flags |= PTHREAD_ATTR_FLAG_ZOMBIE;
}
pthread_mutex_unlock(&g_thread_list_lock);
diff --git a/libc/bionic/pthread_internal.h b/libc/bionic/pthread_internal.h
index 80002e9..8fbaf22 100644
--- a/libc/bionic/pthread_internal.h
+++ b/libc/bionic/pthread_internal.h
@@ -38,6 +38,9 @@
/* Has the thread been joined by another thread? */
#define PTHREAD_ATTR_FLAG_JOINED 0x00000002
+/* Did the thread exit without freeing pthread_internal_t? */
+#define PTHREAD_ATTR_FLAG_ZOMBIE 0x00000004
+
/* Is this the main thread? */
#define PTHREAD_ATTR_FLAG_MAIN_THREAD 0x80000000
diff --git a/libc/include/sys/_system_properties.h b/libc/include/sys/_system_properties.h
index 0349e4c..44fe991 100644
--- a/libc/include/sys/_system_properties.h
+++ b/libc/include/sys/_system_properties.h
@@ -50,7 +50,7 @@
__BEGIN_DECLS
-struct prop_msg
+struct prop_msg
{
unsigned cmd;
char name[PROP_NAME_MAX];
@@ -58,7 +58,7 @@
};
#define PROP_MSG_SETPROP 1
-
+
/*
** Rules:
**
@@ -82,6 +82,7 @@
#define PROP_PATH_SYSTEM_BUILD "/system/build.prop"
#define PROP_PATH_SYSTEM_DEFAULT "/system/default.prop"
#define PROP_PATH_VENDOR_BUILD "/vendor/build.prop"
+#define PROP_PATH_BOOTIMAGE_BUILD "/build.prop"
#define PROP_PATH_LOCAL_OVERRIDE "/data/local.prop"
#define PROP_PATH_FACTORY "/factory/factory.prop"
diff --git a/libc/upstream-openbsd/lib/libc/stdio/fgetln.c b/libc/upstream-openbsd/lib/libc/stdio/fgetln.c
index d0c0809..1109cf2 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/fgetln.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/fgetln.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: fgetln.c,v 1.12 2013/11/12 07:04:06 deraadt Exp $ */
+/* $OpenBSD: fgetln.c,v 1.13 2015/01/05 21:58:52 millert Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
@@ -38,19 +38,12 @@
/*
* Expand the line buffer. Return -1 on error.
-#ifdef notdef
- * The `new size' does not account for a terminating '\0',
- * so we add 1 here.
-#endif
*/
static int
__slbexpand(FILE *fp, size_t newsize)
{
void *p;
-#ifdef notdef
- ++newsize;
-#endif
if (fp->_lb._size >= newsize)
return (0);
if ((p = realloc(fp->_lb._base, newsize)) == NULL)
@@ -141,14 +134,11 @@
}
*lenp = len;
ret = (char *)fp->_lb._base;
-#ifdef notdef
- ret[len] = '\0';
-#endif
FUNLOCKFILE(fp);
return (ret);
error:
- *lenp = 0; /* ??? */
FUNLOCKFILE(fp);
- return (NULL); /* ??? */
+ *lenp = 0;
+ return (NULL);
}
diff --git a/libc/upstream-openbsd/lib/libc/stdio/getdelim.c b/libc/upstream-openbsd/lib/libc/stdio/getdelim.c
index dcde0c3..5e583cb 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/getdelim.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/getdelim.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: getdelim.c,v 1.1 2012/03/21 23:44:35 fgsch Exp $ */
+/* $OpenBSD: getdelim.c,v 1.2 2014/10/16 17:31:51 millert Exp $ */
/* $NetBSD: getdelim.c,v 1.13 2011/07/22 23:12:30 joerg Exp $ */
/*
@@ -78,13 +78,12 @@
else
len = (p - fp->_p) + 1;
- newlen = off + len;
/* Ensure we can handle it */
- if (newlen < off || newlen > SSIZE_MAX) {
+ if (off > SSIZE_MAX || len + 1 > SSIZE_MAX - off) {
errno = EOVERFLOW;
goto error;
}
- newlen++; /* reserve space for the NULL terminator */
+ newlen = off + len + 1; /* reserve space for NUL terminator */
if (newlen > *buflen) {
if (newlen < MINBUF)
newlen = MINBUF;
diff --git a/libc/upstream-openbsd/lib/libc/stdio/makebuf.c b/libc/upstream-openbsd/lib/libc/stdio/makebuf.c
index d47e27c..56e5f21 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/makebuf.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/makebuf.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: makebuf.c,v 1.8 2005/12/28 18:50:22 millert Exp $ */
+/* $OpenBSD: makebuf.c,v 1.9 2015/01/13 07:18:21 guenther Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
@@ -65,7 +65,6 @@
fp->_bf._size = 1;
return;
}
- __atexit_register_cleanup(_cleanup);
flags |= __SMBF;
fp->_bf._base = fp->_p = p;
fp->_bf._size = size;
diff --git a/libc/upstream-openbsd/lib/libc/stdio/mktemp.c b/libc/upstream-openbsd/lib/libc/stdio/mktemp.c
index 2a17e52..956608c 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/mktemp.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/mktemp.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: mktemp.c,v 1.34 2014/08/31 02:21:18 guenther Exp $ */
+/* $OpenBSD: mktemp.c,v 1.35 2014/10/31 15:54:14 millert Exp $ */
/*
* Copyright (c) 1996-1998, 2008 Theo de Raadt
* Copyright (c) 1997, 2008-2009 Todd C. Miller
@@ -45,7 +45,7 @@
mktemp_internal(char *path, int slen, int mode, int flags)
{
char *start, *cp, *ep;
- const char *tempchars = TEMPCHARS;
+ const char tempchars[] = TEMPCHARS;
unsigned int tries;
struct stat sb;
size_t len;
diff --git a/libc/upstream-openbsd/lib/libc/stdio/open_wmemstream.c b/libc/upstream-openbsd/lib/libc/stdio/open_wmemstream.c
index 9414187..391a944 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/open_wmemstream.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/open_wmemstream.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: open_wmemstream.c,v 1.3 2014/03/06 07:28:21 gerhard Exp $ */
+/* $OpenBSD: open_wmemstream.c,v 1.4 2014/10/08 05:28:19 deraadt Exp $ */
/*
* Copyright (c) 2011 Martin Pieuchot <mpi@openbsd.org>
@@ -52,7 +52,7 @@
if (sz < end + 1)
sz = end + 1;
- p = realloc(st->string, sz * sizeof(wchar_t));
+ p = reallocarray(st->string, sz, sizeof(wchar_t));
if (!p)
return (-1);
bzero(p + st->size, (sz - st->size) * sizeof(wchar_t));
diff --git a/libc/upstream-openbsd/lib/libc/stdio/setvbuf.c b/libc/upstream-openbsd/lib/libc/stdio/setvbuf.c
index 6c49f7a..9b2ab57 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/setvbuf.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/setvbuf.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: setvbuf.c,v 1.11 2009/11/09 00:18:27 kurt Exp $ */
+/* $OpenBSD: setvbuf.c,v 1.12 2015/01/13 07:18:21 guenther Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
@@ -115,6 +115,13 @@
}
/*
+ * We're committed to buffering from here, so make sure we've
+ * registered to flush buffers on exit.
+ */
+ if (!__sdidinit)
+ __sinit();
+
+ /*
* Kill any seek optimization if the buffer is not the
* right size.
*
@@ -124,8 +131,7 @@
flags |= __SNPT;
/*
- * Fix up the FILE fields, and set __cleanup for output flush on
- * exit (since we are buffered in some way).
+ * Fix up the FILE fields.
*/
if (mode == _IOLBF)
flags |= __SLBF;
@@ -148,7 +154,6 @@
fp->_w = 0;
}
FUNLOCKFILE(fp);
- __atexit_register_cleanup(_cleanup);
return (ret);
}
diff --git a/libc/upstream-openbsd/lib/libc/stdio/ungetc.c b/libc/upstream-openbsd/lib/libc/stdio/ungetc.c
index 675733a..ec98f26 100644
--- a/libc/upstream-openbsd/lib/libc/stdio/ungetc.c
+++ b/libc/upstream-openbsd/lib/libc/stdio/ungetc.c
@@ -1,4 +1,4 @@
-/* $OpenBSD: ungetc.c,v 1.12 2009/11/09 00:18:27 kurt Exp $ */
+/* $OpenBSD: ungetc.c,v 1.13 2014/10/11 04:05:10 deraadt Exp $ */
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
@@ -64,14 +64,14 @@
return (0);
}
i = _UB(fp)._size;
- p = realloc(_UB(fp)._base, i << 1);
+ p = reallocarray(_UB(fp)._base, i, 2);
if (p == NULL)
return (EOF);
/* no overlap (hence can use memcpy) because we doubled the size */
(void)memcpy((void *)(p + i), (void *)p, (size_t)i);
fp->_p = p + i;
_UB(fp)._base = p;
- _UB(fp)._size = i << 1;
+ _UB(fp)._size = i * 2;
return (0);
}
diff --git a/linker/Android.mk b/linker/Android.mk
index d6e0095..720389f 100644
--- a/linker/Android.mk
+++ b/linker/Android.mk
@@ -16,8 +16,8 @@
LOCAL_SRC_FILES_arm64 := arch/arm64/begin.S
LOCAL_SRC_FILES_x86 := arch/x86/begin.c
LOCAL_SRC_FILES_x86_64 := arch/x86_64/begin.S
-LOCAL_SRC_FILES_mips := arch/mips/begin.S
-LOCAL_SRC_FILES_mips64 := arch/mips64/begin.S
+LOCAL_SRC_FILES_mips := arch/mips/begin.S linker_mips.cpp
+LOCAL_SRC_FILES_mips64 := arch/mips64/begin.S linker_mips.cpp
LOCAL_LDFLAGS := \
-shared \
diff --git a/linker/linker.cpp b/linker/linker.cpp
index e0fec0f..0b0afc3 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -122,14 +122,6 @@
__LIBC_HIDDEN__ abort_msg_t* g_abort_message = nullptr; // For debuggerd.
-enum RelocationKind {
- kRelocAbsolute = 0,
- kRelocRelative,
- kRelocCopy,
- kRelocSymbol,
- kRelocMax
-};
-
#if STATS
struct linker_stats_t {
int count[kRelocMax];
@@ -137,30 +129,16 @@
static linker_stats_t linker_stats;
-static void count_relocation(RelocationKind kind) {
+void count_relocation(RelocationKind kind) {
++linker_stats.count[kind];
}
#else
-static void count_relocation(RelocationKind) {
+void count_relocation(RelocationKind) {
}
#endif
#if COUNT_PAGES
-static unsigned bitmask[4096];
-#if defined(__LP64__)
-#define MARK(offset) \
- do { \
- if ((((offset) >> 12) >> 5) < 4096) \
- bitmask[((offset) >> 12) >> 5] |= (1 << (((offset) >> 12) & 31)); \
- } while (0)
-#else
-#define MARK(offset) \
- do { \
- bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \
- } while (0)
-#endif
-#else
-#define MARK(x) do {} while (0)
+uint32_t bitmask[4096];
#endif
// You shouldn't try to call memory-allocating functions in the dynamic linker.
@@ -539,7 +517,7 @@
return gnu_hash_;
}
-static ElfW(Sym)* soinfo_do_lookup(soinfo* si_from, const char* name, soinfo** si_found_in,
+ElfW(Sym)* soinfo_do_lookup(soinfo* si_from, const char* name, soinfo** si_found_in,
const soinfo::soinfo_list_t& global_group, const soinfo::soinfo_list_t& local_group) {
SymbolName symbol_name(name);
ElfW(Sym)* s = nullptr;
@@ -1279,16 +1257,32 @@
return ifunc_addr;
}
+#if !defined(__mips__)
#if defined(USE_RELA)
-int soinfo::relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
- for (size_t idx = 0; idx < count; ++idx, ++rela) {
- unsigned type = ELFW(R_TYPE)(rela->r_info);
- unsigned sym = ELFW(R_SYM)(rela->r_info);
- ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rela->r_offset + load_bias);
+static ElfW(Addr) get_addend(ElfW(Rela)* rela, ElfW(Addr) reloc_addr __unused) {
+ return rela->r_addend;
+}
+#else
+static ElfW(Addr) get_addend(ElfW(Rel)* rel, ElfW(Addr) reloc_addr) {
+ if (ELFW(R_TYPE)(rel->r_info) == R_GENERIC_RELATIVE || ELFW(R_TYPE)(rel->r_info) == R_GENERIC_IRELATIVE) {
+ return *reinterpret_cast<ElfW(Addr)*>(reloc_addr);
+ }
+ return 0;
+}
+#endif
+
+template<typename ElfRelT>
+bool soinfo::relocate(ElfRelT* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
+ for (size_t idx = 0; idx < count; ++idx, ++rel) {
+ ElfW(Word) type = ELFW(R_TYPE)(rel->r_info);
+ ElfW(Word) sym = ELFW(R_SYM)(rel->r_info);
+
+ ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
ElfW(Addr) sym_addr = 0;
const char* sym_name = nullptr;
+ ElfW(Addr) addend = get_addend(rel, reloc);
- DEBUG("Processing '%s' relocation at index %zd", name, idx);
+ DEBUG("Processing '%s' relocation at index %zd", this->name, idx);
if (type == R_GENERIC_NONE) {
continue;
}
@@ -1304,7 +1298,7 @@
s = &symtab_[sym];
if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
DL_ERR("cannot locate symbol \"%s\" referenced by \"%s\"...", sym_name, name);
- return -1;
+ return false;
}
/* IHI0044C AAELF 4.5.1.1:
@@ -1320,36 +1314,40 @@
*/
switch (type) {
+ case R_GENERIC_JUMP_SLOT:
+ case R_GENERIC_GLOB_DAT:
+ case R_GENERIC_RELATIVE:
+ case R_GENERIC_IRELATIVE:
#if defined(__aarch64__)
- case R_AARCH64_JUMP_SLOT:
- case R_AARCH64_GLOB_DAT:
case R_AARCH64_ABS64:
case R_AARCH64_ABS32:
case R_AARCH64_ABS16:
- case R_AARCH64_RELATIVE:
- case R_AARCH64_IRELATIVE:
+#elif defined(__x86_64__)
+ case R_X86_64_32:
+ case R_X86_64_64:
+#elif defined(__arm__)
+ case R_ARM_ABS32:
+#elif defined(__i386__)
+ case R_386_32:
+#endif
/*
* The sym_addr was initialized to be zero above, or the relocation
* code below does not care about value of sym_addr.
* No need to do anything.
*/
break;
-#elif defined(__x86_64__)
- case R_X86_64_JUMP_SLOT:
- case R_X86_64_GLOB_DAT:
- case R_X86_64_32:
- case R_X86_64_64:
- case R_X86_64_RELATIVE:
- case R_X86_64_IRELATIVE:
- // No need to do anything.
- break;
+#if defined(__x86_64__)
case R_X86_64_PC32:
sym_addr = reloc;
break;
+#elif defined(__i386__)
+ case R_386_PC32:
+ sym_addr = reloc;
+ break;
#endif
default:
- DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rela, idx);
- return -1;
+ DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
+ return false;
}
} else {
// We got a definition.
@@ -1361,114 +1359,115 @@
switch (type) {
case R_GENERIC_JUMP_SLOT:
count_relocation(kRelocAbsolute);
- MARK(rela->r_offset);
- TRACE_TYPE(RELO, "RELO JMP_SLOT %16llx <- %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + rela->r_addend);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "RELO JMP_SLOT %16p <- %16p %s\n",
+ reinterpret_cast<void*>(reloc),
+ reinterpret_cast<void*>(sym_addr + addend), sym_name);
+
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
break;
case R_GENERIC_GLOB_DAT:
count_relocation(kRelocAbsolute);
- MARK(rela->r_offset);
- TRACE_TYPE(RELO, "RELO GLOB_DAT %16llx <- %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + rela->r_addend);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "RELO GLOB_DAT %16p <- %16p %s\n",
+ reinterpret_cast<void*>(reloc),
+ reinterpret_cast<void*>(sym_addr + addend), sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = (sym_addr + addend);
break;
case R_GENERIC_RELATIVE:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
- if (sym) {
- DL_ERR("error: encountered _RELATIVE relocation with a symbol");
- return -1;
- }
- TRACE_TYPE(RELO, "RELO RELATIVE %16llx <- %16llx\n",
- reloc, (base + rela->r_addend));
- *reinterpret_cast<ElfW(Addr)*>(reloc) = (base + rela->r_addend);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "RELO RELATIVE %16p <- %16p\n",
+ reinterpret_cast<void*>(reloc),
+ reinterpret_cast<void*>(base + addend));
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = (base + addend);
break;
-
case R_GENERIC_IRELATIVE:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
- TRACE_TYPE(RELO, "RELO IRELATIVE %16llx <- %16llx\n", reloc, (base + rela->r_addend));
- *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + rela->r_addend);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "RELO IRELATIVE %16p <- %16p\n",
+ reinterpret_cast<void*>(reloc),
+ reinterpret_cast<void*>(base + addend));
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + addend);
break;
#if defined(__aarch64__)
case R_AARCH64_ABS64:
count_relocation(kRelocAbsolute);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO ABS64 %16llx <- %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
+ reloc, (sym_addr + addend), sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + addend);
break;
case R_AARCH64_ABS32:
count_relocation(kRelocAbsolute);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO ABS32 %16llx <- %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), sym_name);
- if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
- ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
+ reloc, (sym_addr + addend), sym_name);
+ if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + addend))) &&
+ ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + addend)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + addend);
} else {
DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + addend)),
static_cast<ElfW(Addr)>(INT32_MIN),
static_cast<ElfW(Addr)>(UINT32_MAX));
- return -1;
+ return false;
}
break;
case R_AARCH64_ABS16:
count_relocation(kRelocAbsolute);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO ABS16 %16llx <- %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), sym_name);
- if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend))) &&
- ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend);
+ reloc, (sym_addr + addend), sym_name);
+ if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + addend))) &&
+ ((*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + addend)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + addend);
} else {
DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + rela->r_addend)),
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + (sym_addr + addend)),
static_cast<ElfW(Addr)>(INT16_MIN),
static_cast<ElfW(Addr)>(UINT16_MAX));
- return -1;
+ return false;
}
break;
case R_AARCH64_PREL64:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO REL64 %16llx <- %16llx - %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + rela->r_addend) - rela->r_offset;
+ reloc, (sym_addr + addend), rel->r_offset, sym_name);
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr + addend) - rel->r_offset;
break;
case R_AARCH64_PREL32:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO REL32 %16llx <- %16llx - %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
- if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
- ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
+ reloc, (sym_addr + addend), rel->r_offset, sym_name);
+ if ((static_cast<ElfW(Addr)>(INT32_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + addend) - rel->r_offset))) &&
+ ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + addend) - rel->r_offset)) <= static_cast<ElfW(Addr)>(UINT32_MAX))) {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + addend) - rel->r_offset);
} else {
DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + addend) - rel->r_offset)),
static_cast<ElfW(Addr)>(INT32_MIN),
static_cast<ElfW(Addr)>(UINT32_MAX));
- return -1;
+ return false;
}
break;
case R_AARCH64_PREL16:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO REL16 %16llx <- %16llx - %16llx %s\n",
- reloc, (sym_addr + rela->r_addend), rela->r_offset, sym_name);
- if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset))) &&
- ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + rela->r_addend) - rela->r_offset);
+ reloc, (sym_addr + addend), rel->r_offset, sym_name);
+ if ((static_cast<ElfW(Addr)>(INT16_MIN) <= (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + addend) - rel->r_offset))) &&
+ ((*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + addend) - rel->r_offset)) <= static_cast<ElfW(Addr)>(UINT16_MAX))) {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += ((sym_addr + addend) - rel->r_offset);
} else {
DL_ERR("0x%016llx out of range 0x%016llx to 0x%016llx",
- (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + rela->r_addend) - rela->r_offset)),
+ (*reinterpret_cast<ElfW(Addr)*>(reloc) + ((sym_addr + addend) - rel->r_offset)),
static_cast<ElfW(Addr)>(INT16_MIN),
static_cast<ElfW(Addr)>(UINT16_MAX));
- return -1;
+ return false;
}
break;
@@ -1483,167 +1482,39 @@
* set to ET_EXEC.
*/
DL_ERR("%s R_AARCH64_COPY relocations are not supported", name);
- return -1;
+ return false;
case R_AARCH64_TLS_TPREL64:
TRACE_TYPE(RELO, "RELO TLS_TPREL64 *** %16llx <- %16llx - %16llx\n",
- reloc, (sym_addr + rela->r_addend), rela->r_offset);
+ reloc, (sym_addr + addend), rel->r_offset);
break;
case R_AARCH64_TLS_DTPREL32:
TRACE_TYPE(RELO, "RELO TLS_DTPREL32 *** %16llx <- %16llx - %16llx\n",
- reloc, (sym_addr + rela->r_addend), rela->r_offset);
+ reloc, (sym_addr + addend), rel->r_offset);
break;
#elif defined(__x86_64__)
case R_X86_64_32:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO R_X86_64_32 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
static_cast<size_t>(sym_addr), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
break;
case R_X86_64_64:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO R_X86_64_64 %08zx <- +%08zx %s", static_cast<size_t>(reloc),
static_cast<size_t>(sym_addr), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend;
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend;
break;
case R_X86_64_PC32:
count_relocation(kRelocRelative);
- MARK(rela->r_offset);
+ MARK(rel->r_offset);
TRACE_TYPE(RELO, "RELO R_X86_64_PC32 %08zx <- +%08zx (%08zx - %08zx) %s",
static_cast<size_t>(reloc), static_cast<size_t>(sym_addr - reloc),
static_cast<size_t>(sym_addr), static_cast<size_t>(reloc), sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + rela->r_addend - reloc;
+ *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr + addend - reloc;
break;
-#endif
-
- default:
- DL_ERR("unknown reloc type %d @ %p (%zu)", type, rela, idx);
- return -1;
- }
- }
- return 0;
-}
-
-#else // REL, not RELA.
-int soinfo::relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
- for (size_t idx = 0; idx < count; ++idx, ++rel) {
- unsigned type = ELFW(R_TYPE)(rel->r_info);
- // TODO: don't use unsigned for 'sym'. Use uint32_t or ElfW(Addr) instead.
- unsigned sym = ELFW(R_SYM)(rel->r_info);
- ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
- ElfW(Addr) sym_addr = 0;
- const char* sym_name = nullptr;
-
- DEBUG("Processing '%s' relocation at index %zd", name, idx);
- if (type == R_GENERIC_NONE) {
- continue;
- }
-
- ElfW(Sym)* s = nullptr;
- soinfo* lsi = nullptr;
-
- if (sym != 0) {
- sym_name = get_string(symtab_[sym].st_name);
- s = soinfo_do_lookup(this, sym_name, &lsi, global_group, local_group);
- if (s == nullptr) {
- // 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);
- return -1;
- }
-
- /* IHI0044C AAELF 4.5.1.1:
-
- Libraries are not searched to resolve weak references.
- It is not an error for a weak reference to remain
- unsatisfied.
-
- During linking, the value of an undefined weak reference is:
- - Zero if the relocation type is absolute
- - The address of the place if the relocation is pc-relative
- - The address of nominal base address if the relocation
- type is base-relative.
- */
-
- switch (type) {
-#if !defined(__mips__)
- case R_GENERIC_JUMP_SLOT:
- case R_GENERIC_GLOB_DAT:
- case R_GENERIC_RELATIVE:
- case R_GENERIC_IRELATIVE:
-#endif
-
-#if defined(__arm__)
- case R_ARM_ABS32: /* Don't care. */
- // sym_addr was initialized to be zero above or relocation
- // code below does not care about value of sym_addr.
- // No need to do anything.
- break;
-#elif defined(__i386__)
- case R_386_32:
- // sym_addr was initialized to be zero above or relocation
- // code below does not care about value of sym_addr.
- // No need to do anything.
- break;
- case R_386_PC32:
- sym_addr = reloc;
- break;
-#endif
-
-#if defined(__arm__)
- case R_ARM_COPY:
- // Fall through. Can't really copy if weak symbol is not found at run-time.
-#endif
- default:
- DL_ERR("unknown weak reloc type %d @ %p (%zu)", type, rel, idx);
- return -1;
- }
- } else {
- // We got a definition.
- sym_addr = lsi->resolve_symbol_address(s);
- }
- count_relocation(kRelocSymbol);
- }
-
- switch (type) {
-#if !defined(__mips__)
- case R_GENERIC_JUMP_SLOT:
- count_relocation(kRelocAbsolute);
- MARK(rel->r_offset);
- TRACE_TYPE(RELO, "RELO JMP_SLOT %08x <- %08x %s", reloc, sym_addr, sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
- break;
-
- case R_GENERIC_GLOB_DAT:
- count_relocation(kRelocAbsolute);
- MARK(rel->r_offset);
- TRACE_TYPE(RELO, "RELO GLOB_DAT %08x <- %08x %s", reloc, sym_addr, sym_name);
- *reinterpret_cast<ElfW(Addr)*>(reloc) = sym_addr;
- break;
-
- case R_GENERIC_RELATIVE:
- count_relocation(kRelocRelative);
- MARK(rel->r_offset);
- if (sym) {
- DL_ERR("odd RELATIVE form...");
- return -1;
- }
- TRACE_TYPE(RELO, "RELO RELATIVE %p <- +%p",
- reinterpret_cast<void*>(reloc), reinterpret_cast<void*>(base));
- *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
- break;
-
- case R_GENERIC_IRELATIVE:
- count_relocation(kRelocRelative);
- MARK(rel->r_offset);
- TRACE_TYPE(RELO, "RELO IRELATIVE %p <- %p", reinterpret_cast<void*>(reloc), reinterpret_cast<void*>(base));
- *reinterpret_cast<ElfW(Addr)*>(reloc) = call_ifunc_resolver(base + *reinterpret_cast<ElfW(Addr)*>(reloc));
- break;
-#endif
-
-#if defined(__arm__)
+#elif defined(__arm__)
case R_ARM_ABS32:
count_relocation(kRelocAbsolute);
MARK(rel->r_offset);
@@ -1668,7 +1539,7 @@
* set to ET_EXEC.
*/
DL_ERR("%s R_ARM_COPY relocations are not supported", name);
- return -1;
+ return false;
#elif defined(__i386__)
case R_386_32:
count_relocation(kRelocRelative);
@@ -1683,89 +1554,15 @@
reloc, (sym_addr - reloc), sym_addr, reloc, sym_name);
*reinterpret_cast<ElfW(Addr)*>(reloc) += (sym_addr - reloc);
break;
-#elif defined(__mips__)
- case R_MIPS_REL32:
-#if defined(__LP64__)
- // MIPS Elf64_Rel entries contain compound relocations
- // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case
- if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 ||
- ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) {
- DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)",
- type, (unsigned)ELF64_R_TYPE2(rel->r_info),
- (unsigned)ELF64_R_TYPE3(rel->r_info), rel, idx);
- return -1;
- }
#endif
- count_relocation(kRelocAbsolute);
- MARK(rel->r_offset);
- TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast<size_t>(reloc),
- static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
- if (s) {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
- } else {
- *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
- }
- break;
-#endif
-
default:
DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
- return -1;
- }
- }
- return 0;
-}
-#endif
-
-#if defined(__mips__)
-bool soinfo::mips_relocate_got(const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
- ElfW(Addr)** got = plt_got_;
- if (got == nullptr) {
- return true;
- }
-
- // got[0] is the address of the lazy resolver function.
- // got[1] may be used for a GNU extension.
- // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start).
- // FIXME: maybe this should be in a separate routine?
- if ((flags_ & FLAG_LINKER) == 0) {
- size_t g = 0;
- got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadbeef);
- if (reinterpret_cast<intptr_t>(got[g]) < 0) {
- got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
- }
- // Relocate the local GOT entries.
- for (; g < mips_local_gotno_; g++) {
- got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(got[g]) + load_bias);
- }
- }
-
- // Now for the global GOT entries...
- ElfW(Sym)* sym = symtab_ + mips_gotsym_;
- got = plt_got_ + mips_local_gotno_;
- for (size_t g = mips_gotsym_; g < mips_symtabno_; g++, sym++, got++) {
- // This is an undefined reference... try to locate it.
- const char* sym_name = get_string(sym->st_name);
- soinfo* lsi = nullptr;
- ElfW(Sym)* s = soinfo_do_lookup(this, sym_name, &lsi, global_group, local_group);
- if (s == nullptr) {
- // We only allow an undefined symbol if this is a weak reference.
- s = &symtab_[g];
- if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
- DL_ERR("cannot locate \"%s\"...", sym_name);
return false;
- }
- *got = 0;
- } else {
- // FIXME: is this sufficient?
- // For reference see NetBSD link loader
- // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup
- *got = reinterpret_cast<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
}
}
return true;
}
-#endif
+#endif // !defined(__mips__)
void soinfo::call_array(const char* array_name __unused, linker_function_t* functions, size_t count, bool reverse) {
if (functions == nullptr) {
@@ -2454,26 +2251,26 @@
#if defined(USE_RELA)
if (rela_ != nullptr) {
DEBUG("[ relocating %s ]", name);
- if (relocate(rela_, rela_count_, global_group, local_group)) {
+ if (!relocate(rela_, rela_count_, global_group, local_group)) {
return false;
}
}
if (plt_rela_ != nullptr) {
DEBUG("[ relocating %s plt ]", name);
- if (relocate(plt_rela_, plt_rela_count_, global_group, local_group)) {
+ if (!relocate(plt_rela_, plt_rela_count_, global_group, local_group)) {
return false;
}
}
#else
if (rel_ != nullptr) {
DEBUG("[ relocating %s ]", name);
- if (relocate(rel_, rel_count_, global_group, local_group)) {
+ if (!relocate(rel_, rel_count_, global_group, local_group)) {
return false;
}
}
if (plt_rel_ != nullptr) {
DEBUG("[ relocating %s plt ]", name);
- if (relocate(plt_rel_, plt_rel_count_, global_group, local_group)) {
+ if (!relocate(plt_rel_, plt_rel_count_, global_group, local_group)) {
return false;
}
}
diff --git a/linker/linker.h b/linker/linker.h
index f7aa11c..2afbaf6 100644
--- a/linker/linker.h
+++ b/linker/linker.h
@@ -286,11 +286,8 @@
void call_array(const char* array_name, linker_function_t* functions, size_t count, bool reverse);
void call_function(const char* function_name, linker_function_t function);
-#if defined(USE_RELA)
- int relocate(ElfW(Rela)* rela, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group);
-#else
- int relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group);
-#endif
+ template<typename ElfRelT>
+ bool relocate(ElfRelT* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group);
private:
// This part of the structure is only available
@@ -321,6 +318,19 @@
friend soinfo* get_libdl_info();
};
+ElfW(Sym)* soinfo_do_lookup(soinfo* si_from, const char* name, soinfo** si_found_in,
+ const soinfo::soinfo_list_t& global_group, const soinfo::soinfo_list_t& local_group);
+
+enum RelocationKind {
+ kRelocAbsolute = 0,
+ kRelocRelative,
+ kRelocCopy,
+ kRelocSymbol,
+ kRelocMax
+};
+
+void count_relocation(RelocationKind kind);
+
soinfo* get_libdl_info();
void do_android_get_LD_LIBRARY_PATH(char*, size_t);
diff --git a/linker/linker_debug.h b/linker/linker_debug.h
index 0c7a784..5ded5ab 100644
--- a/linker/linker_debug.h
+++ b/linker/linker_debug.h
@@ -82,4 +82,23 @@
#define TRACE_TYPE(t, x...) do { if (DO_TRACE_##t) { TRACE(x); } } while (0)
+#if COUNT_PAGES
+extern uint32_t bitmask[];
+#if defined(__LP64__)
+#define MARK(offset) \
+ do { \
+ if ((((offset) >> 12) >> 5) < 4096) \
+ bitmask[((offset) >> 12) >> 5] |= (1 << (((offset) >> 12) & 31)); \
+ } while (0)
+#else
+#define MARK(offset) \
+ do { \
+ bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \
+ } while (0)
+#endif
+#else
+#define MARK(x) do {} while (0)
+
+#endif
+
#endif /* _LINKER_DEBUG_H_ */
diff --git a/linker/linker_mips.cpp b/linker/linker_mips.cpp
new file mode 100644
index 0000000..eb2ae84
--- /dev/null
+++ b/linker/linker_mips.cpp
@@ -0,0 +1,143 @@
+/*
+ * 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.
+ */
+
+#include "linker.h"
+#include "linker_debug.h"
+#include "linker_relocs.h"
+
+template<>
+bool soinfo::relocate(ElfW(Rel)* rel, unsigned count, const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
+ for (size_t idx = 0; idx < count; ++idx, ++rel) {
+ ElfW(Word) type = ELFW(R_TYPE)(rel->r_info);
+ ElfW(Word) sym = ELFW(R_SYM)(rel->r_info);
+
+ ElfW(Addr) reloc = static_cast<ElfW(Addr)>(rel->r_offset + load_bias);
+ ElfW(Addr) sym_addr = 0;
+ const char* sym_name = nullptr;
+
+ DEBUG("Processing '%s' relocation at index %zd", this->name, idx);
+ if (type == R_GENERIC_NONE) {
+ continue;
+ }
+
+ ElfW(Sym)* s = nullptr;
+ soinfo* lsi = nullptr;
+
+ if (sym != 0) {
+ sym_name = get_string(symtab_[sym].st_name);
+ 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);
+ return false;
+ } else {
+ // We got a definition.
+ sym_addr = lsi->resolve_symbol_address(s);
+ }
+ count_relocation(kRelocSymbol);
+ }
+
+ switch (type) {
+ case R_MIPS_REL32:
+#if defined(__LP64__)
+ // MIPS Elf64_Rel entries contain compound relocations
+ // We only handle the R_MIPS_NONE|R_MIPS_64|R_MIPS_REL32 case
+ if (ELF64_R_TYPE2(rel->r_info) != R_MIPS_64 ||
+ ELF64_R_TYPE3(rel->r_info) != R_MIPS_NONE) {
+ DL_ERR("Unexpected compound relocation type:%d type2:%d type3:%d @ %p (%zu)",
+ type, (unsigned)ELF64_R_TYPE2(rel->r_info),
+ (unsigned)ELF64_R_TYPE3(rel->r_info), rel, idx);
+ return false;
+ }
+#endif
+ count_relocation(s == nullptr ? kRelocAbsolute : kRelocRelative);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "RELO REL32 %08zx <- %08zx %s", static_cast<size_t>(reloc),
+ static_cast<size_t>(sym_addr), sym_name ? sym_name : "*SECTIONHDR*");
+ if (s != nullptr) {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += sym_addr;
+ } else {
+ *reinterpret_cast<ElfW(Addr)*>(reloc) += base;
+ }
+ break;
+ default:
+ DL_ERR("unknown reloc type %d @ %p (%zu)", type, rel, idx);
+ return false;
+ }
+ }
+ return true;
+}
+
+bool soinfo::mips_relocate_got(const soinfo_list_t& global_group, const soinfo_list_t& local_group) {
+ ElfW(Addr)** got = plt_got_;
+ if (got == nullptr) {
+ return true;
+ }
+
+ // got[0] is the address of the lazy resolver function.
+ // got[1] may be used for a GNU extension.
+ // Set it to a recognizable address in case someone calls it (should be _rtld_bind_start).
+ // FIXME: maybe this should be in a separate routine?
+ if ((flags_ & FLAG_LINKER) == 0) {
+ size_t g = 0;
+ got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadbeef);
+ if (reinterpret_cast<intptr_t>(got[g]) < 0) {
+ got[g++] = reinterpret_cast<ElfW(Addr)*>(0xdeadfeed);
+ }
+ // Relocate the local GOT entries.
+ for (; g < mips_local_gotno_; g++) {
+ got[g] = reinterpret_cast<ElfW(Addr)*>(reinterpret_cast<uintptr_t>(got[g]) + load_bias);
+ }
+ }
+
+ // Now for the global GOT entries...
+ ElfW(Sym)* sym = symtab_ + mips_gotsym_;
+ got = plt_got_ + mips_local_gotno_;
+ for (size_t g = mips_gotsym_; g < mips_symtabno_; g++, sym++, got++) {
+ // This is an undefined reference... try to locate it.
+ const char* sym_name = get_string(sym->st_name);
+ soinfo* lsi = nullptr;
+ ElfW(Sym)* s = soinfo_do_lookup(this, sym_name, &lsi, global_group, local_group);
+ if (s == nullptr) {
+ // We only allow an undefined symbol if this is a weak reference.
+ s = &symtab_[g];
+ if (ELF_ST_BIND(s->st_info) != STB_WEAK) {
+ DL_ERR("cannot locate \"%s\"...", sym_name);
+ return false;
+ }
+ *got = 0;
+ } else {
+ // FIXME: is this sufficient?
+ // For reference see NetBSD link loader
+ // http://cvsweb.netbsd.org/bsdweb.cgi/src/libexec/ld.elf_so/arch/mips/mips_reloc.c?rev=1.53&content-type=text/x-cvsweb-markup
+ *got = reinterpret_cast<ElfW(Addr)*>(lsi->resolve_symbol_address(s));
+ }
+ }
+ return true;
+}
+
diff --git a/tests/gtest_main.cpp b/tests/gtest_main.cpp
index 4304d8c..6c5023b 100644
--- a/tests/gtest_main.cpp
+++ b/tests/gtest_main.cpp
@@ -42,8 +42,8 @@
void ColoredPrintf(GTestColor color, const char* fmt, ...);
-} // namespace internal
-} // namespace testing
+} // namespace internal
+} // namespace testing
using testing::internal::GTestColor;
using testing::internal::COLOR_DEFAULT;
@@ -73,6 +73,24 @@
return global_test_run_warnline_in_ms;
}
+static void PrintHelpInfo() {
+ printf("Bionic Unit Test Options:\n"
+ " -j [JOB_COUNT]\n"
+ " Run up to JOB_COUNT tests in parallel.\n"
+ " Use isolation mode, Run each test in a separate process.\n"
+ " If JOB_COUNT is not given, it is set to the count of available processors.\n"
+ " --no-isolate\n"
+ " Don't use isolation mode, run all tests in a single process.\n"
+ " --deadline=[TIME_IN_MS]\n"
+ " Run each test in no longer than [TIME_IN_MS] time.\n"
+ " It takes effect only in isolation mode. Deafult deadline is 60000 ms.\n"
+ " --warnline=[TIME_IN_MS]\n"
+ " Test running longer than [TIME_IN_MS] will be warned.\n"
+ " It takes effect only in isolation mode. Default warnline is 2000 ms.\n"
+ "\nDefault bionic unit test option is -j.\n"
+ "\n");
+}
+
enum TestResult {
TEST_SUCCESS = 0,
TEST_FAILED,
@@ -90,37 +108,37 @@
test_list_.push_back(std::make_tuple(test_name, TEST_FAILED, 0LL));
}
- int NumTests() const { return test_list_.size(); }
+ size_t TestCount() const { return test_list_.size(); }
- std::string GetTestName(int test_id) const {
+ std::string GetTestName(size_t test_id) const {
VerifyTestId(test_id);
return name_ + "." + std::get<0>(test_list_[test_id]);
}
- void SetTestResult(int test_id, TestResult result) {
+ void SetTestResult(size_t test_id, TestResult result) {
VerifyTestId(test_id);
std::get<1>(test_list_[test_id]) = result;
}
- TestResult GetTestResult(int test_id) const {
+ TestResult GetTestResult(size_t test_id) const {
VerifyTestId(test_id);
return std::get<1>(test_list_[test_id]);
}
- void SetTestTime(int test_id, int64_t elapsed_time) {
+ void SetTestTime(size_t test_id, int64_t elapsed_time) {
VerifyTestId(test_id);
std::get<2>(test_list_[test_id]) = elapsed_time;
}
- int64_t GetTestTime(int test_id) const {
+ int64_t GetTestTime(size_t test_id) const {
VerifyTestId(test_id);
return std::get<2>(test_list_[test_id]);
}
private:
- void VerifyTestId(int test_id) const {
- if(test_id < 0 || test_id >= static_cast<int>(test_list_.size())) {
- fprintf(stderr, "test_id %d out of range [0, %zu)\n", test_id, test_list_.size());
+ void VerifyTestId(size_t test_id) const {
+ if(test_id >= test_list_.size()) {
+ fprintf(stderr, "test_id %zu out of range [0, %zu)\n", test_id, test_list_.size());
exit(1);
}
}
@@ -167,15 +185,15 @@
int towrite = strlen(buf);
char* p = buf;
while (towrite > 0) {
- ssize_t num_write = write(fileno(stdout), p, towrite);
- if (num_write == -1) {
+ ssize_t write_count = write(fileno(stdout), p, towrite);
+ if (write_count == -1) {
if (errno != EINTR) {
fprintf(stderr, "write, errno = %d\n", errno);
break;
}
} else {
- towrite -= num_write;
- p += num_write;
+ towrite -= write_count;
+ p += write_count;
}
}
}
@@ -265,46 +283,36 @@
return (result != -1 && WEXITSTATUS(result) == 0);
}
-static void PrintHelpInfo() {
- printf("Bionic Unit Test Options:\n"
- " --isolate\n"
- " Use isolation mode, Run each test in a separate process.\n"
- " --deadline=[TIME_IN_MS]\n"
- " Run each test in no longer than [TIME_IN_MS] time.\n"
- " It takes effect only in isolation mode. Deafult deadline is 60000 ms.\n"
- " --warnline=[TIME_IN_MS]\n"
- " Test running longer than [TIME_IN_MS] will be warned.\n"
- " It takes effect only in isolation mode. Default warnline is 2000 ms.\n"
- " -j [JOB_NUM]\n"
- " Run up to JOB_NUM tests in parallel.\n"
- " Use isolation mode, Run each test in a separate process.\n"
- " If JOB_NUM is not given, it is set to the number of cpus available.\n"
- "\n");
-}
-
// Part of the following *Print functions are copied from external/gtest/src/gtest.cc:
// PrettyUnitTestResultPrinter. The reason for copy is that PrettyUnitTestResultPrinter
// is defined and used in gtest.cc, which is hard to reuse.
-static void OnTestIterationStartPrint(const std::vector<TestCase>& testcase_list, int iteration,
- int num_iterations) {
- if (num_iterations > 1) {
- printf("\nRepeating all tests (iteration %d) . . .\n\n", iteration);
+static void OnTestIterationStartPrint(const std::vector<TestCase>& testcase_list, size_t iteration,
+ size_t iteration_count) {
+ if (iteration_count > 1) {
+ printf("\nRepeating all tests (iteration %zu) . . .\n\n", iteration);
}
ColoredPrintf(COLOR_GREEN, "[==========] ");
- int num_testcases = testcase_list.size();
- int num_tests = 0;
+ size_t testcase_count = testcase_list.size();
+ size_t test_count = 0;
for (const auto& testcase : testcase_list) {
- num_tests += testcase.NumTests();
+ test_count += testcase.TestCount();
}
- printf("Running %d %s from %d %s.\n",
- num_tests, (num_tests == 1) ? "test" : "tests",
- num_testcases, (num_testcases == 1) ? "test case" : "test cases");
+ printf("Running %zu %s from %zu %s.\n",
+ test_count, (test_count == 1) ? "test" : "tests",
+ testcase_count, (testcase_count == 1) ? "test case" : "test cases");
fflush(stdout);
}
-static void OnTestTimeoutPrint(const TestCase& testcase, int test_id) {
+static void OnTestTerminatedPrint(const TestCase& testcase, size_t test_id, int sig) {
+ ColoredPrintf(COLOR_RED, "[ FAILED ] ");
+ printf("%s terminated by signal: %s\n", testcase.GetTestName(test_id).c_str(),
+ strsignal(sig));
+ fflush(stdout);
+}
+
+static void OnTestTimeoutPrint(const TestCase& testcase, size_t test_id) {
ColoredPrintf(COLOR_RED, "[ TIMEOUT ] ");
printf("%s (killed by timeout at %lld ms)\n", testcase.GetTestName(test_id).c_str(),
testcase.GetTestTime(test_id) / 1000000LL);
@@ -313,17 +321,17 @@
static void TestcaseTimePrint(const TestCase& testcase) {
int64_t testcase_time = 0;
- for (int i = 0; i < testcase.NumTests(); ++i) {
+ for (size_t i = 0; i < testcase.TestCount(); ++i) {
testcase_time += testcase.GetTestTime(i);
}
- printf("%d %s from %s (%lld ms total)\n", testcase.NumTests(),
- (testcase.NumTests() == 1) ? "test" : "tests",
- testcase.GetName().c_str(),
- testcase_time / 1000000LL);
+ printf("%zu %s from %s (%lld ms total)\n", testcase.TestCount(),
+ (testcase.TestCount() == 1) ? "test" : "tests",
+ testcase.GetName().c_str(),
+ testcase_time / 1000000LL);
fflush(stdout);
}
-static void OnTestIterationEndPrint(const std::vector<TestCase>& testcase_list, int /*iteration*/,
+static void OnTestIterationEndPrint(const std::vector<TestCase>& testcase_list, size_t /*iteration*/,
int64_t elapsed_time) {
std::vector<std::string> fail_test_name_list;
@@ -331,16 +339,16 @@
// For tests run exceed warnline but not timeout.
std::vector<std::tuple<std::string, int64_t, int>> timewarn_test_list;
- int num_testcases = testcase_list.size();
- int num_tests = 0;
- int num_success_tests = 0;
+ size_t testcase_count = testcase_list.size();
+ size_t test_count = 0;
+ size_t success_test_count = 0;
for (const auto& testcase : testcase_list) {
- num_tests += testcase.NumTests();
- for (int i = 0; i < testcase.NumTests(); ++i) {
+ test_count += testcase.TestCount();
+ for (size_t i = 0; i < testcase.TestCount(); ++i) {
TestResult result = testcase.GetTestResult(i);
if (result == TEST_SUCCESS) {
- ++num_success_tests;
+ ++success_test_count;
} else if (result == TEST_FAILED) {
fail_test_name_list.push_back(testcase.GetTestName(i));
} else if (result == TEST_TIMEOUT) {
@@ -361,20 +369,20 @@
}
ColoredPrintf(COLOR_GREEN, "[==========] ");
- printf("%d %s from %d %s ran.", num_tests, (num_tests == 1) ? "test" : "tests",
- num_testcases, (num_testcases == 1) ? "test case" : "test cases");
+ printf("%zu %s from %zu %s ran.", test_count, (test_count == 1) ? "test" : "tests",
+ testcase_count, (testcase_count == 1) ? "test case" : "test cases");
if (testing::GTEST_FLAG(print_time)) {
printf(" (%lld ms total)", elapsed_time / 1000000LL);
}
printf("\n");
ColoredPrintf(COLOR_GREEN, "[ PASSED ] ");
- printf("%d %s.\n", num_success_tests, (num_success_tests == 1) ? "test" : "tests");
+ printf("%zu %s.\n", success_test_count, (success_test_count == 1) ? "test" : "tests");
// Print tests failed.
- int num_fail_tests = fail_test_name_list.size();
- if (num_fail_tests > 0) {
+ size_t fail_test_count = fail_test_name_list.size();
+ if (fail_test_count > 0) {
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
- printf("%d %s, listed below:\n", num_fail_tests, (num_fail_tests == 1) ? "test" : "tests");
+ printf("%zu %s, listed below:\n", fail_test_count, (fail_test_count == 1) ? "test" : "tests");
for (const auto& name : fail_test_name_list) {
ColoredPrintf(COLOR_RED, "[ FAILED ] ");
printf("%s\n", name.c_str());
@@ -382,10 +390,10 @@
}
// Print tests run timeout.
- int num_timeout_tests = timeout_test_list.size();
- if (num_timeout_tests > 0) {
+ size_t timeout_test_count = timeout_test_list.size();
+ if (timeout_test_count > 0) {
ColoredPrintf(COLOR_RED, "[ TIMEOUT ] ");
- printf("%d %s, listed below:\n", num_timeout_tests, (num_timeout_tests == 1) ? "test" : "tests");
+ printf("%zu %s, listed below:\n", timeout_test_count, (timeout_test_count == 1) ? "test" : "tests");
for (const auto& timeout_pair : timeout_test_list) {
ColoredPrintf(COLOR_RED, "[ TIMEOUT ] ");
printf("%s (stopped at %lld ms)\n", timeout_pair.first.c_str(),
@@ -394,10 +402,10 @@
}
// Print tests run exceed warnline.
- int num_timewarn_tests = timewarn_test_list.size();
- if (num_timewarn_tests > 0) {
+ size_t timewarn_test_count = timewarn_test_list.size();
+ if (timewarn_test_count > 0) {
ColoredPrintf(COLOR_YELLOW, "[ TIMEWARN ] ");
- printf("%d %s, listed below:\n", num_timewarn_tests, (num_timewarn_tests == 1) ? "test" : "tests");
+ printf("%zu %s, listed below:\n", timewarn_test_count, (timewarn_test_count == 1) ? "test" : "tests");
for (const auto& timewarn_tuple : timewarn_test_list) {
ColoredPrintf(COLOR_YELLOW, "[ TIMEWARN ] ");
printf("%s (%lld ms, exceed warnline %d ms)\n", std::get<0>(timewarn_tuple).c_str(),
@@ -406,14 +414,14 @@
}
}
- if (num_fail_tests > 0) {
- printf("\n%2d FAILED %s\n", num_fail_tests, (num_fail_tests == 1) ? "TEST" : "TESTS");
+ if (fail_test_count > 0) {
+ printf("\n%2zu FAILED %s\n", fail_test_count, (fail_test_count == 1) ? "TEST" : "TESTS");
}
- if (num_timeout_tests > 0) {
- printf("%2d TIMEOUT %s\n", num_timeout_tests, (num_timeout_tests == 1) ? "TEST" : "TESTS");
+ if (timeout_test_count > 0) {
+ printf("%2zu TIMEOUT %s\n", timeout_test_count, (timeout_test_count == 1) ? "TEST" : "TESTS");
}
- if (num_timewarn_tests > 0) {
- printf("%2d TIMEWARN %s\n", num_timewarn_tests, (num_timewarn_tests == 1) ? "TEST" : "TESTS");
+ if (timewarn_test_count > 0) {
+ printf("%2zu TIMEWARN %s\n", timewarn_test_count, (timewarn_test_count == 1) ? "TEST" : "TESTS");
}
fflush(stdout);
}
@@ -438,19 +446,20 @@
pid_t pid;
int64_t start_time;
int64_t deadline_time;
- int testcase_id, test_id;
+ size_t testcase_id, test_id;
bool done_flag;
- TestResult test_result;
+ bool timeout_flag;
+ int exit_status;
ChildProcInfo() : pid(0) {}
};
static void WaitChildProcs(std::vector<ChildProcInfo>& child_proc_list) {
pid_t result;
- int exit_status;
+ int status;
bool loop_flag = true;
while (true) {
- while ((result = waitpid(-1, &exit_status, WNOHANG)) == -1) {
+ while ((result = waitpid(-1, &status, WNOHANG)) == -1) {
if (errno != EINTR) {
break;
}
@@ -465,7 +474,7 @@
for (size_t i = 0; i < child_proc_list.size(); ++i) {
if (child_proc_list[i].deadline_time <= current_time) {
child_proc_list[i].done_flag = true;
- child_proc_list[i].test_result = TEST_TIMEOUT;
+ child_proc_list[i].timeout_flag = true;
loop_flag = false;
}
}
@@ -474,8 +483,8 @@
for (size_t i = 0; i < child_proc_list.size(); ++i) {
if (child_proc_list[i].pid == result) {
child_proc_list[i].done_flag = true;
- child_proc_list[i].test_result = (WEXITSTATUS(exit_status) == 0) ? TEST_SUCCESS :
- TEST_FAILED;
+ child_proc_list[i].timeout_flag = false;
+ child_proc_list[i].exit_status = status;
loop_flag = false;
break;
}
@@ -511,26 +520,32 @@
// We choose to use multi-fork and multi-wait here instead of multi-thread, because it always
// makes deadlock to use fork in multi-thread.
static void RunTestInSeparateProc(int argc, char** argv, std::vector<TestCase>& testcase_list,
- int num_iterations, int num_jobs) {
+ size_t iteration_count, size_t job_count) {
// Stop default result printer to avoid environment setup/teardown information for each test.
testing::UnitTest::GetInstance()->listeners().Release(
testing::UnitTest::GetInstance()->listeners().default_result_printer());
testing::UnitTest::GetInstance()->listeners().Append(new TestResultPrinter);
- for (int iteration = 1; iteration <= num_iterations; ++iteration) {
- OnTestIterationStartPrint(testcase_list, iteration, num_iterations);
+ for (size_t iteration = 1; iteration <= iteration_count; ++iteration) {
+ OnTestIterationStartPrint(testcase_list, iteration, iteration_count);
int64_t iteration_start_time = NanoTime();
- std::vector<ChildProcInfo> child_proc_list(num_jobs);
- int assign_testcase = 0, assign_test = 0;
- std::vector<int> finish_test_num_list(testcase_list.size(), 0);
- int num_finish_testcases = 0;
+ // Run up to job_count tests in parallel, each test in a child process.
+ std::vector<ChildProcInfo> child_proc_list(job_count);
- while (num_finish_testcases < static_cast<int>(testcase_list.size())) {
- // Fork child process up to num_jobs.
+ // Next test to run is [next_testcase_id:next_test_id].
+ size_t next_testcase_id = 0;
+ size_t next_test_id = 0;
+
+ // Record how many tests are finished.
+ std::vector<size_t> finished_test_count_list(testcase_list.size(), 0);
+ size_t finished_testcase_count = 0;
+
+ while (finished_testcase_count < testcase_list.size()) {
+ // Fork up to job_count child processes.
for (auto& child_proc : child_proc_list) {
- if (child_proc.pid == 0 && assign_testcase < static_cast<int>(testcase_list.size())) {
- std::string test_name = testcase_list[assign_testcase].GetTestName(assign_test);
+ if (child_proc.pid == 0 && next_testcase_id < testcase_list.size()) {
+ std::string test_name = testcase_list[next_testcase_id].GetTestName(next_test_id);
pid_t pid = fork();
if (pid == -1) {
perror("fork in RunTestInSeparateProc");
@@ -543,12 +558,12 @@
child_proc.pid = pid;
child_proc.start_time = NanoTime();
child_proc.deadline_time = child_proc.start_time + GetDeadlineInfo(test_name) * 1000000LL;
- child_proc.testcase_id = assign_testcase;
- child_proc.test_id = assign_test;
+ child_proc.testcase_id = next_testcase_id;
+ child_proc.test_id = next_test_id;
child_proc.done_flag = false;
- if (++assign_test == testcase_list[assign_testcase].NumTests()) {
- assign_test = 0;
- ++assign_testcase;
+ if (++next_test_id == testcase_list[next_testcase_id].TestCount()) {
+ next_test_id = 0;
+ ++next_testcase_id;
}
}
}
@@ -559,22 +574,31 @@
// Collect result.
for (auto& child_proc : child_proc_list) {
if (child_proc.pid != 0 && child_proc.done_flag == true) {
- int testcase_id = child_proc.testcase_id;
- int test_id = child_proc.test_id;
- TestResult test_result = child_proc.test_result;
- if (test_result == TEST_TIMEOUT) {
- // Kill and wait the child process.
+ size_t testcase_id = child_proc.testcase_id;
+ size_t test_id = child_proc.test_id;
+ TestCase& testcase = testcase_list[testcase_id];
+ testcase.SetTestTime(test_id, NanoTime() - child_proc.start_time);
+
+ if (child_proc.timeout_flag) {
+ // Kill and wait the timeout child process.
kill(child_proc.pid, SIGKILL);
WaitChildProc(child_proc.pid);
- }
- TestCase& testcase = testcase_list[testcase_id];
- testcase.SetTestResult(test_id, test_result);
- testcase.SetTestTime(test_id, NanoTime() - child_proc.start_time);
- if (test_result == TEST_TIMEOUT) {
+ testcase.SetTestResult(test_id, TEST_TIMEOUT);
OnTestTimeoutPrint(testcase, test_id);
+
+ } else if (WIFSIGNALED(child_proc.exit_status)) {
+ // Record signal terminated test as failed.
+ testcase.SetTestResult(test_id, TEST_FAILED);
+ OnTestTerminatedPrint(testcase, test_id, WTERMSIG(child_proc.exit_status));
+
+ } else {
+ testcase.SetTestResult(test_id, WEXITSTATUS(child_proc.exit_status) == 0 ?
+ TEST_SUCCESS : TEST_FAILED);
+ // TestResultPrinter::OnTestEnd has already printed result for normal exit.
}
- if (++finish_test_num_list[testcase_id] == testcase.NumTests()) {
- ++num_finish_testcases;
+
+ if (++finished_test_count_list[testcase_id] == testcase.TestCount()) {
+ ++finished_testcase_count;
}
child_proc.pid = 0;
child_proc.done_flag = false;
@@ -586,80 +610,64 @@
}
}
-static int GetCpuNumber() {
- FILE* fp = popen("cat /proc/cpuinfo | grep processor | wc -l", "r");
- int result = 1; // Return 1 if we can't get the exact cpu number.
- if (fp != NULL) {
- fscanf(fp, "%d", &result);
- if (result < 1) {
- result = 1;
- }
- pclose(fp);
- }
- return result;
+static size_t GetProcessorCount() {
+ return static_cast<size_t>(sysconf(_SC_NPROCESSORS_ONLN));
}
-// Pick options not for gtest; Return false if run error.
-// Use exit_flag to indicate whether we need to run gtest flow after PickOptions.
-static bool PickOptions(int* pargc, char*** pargv, bool* exit_flag) {
- int argc = *pargc;
- char** argv = *pargv;
+// Pick options not for gtest: There are two parts in argv, one part is handled by PickOptions()
+// as described in PrintHelpInfo(), the other part is handled by testing::InitGoogleTest() in
+// gtest. PickOptions() picks the first part of options and change them into flags and operations,
+// lefting the second part in argv.
+// Arguments:
+// argv is used to pass in all command arguments, and pass out only the part of options for gtest.
+// exit_flag is to indicate whether we need to run gtest workflow after PickOptions.
+// Return false if run error.
+static bool PickOptions(std::vector<char*>& argv, bool* exit_flag) {
*exit_flag = false;
- for (int i = 0; i < argc; ++i) {
+ for (size_t i = 1; i < argv.size() - 1; ++i) {
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0) {
PrintHelpInfo();
return true;
}
}
- // Move --gtest_filter option to last, and add "-bionic_gtest*" to disable self test.
- int gtest_filter_option_pos = 0;
- for (int i = argc - 1; i >= 1; --i) {
+ // Move --gtest_filter option to last, and add "-bionic_selftest*" to disable self test.
+ std::string gtest_filter_str = "--gtest_filter=-bionic_selftest*";
+ for (size_t i = argv.size() - 2; i >= 1; --i) {
if (strncmp(argv[i], "--gtest_filter=", sizeof("--gtest_filter=") - 1) == 0) {
- gtest_filter_option_pos = i;
+ gtest_filter_str = std::string(argv[i]) + ":-bionic_selftest*";
+ argv.erase(argv.begin() + i);
break;
}
}
- if (gtest_filter_option_pos != 0) {
- char* gtest_filter_arg = argv[gtest_filter_option_pos];
- for (int i = gtest_filter_option_pos; i < argc - 1; ++i) {
- argv[i] = argv[i + 1];
- }
- char* new_arg = new char[strlen(gtest_filter_arg) + sizeof(":-bionic_gtest*")];
- strcpy(new_arg, gtest_filter_arg);
- strcat(new_arg, ":-bionic_gtest*");
- argv[argc - 1] = new_arg;
- } else {
- char** new_argv = new char* [argc + 1];
- for (int i = 0; i < argc; ++i) {
- new_argv[i] = argv[i];
- }
- new_argv[argc++] = const_cast<char*>("--gtest_filter=-bionic_gtest*");
- *pargv = argv = new_argv;
- }
+ argv.insert(argv.end() - 1, strdup(gtest_filter_str.c_str()));
- // Parse bionic_gtest specific options.
- bool isolate_option = false;
- int job_num_option = 1;
+ // Init default bionic_gtest option.
+ bool isolate_option = true;
+ size_t job_count_option = GetProcessorCount();
- int deadline_option_len = sizeof("--deadline=") - 1;
- int warnline_option_len = sizeof("--warnline=") - 1;
- int gtest_color_option_len = sizeof("--gtest_color=") - 1;
+ size_t deadline_option_len = strlen("--deadline=");
+ size_t warnline_option_len = strlen("--warnline=");
+ size_t gtest_color_option_len = strlen("--gtest_color=");
- for (int i = 1; i < argc; ++i) {
- int remove_arg_num = 0;
+ // Parse bionic_gtest specific options in arguments.
+ for (size_t i = 1; i < argv.size() - 1; ++i) {
+ if (strcmp(argv[i], "-j") == 0) {
+ isolate_option = true; // Enable isolation mode when -j is used.
+ int tmp;
+ if (argv[i + 1] != NULL && (tmp = atoi(argv[i + 1])) > 0) {
+ job_count_option = tmp;
+ argv.erase(argv.begin() + i);
+ } else {
+ job_count_option = GetProcessorCount();
+ }
+ argv.erase(argv.begin() + i);
+ --i;
- // If running in isolation mode, main process doesn't call testing::InitGoogleTest(&argc, argv).
- // So we should parse gtest options for printing here.
- if (strncmp(argv[i], "--gtest_color=", gtest_color_option_len) == 0) {
- testing::GTEST_FLAG(color) = argv[i] + gtest_color_option_len;
-
- } else if (strcmp(argv[i], "--gtest_print_time=0") == 0) {
- testing::GTEST_FLAG(print_time) = false;
-
- } else if (strcmp(argv[i], "--isolate") == 0) {
- isolate_option = true;
- remove_arg_num = 1;
+ } else if (strcmp(argv[i], "--no-isolate") == 0) {
+ isolate_option = false;
+ argv.erase(argv.begin() + i);
+ --i;
} else if (strncmp(argv[i], "--deadline=", deadline_option_len) == 0) {
global_test_run_deadline_in_ms = atoi(argv[i] + deadline_option_len);
@@ -668,7 +676,8 @@
argv[i] + deadline_option_len);
exit(1);
}
- remove_arg_num = 1;
+ argv.erase(argv.begin() + i);
+ --i;
} else if (strncmp(argv[i], "--warnline=", warnline_option_len) == 0) {
global_test_run_warnline_in_ms = atoi(argv[i] + warnline_option_len);
@@ -677,98 +686,107 @@
argv[i] + warnline_option_len);
exit(1);
}
- remove_arg_num = 1;
-
- } else if (strcmp(argv[i], "--bionic_gtest") == 0) {
- // Enable "bionic_gtest*" for self test.
- // Don't remove this option from argument list.
- argv[argc - 1] = const_cast<char*>("--gtest_filter=bionic_gtest*");
-
- } else if (strcmp(argv[i], "-j") == 0) {
- isolate_option = true; // Enable isolation mode when -j is used.
- if (i + 1 < argc && (job_num_option = atoi(argv[i + 1])) > 0) {
- remove_arg_num = 2;
- } else {
- job_num_option = GetCpuNumber();
- remove_arg_num = 1;
- }
- }
-
- if (remove_arg_num != 0) {
- for (int j = i; j < argc - remove_arg_num; ++j) {
- argv[j] = argv[j + remove_arg_num];
- }
- argc -= remove_arg_num;
+ argv.erase(argv.begin() + i);
--i;
+
+ } else if (strncmp(argv[i], "--gtest_color=", gtest_color_option_len) == 0) {
+ // If running in isolation mode, main process doesn't call testing::InitGoogleTest(&argc, argv).
+ // So we should parse gtest options for printing by ourselves.
+ testing::GTEST_FLAG(color) = argv[i] + gtest_color_option_len;
+
+ } else if (strcmp(argv[i], "--gtest_print_time=0") == 0) {
+ testing::GTEST_FLAG(print_time) = false;
+
+ } else if (strcmp(argv[i], "--gtest_list_tests") == 0) {
+ // Disable isolation mode in gtest_list_tests option.
+ isolate_option = false;
+
+ } else if (strcmp(argv[i], "--bionic-selftest") == 0) {
+ // This option is to enable "bionic_selftest*" for self test, and not shown in help informantion.
+ // Don't remove this option from argument list.
+ argv[argv.size() - 2] = strdup("--gtest_filter=bionic_selftest*");
}
}
// Handle --gtest_repeat=[COUNT] option if we are in isolation mode.
// We should check and remove this option to avoid child process running single test for several
// iterations.
- int gtest_repeat_num = 1;
+ size_t gtest_repeat_count = 1;
if (isolate_option == true) {
int len = sizeof("--gtest_repeat=") - 1;
- for (int i = 1; i < argc; ++i) {
+ for (size_t i = 1; i < argv.size() - 1; ++i) {
if (strncmp(argv[i], "--gtest_repeat=", len) == 0) {
- gtest_repeat_num = atoi(argv[i] + len);
- if (gtest_repeat_num < 0) {
+ int tmp = atoi(argv[i] + len);
+ if (tmp < 0) {
fprintf(stderr, "error count for option --gtest_repeat=[COUNT]\n");
return false;
}
- for (int j = i; j < argc - 1; ++j) {
- argv[j] = argv[j + 1];
- }
- --argc;
+ gtest_repeat_count = tmp;
+ argv.erase(argv.begin() + i);
break;
}
}
}
- *pargc = argc;
+ // Add --no-isolate option in argv to suppress subprocess running in isolation mode again.
+ // As DeathTest will try to execve again, this option should always be set.
+ argv.insert(argv.begin() + 1, strdup("--no-isolate"));
// Run tests in isolation mode.
if (isolate_option) {
*exit_flag = true;
std::vector<TestCase> testcase_list;
- if (EnumerateTests(argc, argv, testcase_list) == false) {
+ int argc = static_cast<int>(argv.size()) - 1;
+ if (EnumerateTests(argc, argv.data(), testcase_list) == false) {
return false;
}
- RunTestInSeparateProc(argc, argv, testcase_list, gtest_repeat_num, job_num_option);
+ RunTestInSeparateProc(argc, argv.data(), testcase_list, gtest_repeat_count, job_count_option);
return true;
}
return true;
}
int main(int argc, char** argv) {
+ std::vector<char*> arg_list;
+ for (int i = 0; i < argc; ++i) {
+ arg_list.push_back(argv[i]);
+ }
+ arg_list.push_back(NULL);
+
bool exit_flag;
int return_result = 0;
- if (PickOptions(&argc, &argv, &exit_flag) == false) {
+ if (PickOptions(arg_list, &exit_flag) == false) {
return_result = 1;
} else if (!exit_flag) {
- testing::InitGoogleTest(&argc, argv);
+ argc = static_cast<int>(arg_list.size()) - 1;
+ testing::InitGoogleTest(&argc, arg_list.data());
return_result = RUN_ALL_TESTS();
}
return return_result;
}
//################################################################################
-// Bionic Gtest self test, run this by --bionic_gtest --isolate option.
+// Bionic Gtest self test, run this by --bionic-selftest option.
-TEST(bionic_gtest, test_success) {
+TEST(bionic_selftest, test_success) {
ASSERT_EQ(1, 1);
}
-TEST(bionic_gtest, test_fail) {
+TEST(bionic_selftest, test_fail) {
ASSERT_EQ(0, 1);
}
-TEST(bionic_gtest, test_time_warn) {
+TEST(bionic_selftest, test_time_warn) {
sleep(4);
}
-TEST(bionic_gtest, test_timeout) {
+TEST(bionic_selftest, test_timeout) {
while (1) {}
}
+
+TEST(bionic_selftest, test_signal_SEGV_terminated) {
+ char* p = reinterpret_cast<char*>(static_cast<intptr_t>(atoi("0")));
+ *p = 3;
+}
diff --git a/tests/netdb_test.cpp b/tests/netdb_test.cpp
index 5660bbd..a35f703 100644
--- a/tests/netdb_test.cpp
+++ b/tests/netdb_test.cpp
@@ -19,6 +19,7 @@
#include <gtest/gtest.h>
#include <arpa/inet.h>
+#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
@@ -79,16 +80,34 @@
TEST(netdb, getaddrinfo_hints) {
addrinfo hints;
memset(&hints, 0, sizeof(hints));
- hints.ai_family = AF_UNSPEC;
+ hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo* ai = NULL;
ASSERT_EQ(0, getaddrinfo( "localhost", "9999", &hints, &ai));
- ASSERT_EQ(AF_INET, ai->ai_family);
- ASSERT_EQ(SOCK_STREAM, ai->ai_socktype);
- ASSERT_EQ(IPPROTO_TCP, ai->ai_protocol);
- ASSERT_TRUE(ai->ai_next == NULL);
+ ASSERT_TRUE(ai != NULL);
+ // In glibc, getaddrinfo() converts ::1 to 127.0.0.1 for localhost,
+ // so one or two addrinfo may be returned.
+ addrinfo* tai = ai;
+ while (tai != NULL) {
+ ASSERT_EQ(AF_INET, tai->ai_family);
+ ASSERT_EQ(SOCK_STREAM, tai->ai_socktype);
+ ASSERT_EQ(IPPROTO_TCP, tai->ai_protocol);
+ tai = tai->ai_next;
+ }
+ freeaddrinfo(ai);
+}
+
+TEST(netdb, getaddrinfo_ip6_localhost) {
+ addrinfo* ai = NULL;
+ ASSERT_EQ(0, getaddrinfo("ip6-localhost", NULL, NULL, &ai));
+ ASSERT_TRUE(ai != NULL);
+ ASSERT_GE(ai->ai_addrlen, static_cast<socklen_t>(sizeof(sockaddr_in6)));
+ ASSERT_TRUE(ai->ai_addr != NULL);
+ sockaddr_in6 *addr = reinterpret_cast<sockaddr_in6*>(ai->ai_addr);
+ ASSERT_EQ(addr->sin6_family, AF_INET6);
+ ASSERT_EQ(0, memcmp(&addr->sin6_addr, &in6addr_loopback, sizeof(in6_addr)));
freeaddrinfo(ai);
}
@@ -121,8 +140,41 @@
ASSERT_EQ(EAI_FAMILY, getnameinfo(sa, too_little, tmp, sizeof(tmp), NULL, 0, NI_NUMERICHOST));
}
-void VerifyLocalhost(hostent *hent) {
+TEST(netdb, getnameinfo_localhost) {
+ sockaddr_in addr;
+ char host[NI_MAXHOST];
+ memset(&addr, 0, sizeof(sockaddr_in));
+ addr.sin_family = AF_INET;
+ addr.sin_addr.s_addr = htonl(0x7f000001);
+ ASSERT_EQ(0, getnameinfo(reinterpret_cast<sockaddr*>(&addr), sizeof(addr),
+ host, sizeof(host), NULL, 0, 0));
+ ASSERT_STREQ(host, "localhost");
+}
+
+static void VerifyLocalhostName(const char* name) {
+ // Test possible localhost name and aliases, which depend on /etc/hosts or /system/etc/hosts.
+ ASSERT_TRUE(strcmp(name, "localhost") == 0 ||
+ strcmp(name, "ip6-localhost") == 0 ||
+ strcmp(name, "ip6-loopback") == 0) << name;
+}
+
+TEST(netdb, getnameinfo_ip6_localhost) {
+ sockaddr_in6 addr;
+ char host[NI_MAXHOST];
+ memset(&addr, 0, sizeof(sockaddr_in6));
+ addr.sin6_family = AF_INET6;
+ addr.sin6_addr = in6addr_loopback;
+ ASSERT_EQ(0, getnameinfo(reinterpret_cast<sockaddr*>(&addr), sizeof(addr),
+ host, sizeof(host), NULL, 0, 0));
+ VerifyLocalhostName(host);
+}
+
+static void VerifyLocalhost(hostent *hent) {
ASSERT_TRUE(hent != NULL);
+ VerifyLocalhostName(hent->h_name);
+ for (size_t i = 0; hent->h_aliases[i] != NULL; ++i) {
+ VerifyLocalhostName(hent->h_aliases[i]);
+ }
ASSERT_EQ(hent->h_addrtype, AF_INET);
ASSERT_EQ(hent->h_addr[0], 127);
ASSERT_EQ(hent->h_addr[1], 0);
@@ -185,21 +237,18 @@
}
TEST(netdb, gethostbyaddr) {
- char addr[4];
- ASSERT_EQ(1, inet_pton(AF_INET, "127.0.0.1", addr));
- hostent *hp = gethostbyaddr(addr, sizeof(addr), AF_INET);
+ in_addr addr = { htonl(0x7f000001) };
+ hostent *hp = gethostbyaddr(&addr, sizeof(addr), AF_INET);
VerifyLocalhost(hp);
}
TEST(netdb, gethostbyaddr_r) {
- char addr[4];
- ASSERT_EQ(1, inet_pton(AF_INET, "127.0.0.1", addr));
-
+ in_addr addr = { htonl(0x7f000001) };
hostent hent;
hostent *hp;
char buf[512];
int err;
- int result = gethostbyaddr_r(addr, sizeof(addr), AF_INET, &hent, buf, sizeof(buf), &hp, &err);
+ int result = gethostbyaddr_r(&addr, sizeof(addr), AF_INET, &hent, buf, sizeof(buf), &hp, &err);
ASSERT_EQ(0, result);
VerifyLocalhost(hp);
@@ -209,7 +258,7 @@
hostent hent2;
hostent *hp2;
char buf2[512];
- result = gethostbyaddr_r(addr, sizeof(addr), AF_INET, &hent2, buf2, sizeof(buf2), &hp2, &err);
+ result = gethostbyaddr_r(&addr, sizeof(addr), AF_INET, &hent2, buf2, sizeof(buf2), &hp2, &err);
ASSERT_EQ(0, result);
VerifyLocalhost(hp2);
@@ -237,14 +286,12 @@
}
TEST(netdb, gethostbyaddr_r_ERANGE) {
- char addr[4];
- ASSERT_EQ(1, inet_pton(AF_INET, "127.0.0.1", addr));
-
+ in_addr addr = { htonl(0x7f000001) };
hostent hent;
hostent *hp;
char buf[4]; // Use too small buffer.
int err;
- int result = gethostbyaddr_r(addr, sizeof(addr), AF_INET, &hent, buf, sizeof(buf), &hp, &err);
+ int result = gethostbyaddr_r(&addr, sizeof(addr), AF_INET, &hent, buf, sizeof(buf), &hp, &err);
ASSERT_EQ(ERANGE, result);
ASSERT_EQ(NULL, hp);
}
diff --git a/tests/pthread_test.cpp b/tests/pthread_test.cpp
index 2398f23..cb32079 100644
--- a/tests/pthread_test.cpp
+++ b/tests/pthread_test.cpp
@@ -431,7 +431,7 @@
ASSERT_EQ(ESRCH, pthread_detach(dead_thread));
}
-TEST(pthread, pthread_detach__leak) {
+TEST(pthread, pthread_detach_no_leak) {
size_t initial_bytes = 0;
// Run this loop more than once since the first loop causes some memory
// to be allocated permenantly. Run an extra loop to help catch any subtle
@@ -464,9 +464,7 @@
size_t final_bytes = mallinfo().uordblks;
int leaked_bytes = (final_bytes - initial_bytes);
- // User code (like this test) doesn't know how large pthread_internal_t is.
- // We can be pretty sure it's more than 128 bytes.
- ASSERT_LT(leaked_bytes, 32 /*threads*/ * 128 /*bytes*/);
+ ASSERT_EQ(0, leaked_bytes);
}
TEST(pthread, pthread_getcpuclockid__clock_gettime) {
diff --git a/tests/sys_resource_test.cpp b/tests/sys_resource_test.cpp
index 91d07ab..8cefc65 100644
--- a/tests/sys_resource_test.cpp
+++ b/tests/sys_resource_test.cpp
@@ -14,11 +14,11 @@
* limitations under the License.
*/
-#include <gtest/gtest.h>
-
#include <sys/resource.h>
-TEST(sys_resource, smoke) {
+#include <gtest/gtest.h>
+
+TEST(sys_resource, rlimit_struct_size) {
#if defined(__LP64__) || defined(__GLIBC__)
ASSERT_EQ(sizeof(rlimit), sizeof(rlimit64));
ASSERT_EQ(8U, sizeof(rlim_t));
@@ -26,51 +26,75 @@
ASSERT_NE(sizeof(rlimit), sizeof(rlimit64));
ASSERT_EQ(4U, sizeof(rlim_t));
#endif
+}
- // Read with getrlimit, getrlimit64, and prlimit64.
- // (prlimit is prlimit64 on LP64 and unimplemented on 32-bit.)
- rlimit l32;
- rlimit64 l64;
- rlimit64 pr_l64;
- ASSERT_EQ(0, getrlimit(RLIMIT_CORE, &l32));
- ASSERT_EQ(0, getrlimit64(RLIMIT_CORE, &l64));
- ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, NULL, &pr_l64));
- ASSERT_EQ(l64.rlim_cur, l32.rlim_cur);
- ASSERT_EQ(l64.rlim_cur, pr_l64.rlim_cur);
- ASSERT_EQ(l64.rlim_max, pr_l64.rlim_max);
- if (l64.rlim_max == RLIM64_INFINITY) {
- ASSERT_EQ(RLIM_INFINITY, l32.rlim_max);
- } else {
- ASSERT_EQ(l64.rlim_max, l32.rlim_max);
+class SysResourceTest : public ::testing::Test {
+ protected:
+ virtual void SetUp() {
+ ASSERT_EQ(0, getrlimit(RLIMIT_CORE, &l32_));
+ ASSERT_EQ(0, getrlimit64(RLIMIT_CORE, &l64_));
+ ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, NULL, &pr_l64_));
}
- // Write with setrlimit and read back with everything.
- l32.rlim_cur = 123;
- ASSERT_EQ(0, setrlimit(RLIMIT_CORE, &l32));
- ASSERT_EQ(0, getrlimit(RLIMIT_CORE, &l32));
- ASSERT_EQ(0, getrlimit64(RLIMIT_CORE, &l64));
- ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, NULL, &pr_l64));
- ASSERT_EQ(123U, l32.rlim_cur);
- ASSERT_EQ(l64.rlim_cur, l32.rlim_cur);
- ASSERT_EQ(l64.rlim_cur, pr_l64.rlim_cur);
+ void CheckResourceLimits();
- // Write with setrlimit64 and read back with everything.
- l64.rlim_cur = 456;
- ASSERT_EQ(0, setrlimit64(RLIMIT_CORE, &l64));
- ASSERT_EQ(0, getrlimit(RLIMIT_CORE, &l32));
- ASSERT_EQ(0, getrlimit64(RLIMIT_CORE, &l64));
- ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, NULL, &pr_l64));
- ASSERT_EQ(456U, l32.rlim_cur);
- ASSERT_EQ(l64.rlim_cur, l32.rlim_cur);
- ASSERT_EQ(l64.rlim_cur, pr_l64.rlim_cur);
+ protected:
+ rlimit l32_;
+ rlimit64 l64_;
+ rlimit64 pr_l64_;
+};
- // Write with prlimit64 and read back with everything.
- l64.rlim_cur = 789;
- ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, &l64, NULL));
- ASSERT_EQ(0, getrlimit(RLIMIT_CORE, &l32));
- ASSERT_EQ(0, getrlimit64(RLIMIT_CORE, &l64));
- ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, NULL, &pr_l64));
- ASSERT_EQ(789U, l32.rlim_cur);
- ASSERT_EQ(l64.rlim_cur, l32.rlim_cur);
- ASSERT_EQ(l64.rlim_cur, pr_l64.rlim_cur);
+void SysResourceTest::CheckResourceLimits() {
+ ASSERT_EQ(0, getrlimit(RLIMIT_CORE, &l32_));
+ ASSERT_EQ(0, getrlimit64(RLIMIT_CORE, &l64_));
+ ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, NULL, &pr_l64_));
+ ASSERT_EQ(l64_.rlim_cur, pr_l64_.rlim_cur);
+ if (l64_.rlim_cur == RLIM64_INFINITY) {
+ ASSERT_EQ(RLIM_INFINITY, l32_.rlim_cur);
+ } else {
+ ASSERT_EQ(l64_.rlim_cur, l32_.rlim_cur);
+ }
+
+ ASSERT_EQ(l64_.rlim_max, pr_l64_.rlim_max);
+ if (l64_.rlim_max == RLIM64_INFINITY) {
+ ASSERT_EQ(RLIM_INFINITY, l32_.rlim_max);
+ } else {
+ ASSERT_EQ(l64_.rlim_max, l32_.rlim_max);
+ }
+}
+
+// Force rlim_max to be bigger than a constant so we can continue following test.
+// Change resource limit setting with "ulimit -Hc" in the shell if this test fails.
+TEST_F(SysResourceTest, RLIMIT_CORE_rlim_max_not_zero) {
+ ASSERT_TRUE(l32_.rlim_max == RLIM_INFINITY || l32_.rlim_max >= 456U) <<
+ "RLIMIT_CORE rlim_max = " << l32_.rlim_max;
+}
+
+TEST_F(SysResourceTest, get_resource_limit_equal) {
+ CheckResourceLimits();
+}
+
+TEST_F(SysResourceTest, setrlimit) {
+ l32_.rlim_cur = 123U;
+ ASSERT_EQ(0, setrlimit(RLIMIT_CORE, &l32_));
+ CheckResourceLimits();
+ ASSERT_EQ(123U, l32_.rlim_cur);
+}
+
+TEST_F(SysResourceTest, setrlimit64) {
+ l64_.rlim_cur = 456U;
+ ASSERT_EQ(0, setrlimit64(RLIMIT_CORE, &l64_));
+ CheckResourceLimits();
+ ASSERT_EQ(456U, l64_.rlim_cur);
+}
+
+TEST_F(SysResourceTest, prlimit64) {
+ pr_l64_.rlim_cur = pr_l64_.rlim_max;
+ ASSERT_EQ(0, prlimit64(0, RLIMIT_CORE, &pr_l64_, NULL));
+ CheckResourceLimits();
+ ASSERT_EQ(pr_l64_.rlim_max, pr_l64_.rlim_cur);
+}
+
+TEST_F(SysResourceTest, prlimit) {
+ // prlimit is prlimit64 on LP64 and unimplemented on 32-bit. So we only test prlimit64.
}