summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Makefile56
-rw-r--r--src/app.c41
-rw-r--r--src/libandroid.c464
-rw-r--r--src/libc-sha1.h302
-rw-r--r--src/libc.c64
-rw-r--r--src/liblog.c19
-rw-r--r--src/libpthread.c178
-rw-r--r--src/linker/NOTICE190
-rw-r--r--src/linker/README.TXT144
-rw-r--r--src/linker/bionic_tls.h141
-rw-r--r--src/linker/dlfcn.c333
-rw-r--r--src/linker/linker.c2541
-rw-r--r--src/linker/linker.h226
-rw-r--r--src/linker/linker_debug.h154
-rw-r--r--src/linker/linker_environ.c204
-rw-r--r--src/linker/linker_environ.h54
-rw-r--r--src/linker/linker_format.h43
-rw-r--r--src/linker/rt.c36
-rw-r--r--src/linker/strlcpy.c50
-rw-r--r--src/linker/strlcpy.h10
20 files changed, 5250 insertions, 0 deletions
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..c9c552a
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,56 @@
+PREFIX ?= /usr/local
+BINDIR ?= /bin
+
+MAKEFLAGS += --no-builtin-rules
+
+# GCC 7: -Wstringop-overflow=, -Walloc-size-larger-than=, -Wduplicated-{branches,cond}
+WARNINGS := -Wall -Wextra -Wpedantic -Wformat=2 -Wstrict-aliasing=3 -Wstrict-overflow=3 -Wstack-usage=12500 \
+ -Wfloat-equal -Wcast-align -Wpointer-arith -Wchar-subscripts -Warray-bounds=2 -Wno-unused-parameter
+
+override CFLAGS ?= -g
+override CFLAGS += -std=c11 $(WARNINGS)
+override CPPFLAGS += -Isrc
+
+bins = app
+all: $(bins) runtime/libc.so runtime/libandroid.so runtime/liblog.so
+
+%.o: %.c
+ $(COMPILE.c) $^ -o $@
+
+%.so:
+ $(LINK.c) -shared $(filter %.c,$^) $(LDLIBS) -o $@
+
+%.a:
+ $(AR) rvs $@ $^
+
+$(bins): %:
+ $(LINK.c) $(filter %.c %.a,$^) $(LDLIBS) -o $@
+
+runtime:
+ mkdir -p $@
+
+runtime/libc.so: private CFLAGS += -D_GNU_SOURCE
+runtime/libc.so: runtime src/libc.c
+runtime/libpthread.so: private CFLAGS += -D_GNU_SOURCE
+runtime/libpthread.so: private LDLIBS += -lpthread
+runtime/libpthread.so: runtime src/libpthread.c
+runtime/libandroid.so: runtime src/libandroid.c
+runtime/liblog.so: runtime src/liblog.c
+
+linker.a: CFLAGS += -D_GNU_SOURCE -DANDROID_X86_LINKER -DLINKER_DEBUG=1
+linker.a: CFLAGS += -Wno-pedantic -Wno-variadic-macros -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast
+linker.a: src/linker/dlfcn.o src/linker/linker.o src/linker/linker_environ.o src/linker/rt.o src/linker/strlcpy.o
+
+app: private LDLIBS += -ldl -Wl,-rpath,runtime
+app: src/app.c linker.a runtime/libc.so runtime/libpthread.so runtime/libandroid.so runtime/liblog.so
+
+install-bin: $(bins)
+ install -Dm755 $^ -t "$(DESTDIR)$(PREFIX)$(BINDIR)"
+
+install: install-bin
+
+clean:
+ $(RM) $(bins) *.a src/linker/*.o
+ $(RM) -r runtime
+
+.PHONY: all clean install
diff --git a/src/app.c b/src/app.c
new file mode 100644
index 0000000..6dd8e10
--- /dev/null
+++ b/src/app.c
@@ -0,0 +1,41 @@
+#include <stdlib.h>
+#include <stdio.h>
+#include <libgen.h>
+#include <dlfcn.h>
+#include <err.h>
+#include <assert.h>
+
+extern void *apkenv_android_dlopen(const char*, int);
+extern void *apkenv_android_dlclose(void*);
+extern void *apkenv_android_dlsym(void*, const char*);
+extern void apkenv_parse_library_path(const char *path, char *delim);
+
+int
+main(int argc, const char *argv[])
+{
+ if (argc < 2)
+ errx(EXIT_FAILURE, "usage: so-file");
+
+ dlopen("libpthread.so", RTLD_NOW | RTLD_GLOBAL);
+
+ printf("loading: %s\n", argv[1]);
+
+ char path[4096];
+ snprintf(path, sizeof(path), "%s", argv[1]);
+ apkenv_parse_library_path(dirname(path), ";");
+
+ void *handle;
+ if (!(handle = apkenv_android_dlopen(argv[1], RTLD_NOW | RTLD_LOCAL)))
+ errx(EXIT_FAILURE, "dlopen failed: %s", dlerror());
+
+ printf("loaded: %s\n", argv[1]);
+
+ void* (*JNI_OnLoad)(void*, void*) = apkenv_android_dlsym(handle, "JNI_OnLoad");
+ assert(JNI_OnLoad);
+
+ char data[1024];
+ JNI_OnLoad(data, NULL);
+
+ // apkenv_android_dlclose(handle);
+ return EXIT_SUCCESS;
+}
diff --git a/src/libandroid.c b/src/libandroid.c
new file mode 100644
index 0000000..fb58bd7
--- /dev/null
+++ b/src/libandroid.c
@@ -0,0 +1,464 @@
+#include <stddef.h>
+#include <stdint.h>
+#include <stdlib.h>
+
+// System
+
+#define PROP_NAME_MAX 32
+#define PROP_VALUE_MAX 92
+
+int __system_property_get(const char *name, char *value)
+{
+ return 0;
+}
+
+// AConfiguration
+
+struct AConfiguration
+{
+};
+
+struct AAssetManager
+{
+};
+
+struct AConfiguration*
+AConfiguration_new(void)
+{
+ return calloc(1, sizeof(struct AConfiguration));
+}
+
+void
+AConfiguration_delete(struct AConfiguration *config)
+{
+ free(config);
+}
+
+void
+AConfiguration_fromAssetManager(struct AConfiguration *out, struct AAssetManager *am)
+{
+}
+
+// ALooper
+
+static struct ALooper
+{
+} thread_looper;
+
+typedef void* ALooper_callbackFunc;
+
+struct ALooper*
+ALooper_forThread(void)
+{
+ return &thread_looper;
+}
+
+struct ALooper*
+ALooper_prepare(int opts)
+{
+ return &thread_looper;
+}
+
+void
+ALooper_wake(struct ALooper *looper)
+{
+}
+
+int
+ALooper_pollAll(int timeoutMillis, int *outFd, int *outEvents, void **outData)
+{
+ return 0;
+}
+
+// ASensor
+
+struct ASensor {
+};
+
+const char*
+ASensor_getName(struct ASensor const *sensor)
+{
+ return NULL;
+}
+
+const char*
+ASensor_getVendor(struct ASensor const *sensor)
+{
+ return NULL;
+}
+
+int
+ASensor_getType(struct ASensor const *sensor)
+{
+ return 0;
+}
+
+float
+ASensor_getResolution(struct ASensor const *sensor)
+{
+ return 0;
+}
+
+int
+ASensor_getMinDelay(struct ASensor const *sensor)
+{
+ return 0;
+}
+
+struct ASensorEvent {
+};
+
+struct ASensorEventQueue {
+};
+
+int
+ASensorEventQueue_enableSensor(struct ASensorEventQueue *queue, struct ASensor const *sensor)
+{
+ return 0;
+}
+
+int
+ASensorEventQueue_disableSensor(struct ASensorEventQueue *queue, struct ASensor const *sensor)
+{
+ return 0;
+}
+
+int
+ASensorEventQueue_setEventRate(struct ASensorEventQueue *queue, struct ASensor const *sensor, int32_t usec)
+{
+ return 0;
+}
+
+int
+ASensorEventQueue_hasEvents(struct ASensorEventQueue *queue)
+{
+ return 0;
+}
+
+size_t
+ASensorEventQueue_getEvents(struct ASensorEventQueue *queue, struct ASensorEvent *events, size_t count)
+{
+ return 0;
+}
+
+struct ASensorManager {
+};
+
+struct ASensorList {
+};
+
+struct ASensorManager*
+ASensorManager_getInstance()
+{
+ return NULL;
+}
+
+struct ASensor const*
+ASensorManager_getDefaultSensor(struct ASensorManager *manager, int type)
+{
+ return NULL;
+}
+
+int
+ASensorManager_getSensorList(struct ASensorManager *manager, struct ASensorList *list)
+{
+ return 0;
+}
+
+struct ASensorEventQueue*
+ASensorManager_createEventQueue(struct ASensorManager *manager, struct ALooper *looper, int ident, ALooper_callbackFunc callback, void *data)
+{
+ return NULL;
+}
+
+int
+ASensorManager_destroyEventQueue(struct ASensorManager *manager, struct ASensorEventQueue *queue)
+{
+ return 0;
+}
+
+// AInput
+
+struct AInputEvent
+{
+};
+
+int32_t
+AInputEvent_getType(const struct AInputEvent *event)
+{
+ return 0;
+}
+
+int32_t
+AInputEvent_getDeviceId(const struct AInputEvent *event)
+{
+ return 0;
+}
+
+int32_t
+AInputEvent_getSource(const struct AInputEvent *event)
+{
+ return 0;
+}
+
+int32_t
+AMotionEvent_getEdgeFlags(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getTouchMajor(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getTouchMinor(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+int32_t
+AMotionEvent_getPointerId(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+int64_t
+AMotionEvent_getDownTime(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+size_t
+AMotionEvent_getPointerCount(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getXPrecision(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getYPrecision(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getToolMajor(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getToolMinor(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getX(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getY(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getSize(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getPressure(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+int64_t
+AMotionEvent_getEventTime(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+int32_t
+AMotionEvent_getFlags(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+int32_t
+AMotionEvent_getMetaState(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+int32_t
+AMotionEvent_getAction(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+size_t
+AMotionEvent_getHistorySize(const struct AInputEvent *motion_event)
+{
+ return 0;
+}
+
+int64_t
+AMotionEvent_getHistoricalEventTime(const struct AInputEvent *motion_event, size_t history_index)
+{
+ return 0;
+}
+
+size_t
+AMotionEvent_getHistoricalSize(const struct AInputEvent *motion_event, size_t pointer_index, size_t history_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getHistoricalPressure(const struct AInputEvent *motion_event, size_t pointer_index, size_t history_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getHistoricalX(const struct AInputEvent *motion_event, size_t pointer_index, size_t history_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getHistoricalY(const struct AInputEvent *motion_event, size_t pointer_index, size_t history_index)
+{
+ return 0;
+}
+
+float
+AMotionEvent_getOrientation(const struct AInputEvent *motion_event, size_t pointer_index)
+{
+ return 0;
+}
+
+int32_t
+AKeyEvent_getKeyCode(const struct AInputEvent *key_event)
+{
+ return 0;
+}
+
+int32_t
+AKeyEvent_getMetaState(const struct AInputEvent *key_event)
+{
+ return 0;
+}
+
+int32_t
+AKeyEvent_getAction(const struct AInputEvent *key_event)
+{
+ return 0;
+}
+
+struct AInputQueue
+{
+};
+
+void
+AInputQueue_attachLooper(struct AInputQueue *queue, struct ALooper *looper, int ident, ALooper_callbackFunc callback, void *data)
+{
+}
+
+void
+AInputQueue_detachLooper(struct AInputQueue *queue)
+{
+}
+
+int32_t
+AInputQueue_getEvent(struct AInputQueue *queue, struct AInputEvent **outEvent)
+{
+ return 0;
+}
+
+int32_t
+AInputQueue_preDispatchEvent(struct AInputQueue *queue, struct AInputEvent *event)
+{
+ return 0;
+}
+
+void
+AInputQueue_finishEvent(struct AInputQueue *queue, struct AInputEvent *event, int handled)
+{
+}
+
+// ANative
+
+struct ANativeWindow
+{
+};
+
+struct ANativeWindow_Buffer
+{
+};
+
+struct ARect
+{
+};
+
+typedef void JNIEnv;
+typedef uint32_t jobject;
+
+struct ANativeWindow*
+ANativeWindow_fromSurface(JNIEnv* env, jobject surface)
+{
+ return NULL;
+}
+
+void
+ANativeWindow_acquire(struct ANativeWindow *window)
+{
+}
+
+void
+ANativeWindow_release(struct ANativeWindow *window)
+{
+}
+
+int32_t
+ANativeWindow_getWidth(struct ANativeWindow *window)
+{
+ return 0;
+}
+
+int32_t
+ANativeWindow_getHeight(struct ANativeWindow *window)
+{
+ return 0;
+}
+
+int32_t
+ANativeWindow_setBuffersGeometry(struct ANativeWindow *window, int32_t width, int32_t height, int32_t format)
+{
+ return 0;
+}
+
+int32_t
+ANativeWindow_lock(struct ANativeWindow *window, struct ANativeWindow_Buffer *outBuffer, struct ARect *inOutDirtyBounds)
+{
+ return 0;
+}
+
+int32_t
+ANativeWindow_unlockAndPost(struct ANativeWindow *window)
+{
+ return 0;
+}
diff --git a/src/libc-sha1.h b/src/libc-sha1.h
new file mode 100644
index 0000000..43b562a
--- /dev/null
+++ b/src/libc-sha1.h
@@ -0,0 +1,302 @@
+#pragma once
+
+/*
+ SHA-1 in C
+ By Steve Reid <steve@edmweb.com>
+ 100% Public Domain
+ */
+
+#include <stdint.h>
+
+typedef struct
+{
+ uint32_t state[5];
+ uint32_t count[2];
+ unsigned char buffer[64];
+} SHA1_CTX;
+
+/*
+Test Vectors (from FIPS PUB 180-1)
+"abc"
+ A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D
+"abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"
+ 84983E44 1C3BD26E BAAE4AA1 F95129E5 E54670F1
+A million repetitions of "a"
+ 34AA973C D4C4DAA4 F61EEB2B DBAD2731 6534016F
+*/
+
+/* #define LITTLE_ENDIAN * This should be #define'd already, if true. */
+/* #define SHA1HANDSOFF * Copies data before messing with it. */
+
+#define SHA1HANDSOFF
+
+#include <stdio.h>
+#include <string.h>
+
+#define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits))))
+
+/* blk0() and blk() perform the initial expand. */
+/* I got the idea of expanding during the round function from SSLeay */
+#if BYTE_ORDER == LITTLE_ENDIAN
+#define blk0(i) (block->l[i] = (rol(block->l[i],24)&0xFF00FF00) \
+ |(rol(block->l[i],8)&0x00FF00FF))
+#elif BYTE_ORDER == BIG_ENDIAN
+#define blk0(i) block->l[i]
+#else
+#error "Endianness not defined!"
+#endif
+#define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \
+ ^block->l[(i+2)&15]^block->l[i&15],1))
+
+/* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */
+#define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30);
+#define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30);
+#define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30);
+#define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30);
+#define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30);
+
+
+/* Hash a single 512-bit block. This is the core of the algorithm. */
+
+void SHA1Transform(
+ uint32_t state[5],
+ const unsigned char buffer[64]
+)
+{
+ uint32_t a, b, c, d, e;
+
+ typedef union
+ {
+ unsigned char c[64];
+ uint32_t l[16];
+ } CHAR64LONG16;
+
+#ifdef SHA1HANDSOFF
+ CHAR64LONG16 block[1]; /* use array to appear as a pointer */
+
+ memcpy(block, buffer, 64);
+#else
+ /* The following had better never be used because it causes the
+ * pointer-to-const buffer to be cast into a pointer to non-const.
+ * And the result is written through. I threw a "const" in, hoping
+ * this will cause a diagnostic.
+ */
+ CHAR64LONG16 *block = (const CHAR64LONG16 *) buffer;
+#endif
+ /* Copy context->state[] to working vars */
+ a = state[0];
+ b = state[1];
+ c = state[2];
+ d = state[3];
+ e = state[4];
+ /* 4 rounds of 20 operations each. Loop unrolled. */
+ R0(a, b, c, d, e, 0);
+ R0(e, a, b, c, d, 1);
+ R0(d, e, a, b, c, 2);
+ R0(c, d, e, a, b, 3);
+ R0(b, c, d, e, a, 4);
+ R0(a, b, c, d, e, 5);
+ R0(e, a, b, c, d, 6);
+ R0(d, e, a, b, c, 7);
+ R0(c, d, e, a, b, 8);
+ R0(b, c, d, e, a, 9);
+ R0(a, b, c, d, e, 10);
+ R0(e, a, b, c, d, 11);
+ R0(d, e, a, b, c, 12);
+ R0(c, d, e, a, b, 13);
+ R0(b, c, d, e, a, 14);
+ R0(a, b, c, d, e, 15);
+ R1(e, a, b, c, d, 16);
+ R1(d, e, a, b, c, 17);
+ R1(c, d, e, a, b, 18);
+ R1(b, c, d, e, a, 19);
+ R2(a, b, c, d, e, 20);
+ R2(e, a, b, c, d, 21);
+ R2(d, e, a, b, c, 22);
+ R2(c, d, e, a, b, 23);
+ R2(b, c, d, e, a, 24);
+ R2(a, b, c, d, e, 25);
+ R2(e, a, b, c, d, 26);
+ R2(d, e, a, b, c, 27);
+ R2(c, d, e, a, b, 28);
+ R2(b, c, d, e, a, 29);
+ R2(a, b, c, d, e, 30);
+ R2(e, a, b, c, d, 31);
+ R2(d, e, a, b, c, 32);
+ R2(c, d, e, a, b, 33);
+ R2(b, c, d, e, a, 34);
+ R2(a, b, c, d, e, 35);
+ R2(e, a, b, c, d, 36);
+ R2(d, e, a, b, c, 37);
+ R2(c, d, e, a, b, 38);
+ R2(b, c, d, e, a, 39);
+ R3(a, b, c, d, e, 40);
+ R3(e, a, b, c, d, 41);
+ R3(d, e, a, b, c, 42);
+ R3(c, d, e, a, b, 43);
+ R3(b, c, d, e, a, 44);
+ R3(a, b, c, d, e, 45);
+ R3(e, a, b, c, d, 46);
+ R3(d, e, a, b, c, 47);
+ R3(c, d, e, a, b, 48);
+ R3(b, c, d, e, a, 49);
+ R3(a, b, c, d, e, 50);
+ R3(e, a, b, c, d, 51);
+ R3(d, e, a, b, c, 52);
+ R3(c, d, e, a, b, 53);
+ R3(b, c, d, e, a, 54);
+ R3(a, b, c, d, e, 55);
+ R3(e, a, b, c, d, 56);
+ R3(d, e, a, b, c, 57);
+ R3(c, d, e, a, b, 58);
+ R3(b, c, d, e, a, 59);
+ R4(a, b, c, d, e, 60);
+ R4(e, a, b, c, d, 61);
+ R4(d, e, a, b, c, 62);
+ R4(c, d, e, a, b, 63);
+ R4(b, c, d, e, a, 64);
+ R4(a, b, c, d, e, 65);
+ R4(e, a, b, c, d, 66);
+ R4(d, e, a, b, c, 67);
+ R4(c, d, e, a, b, 68);
+ R4(b, c, d, e, a, 69);
+ R4(a, b, c, d, e, 70);
+ R4(e, a, b, c, d, 71);
+ R4(d, e, a, b, c, 72);
+ R4(c, d, e, a, b, 73);
+ R4(b, c, d, e, a, 74);
+ R4(a, b, c, d, e, 75);
+ R4(e, a, b, c, d, 76);
+ R4(d, e, a, b, c, 77);
+ R4(c, d, e, a, b, 78);
+ R4(b, c, d, e, a, 79);
+ /* Add the working vars back into context.state[] */
+ state[0] += a;
+ state[1] += b;
+ state[2] += c;
+ state[3] += d;
+ state[4] += e;
+ /* Wipe variables */
+ a = b = c = d = e = 0;
+#ifdef SHA1HANDSOFF
+ memset(block, '\0', sizeof(block));
+#endif
+}
+
+
+/* SHA1Init - Initialize new context */
+
+void SHA1Init(
+ SHA1_CTX * context
+)
+{
+ /* SHA1 initialization constants */
+ context->state[0] = 0x67452301;
+ context->state[1] = 0xEFCDAB89;
+ context->state[2] = 0x98BADCFE;
+ context->state[3] = 0x10325476;
+ context->state[4] = 0xC3D2E1F0;
+ context->count[0] = context->count[1] = 0;
+}
+
+
+/* Run your data through this. */
+
+void SHA1Update(
+ SHA1_CTX * context,
+ const unsigned char *data,
+ uint32_t len
+)
+{
+ uint32_t i;
+
+ uint32_t j;
+
+ j = context->count[0];
+ if ((context->count[0] += len << 3) < j)
+ context->count[1]++;
+ context->count[1] += (len >> 29);
+ j = (j >> 3) & 63;
+ if ((j + len) > 63)
+ {
+ memcpy(&context->buffer[j], data, (i = 64 - j));
+ SHA1Transform(context->state, context->buffer);
+ for (; i + 63 < len; i += 64)
+ {
+ SHA1Transform(context->state, &data[i]);
+ }
+ j = 0;
+ }
+ else
+ i = 0;
+ memcpy(&context->buffer[j], &data[i], len - i);
+}
+
+
+/* Add padding and return the message digest. */
+
+void SHA1Final(
+ unsigned char digest[20],
+ SHA1_CTX * context
+)
+{
+ unsigned i;
+
+ unsigned char finalcount[8];
+
+ unsigned char c;
+
+#if 0 /* untested "improvement" by DHR */
+ /* Convert context->count to a sequence of bytes
+ * in finalcount. Second element first, but
+ * big-endian order within element.
+ * But we do it all backwards.
+ */
+ unsigned char *fcp = &finalcount[8];
+
+ for (i = 0; i < 2; i++)
+ {
+ uint32_t t = context->count[i];
+
+ int j;
+
+ for (j = 0; j < 4; t >>= 8, j++)
+ *--fcp = (unsigned char) t}
+#else
+ for (i = 0; i < 8; i++)
+ {
+ finalcount[i] = (unsigned char) ((context->count[(i >= 4 ? 0 : 1)] >> ((3 - (i & 3)) * 8)) & 255); /* Endian independent */
+ }
+#endif
+ c = 0200;
+ SHA1Update(context, &c, 1);
+ while ((context->count[0] & 504) != 448)
+ {
+ c = 0000;
+ SHA1Update(context, &c, 1);
+ }
+ SHA1Update(context, finalcount, 8); /* Should cause a SHA1Transform() */
+ for (i = 0; i < 20; i++)
+ {
+ digest[i] = (unsigned char)
+ ((context->state[i >> 2] >> ((3 - (i & 3)) * 8)) & 255);
+ }
+ /* Wipe variables */
+ memset(context, '\0', sizeof(*context));
+ memset(&finalcount, '\0', sizeof(finalcount));
+}
+
+void SHA1(
+ char *hash_out,
+ const char *str,
+ int len)
+{
+ SHA1_CTX ctx;
+ int ii;
+
+ SHA1Init(&ctx);
+ for (ii=0; ii<len; ii+=1)
+ SHA1Update(&ctx, (const unsigned char*)str + ii, 1);
+ SHA1Final((unsigned char *)hash_out, &ctx);
+ hash_out[20] = '\0';
+}
diff --git a/src/libc.c b/src/libc.c
new file mode 100644
index 0000000..f83395b
--- /dev/null
+++ b/src/libc.c
@@ -0,0 +1,64 @@
+#include <unistd.h>
+#include <stdint.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <math.h>
+#include <sys/stat.h>
+#include <sys/types.h>
+#include <sys/syscall.h>
+
+// Stuff that doesn't exist in glibc
+
+void
+__assert2(const char* file, int line, const char* function, const char* failed_expression)
+{
+ fprintf(stderr, "%s:%d: %s: assertion \"%s\" failed", file, line, function, failed_expression);
+ abort();
+}
+
+pid_t
+gettid(void)
+{
+ return syscall(SYS_gettid);
+}
+
+#include "libc-sha1.h"
+
+// Stuff needed for runtime compatibility, but not neccessary for linking
+// Also stuff that exists in glibc, but needs to be wrapped for runtime compatibility
+
+const char *bionic__ctype_, *bionic__tolower_tab_, *bionic__toupper_tab_;
+char bionic___sF[0x54];
+int bionic___errno;
+
+int
+bionic_stat(const char *restrict path, struct stat *restrict buf)
+{
+ return stat(path, buf);
+}
+
+int
+bionic_lstat(const char *restrict path, struct stat *restrict buf)
+{
+ return lstat(path, buf);
+}
+
+int
+bionic_fstat(int fd, struct stat *buf)
+{
+ return fstat(fd, buf);
+}
+
+int
+bionic___isfinitef(float f)
+{
+ return isfinite(f);
+}
+
+uintptr_t bionic___stack_chk_guard = 4;
+
+__attribute__((noreturn))
+void bionic___stack_chk_fail(void)
+{
+ abort();
+}
diff --git a/src/liblog.c b/src/liblog.c
new file mode 100644
index 0000000..522166e
--- /dev/null
+++ b/src/liblog.c
@@ -0,0 +1,19 @@
+#include <stdarg.h>
+
+int
+__android_log_print(int prio, const char *tag, const char *fmt, ...)
+{
+ return 0;
+}
+
+int
+__android_log_vprint(int prio, const char *tag, const char *fmt, va_list ap)
+{
+ return 0;
+}
+
+int
+__android_log_write(int prio, const char *tag, const char *text)
+{
+ return 0;
+}
diff --git a/src/libpthread.c b/src/libpthread.c
new file mode 100644
index 0000000..3359c4a
--- /dev/null
+++ b/src/libpthread.c
@@ -0,0 +1,178 @@
+#include <stdint.h>
+#include <stdbool.h>
+#include <unistd.h>
+#include <memory.h>
+#include <pthread.h>
+#include <assert.h>
+#include <sys/mman.h>
+
+typedef struct {
+ union {
+#if defined(__LP64__)
+ int32_t __private[10];
+#else
+ int32_t __private[1];
+#endif
+ void *glibc;
+ };
+} bionic_mutex_t;
+
+typedef struct {
+ union {
+ long __private;
+ void *glibc;
+ };
+} bionic_mutexattr_t;
+
+static const struct {
+ bionic_mutex_t bionic;
+ pthread_mutex_t glibc;
+} bionic_mutex_init_map[] = {
+ { .bionic = {{{ ((PTHREAD_MUTEX_NORMAL & 3) << 14) }}}, .glibc = PTHREAD_MUTEX_INITIALIZER },
+ { .bionic = {{{ ((PTHREAD_MUTEX_RECURSIVE & 3) << 14) }}}, .glibc = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP },
+ { .bionic = {{{ ((PTHREAD_MUTEX_ERRORCHECK & 3) << 14) }}}, .glibc = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP },
+};
+
+typedef struct {
+ union {
+#if defined(__LP64__)
+ int32_t __private[12];
+#else
+ int32_t __private[1];
+#endif
+ void *glibc;
+ };
+} bionic_cond_t;
+
+typedef struct {
+ union {
+ long __private;
+ void *glibc;
+ };
+} bionic_condattr_t;
+
+typedef int bionic_key_t;
+
+_Static_assert(sizeof(bionic_key_t) == sizeof(pthread_key_t), "bionic_key_t and pthread_key_t size mismatch");
+
+#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
+#define IS_MAPPED(x) is_mapped(x->glibc, sizeof(x))
+#define INIT_IF_NOT_MAPPED(x, init) do { if (!IS_MAPPED(x)) init(x); } while(0)
+
+static bool
+is_mapped(void *mem, const size_t sz)
+{
+ const size_t ps = sysconf(_SC_PAGESIZE);
+ assert(ps > 0);
+ unsigned char vec[(sz + ps - 1) / ps];
+ return !mincore(mem, sz, vec);
+}
+
+int
+bionic_pthread_cond_timedwait_monotonic_np(bionic_cond_t *cond, bionic_mutex_t *mutex, const struct timespec *abstime)
+{
+ return 0;
+}
+
+int
+bionic_pthread_mutexattr_settype(bionic_mutexattr_t *attr, int type)
+{
+ assert(attr && IS_MAPPED(attr));
+ return pthread_mutexattr_settype(attr->glibc, type);
+}
+
+int
+bionic_pthread_mutexattr_destroy(bionic_mutexattr_t *attr)
+{
+ assert(attr);
+ int ret = 0;
+ if (IS_MAPPED(attr)) {
+ ret = pthread_mutexattr_destroy(attr->glibc);
+ munmap(attr->glibc, sizeof(pthread_mutexattr_t));
+ }
+ return ret;
+}
+
+int
+bionic_pthread_mutexattr_init(bionic_mutexattr_t *attr)
+{
+ assert(attr);
+ if (!IS_MAPPED(attr))
+ attr->glibc = mmap(NULL, sizeof(pthread_mutexattr_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
+ return pthread_mutexattr_init(attr->glibc);
+}
+
+int
+bionic_pthread_mutex_destroy(bionic_mutex_t *mutex)
+{
+ assert(mutex);
+ int ret = 0;
+ if (IS_MAPPED(mutex)) {
+ ret = pthread_mutex_destroy(mutex->glibc);
+ munmap(mutex->glibc, sizeof(pthread_mutex_t));
+ }
+ return ret;
+}
+
+int
+bionic_pthread_mutex_init(bionic_mutex_t *mutex, const bionic_mutexattr_t *attr)
+{
+ assert(mutex && (!attr || IS_MAPPED(attr)));
+ if (!IS_MAPPED(mutex))
+ mutex->glibc = mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
+ return pthread_mutex_init(mutex->glibc, (attr ? attr->glibc : NULL));
+}
+
+static void
+default_pthread_mutex_init(bionic_mutex_t *mutex)
+{
+ assert(mutex && !IS_MAPPED(mutex));
+ mutex->glibc = mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
+
+ for (size_t i = 0; i < ARRAY_SIZE(bionic_mutex_init_map); ++i) {
+ if (!memcmp(&bionic_mutex_init_map[i].bionic, mutex, sizeof(*mutex)))
+ continue;
+
+ memcpy(mutex->glibc, &bionic_mutex_init_map[i].glibc, sizeof(bionic_mutex_init_map[i].glibc));
+ return;
+ }
+
+ assert(0 && "no such default initializer???");
+}
+
+int
+bionic_pthread_mutex_lock(bionic_mutex_t *mutex)
+{
+ assert(mutex);
+ INIT_IF_NOT_MAPPED(mutex, default_pthread_mutex_init);
+ return pthread_mutex_lock(mutex->glibc);
+}
+
+int
+bionic_pthread_cond_destroy(bionic_cond_t *cond)
+{
+ assert(cond);
+ int ret = 0;
+ if (IS_MAPPED(cond)) {
+ ret = pthread_cond_destroy(cond->glibc);
+ munmap(cond->glibc, sizeof(pthread_cond_t));
+ }
+ return ret;
+}
+
+int
+bionic_pthread_cond_init(bionic_cond_t *cond, const bionic_condattr_t *attr)
+{
+ assert(cond && (!attr || IS_MAPPED(attr)));
+ if (!IS_MAPPED(cond))
+ cond->glibc = mmap(NULL, sizeof(pthread_cond_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
+ return pthread_cond_init(cond->glibc, (attr ? attr->glibc : NULL));
+}
+
+static void
+default_pthread_cond_init(bionic_cond_t *cond)
+{
+ assert(cond && !IS_MAPPED(cond));
+ cond->glibc = mmap(NULL, sizeof(pthread_cond_t), PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_SHARED, -1, 0);
+ memset(cond->glibc, 0, sizeof(pthread_cond_t));
+}
diff --git a/src/linker/NOTICE b/src/linker/NOTICE
new file mode 100644
index 0000000..c5b1efa
--- /dev/null
+++ b/src/linker/NOTICE
@@ -0,0 +1,190 @@
+
+ Copyright (c) 2005-2008, 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.
+
+ 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.
+
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
diff --git a/src/linker/README.TXT b/src/linker/README.TXT
new file mode 100644
index 0000000..f920b97
--- /dev/null
+++ b/src/linker/README.TXT
@@ -0,0 +1,144 @@
+Android Dynamic Linker Design Notes
+===================================
+
+Introduction:
+-------------
+
+This document provides several notes related to the design of the Android
+dynamic linker.
+
+
+Prelinking:
+-----------
+
+System libraries in Android are internally prelinked, which means that
+any internal relocations within them are stripped from the corresponding
+shared object, in order to reduce size and speed up loading.
+
+Such libraries can only be loaded at the very specific virtual memory address
+they have been prelinked to (during the build process). The list of prelinked
+system libraries and their corresponding virtual memory address is found in
+the file:
+
+ build/core/prelink-linux-<arch>.map
+
+It should be updated each time a new system library is added to the
+system.
+
+The prelink step happens at build time, and uses the 'soslim' and 'apriori'
+tools:
+
+ - 'apriori' is the real prelink tool which removes relocations from the
+ shared object, however, it must be given a list of symbols to remove
+ from the file.
+
+ - 'soslim' is used to find symbols in an executable ELF file
+ and generate a list that can be passed to 'apriori'.
+
+By default, these tools are only used to remove internal symbols from
+libraries, though they have been designed to allow more aggressive
+optimizations (e.g. 'global' prelinking and symbol stripping, which
+prevent replacing individual system libraries though).
+
+You can disable prelinking at build time by modifying your Android.mk with
+a line like:
+
+ LOCAL_PRELINK_MODULE := false
+
+
+Initialization and Termination functions:
+-----------------------------------------
+
+The Unix Sys V Binary Interface standard states that an
+executable can have the following entries in its .dynamic
+section:
+
+ DT_INIT
+ Points to the address of an initialization function
+ that must be called when the file is loaded.
+
+ DT_INIT_ARRAY
+ Points to an array of function addresses that must be
+ called, in-order, to perform initialization. Some of
+ the entries in the array can be 0 or -1, and should
+ be ignored.
+
+ Note: this is generally stored in a .init_array section
+
+ DT_INIT_ARRAYSZ
+ The size of the DT_INITARRAY, if any
+
+ DT_FINI
+ Points to the address of a finalization function which
+ must be called when the file is unloaded or the process
+ terminated.
+
+ DT_FINI_ARRAY
+ Same as DT_INITARRAY but for finalizers. Note that the
+ functions must be called in reverse-order though
+
+ Note: this is generally stored in a .fini_array section
+
+ DT_FINI_ARRAYSZ
+ Size of FT_FINIARRAY
+
+ DT_PREINIT_ARRAY
+ An array similar to DT_INIT_ARRAY which must *only* be
+ present in executables, not shared libraries, which contains
+ a list of functions that need to be called before any other
+ initialization function (i.e. DT_INIT and/or DT_INIT_ARRAY)
+ in the executable or any of its libraries.
+
+ Note: this is generally stored in a .preinit_array section
+
+ DT_PREINIT_ARRAYSZ
+ The size of DT_PREINIT_ARRAY
+
+If both a DT_INIT and DT_INITARRAY entry are present, the DT_INIT
+function must be called before the DT_INITARRAY functions.
+
+Consequently, the DT_FINIARRAY must be parsed in reverse order before
+the DT_FINI function, if both are available.
+
+Note that the implementation of static C++ constructors is very
+much processor dependent, and may use different ELF sections.
+
+On the ARM (see "C++ ABI for ARM" document), the static constructors
+must be called explicitly from the DT_INIT_ARRAY, and each one of them
+shall register a destructor by calling the special __eabi_atexit()
+function (provided by the C library). The DT_FINI_ARRAY is not used
+by static C++ destructors.
+
+On x86, the lists of constructors and destructors are placed in special
+sections named ".ctors" and ".dtors", and the DT_INIT / DT_FINI functions
+are in charge of calling them explicitly.
+
+
+Debugging:
+----------
+
+It is possible to enable debug output in the dynamic linker. To do so,
+follow these steps:
+
+1/ Modify the line in Android.mk that says:
+
+ LOCAL_CFLAGS += -DLINKER_DEBUG=0
+
+ Into the following:
+
+ LOCAL_CFLAGS += -DLINKER_DEBUG=1
+
+2/ Force-rebuild the dynamic linker:
+
+ cd bionic/linker
+ mm -B
+
+3/ Rebuild a new system image.
+
+You can increase the verbosity of debug traces by defining the DEBUG
+environment variable to a numeric value from 0 to 2. This will only
+affect new processes being launched.
+
+By default, traces are sent to logcat, with the "linker" tag. You can
+change this to go to stdout instead by setting the definition of
+LINKER_DEBUG_TO_LOG to 0 in "linker_debug.h".
diff --git a/src/linker/bionic_tls.h b/src/linker/bionic_tls.h
new file mode 100644
index 0000000..3907a83
--- /dev/null
+++ b/src/linker/bionic_tls.h
@@ -0,0 +1,141 @@
+/*
+ * Copyright (C) 2008 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 _SYS_TLS_H
+#define _SYS_TLS_H
+
+#define HAVE_ARM_TLS_REGISTER
+
+#include <sys/cdefs.h>
+
+__BEGIN_DECLS
+
+/** WARNING WARNING WARNING
+ **
+ ** This header file is *NOT* part of the public Bionic ABI/API
+ ** and should not be used/included by user-serviceable parts of
+ ** the system (e.g. applications).
+ **
+ ** It is only provided here for the benefit of the system dynamic
+ ** linker and the OpenGL sub-system (which needs to access the
+ ** pre-allocated slot directly for performance reason).
+ **/
+
+/* maximum number of elements in the TLS array */
+#define BIONIC_TLS_SLOTS 64
+
+/* note that slot 0, called TLS_SLOT_SELF must point to itself.
+ * this is required to implement thread-local storage with the x86
+ * Linux kernel, that reads the TLS from fs:[0], where 'fs' is a
+ * thread-specific segment descriptor...
+ */
+
+/* Well known TLS slots */
+#define TLS_SLOT_SELF 0
+#define TLS_SLOT_THREAD_ID 1
+#define TLS_SLOT_ERRNO 2
+
+#define TLS_SLOT_OPENGL_API 3
+#define TLS_SLOT_OPENGL 4
+
+/* this slot is only used to pass information from the dynamic linker to
+ * libc.so when the C library is loaded in to memory. The C runtime init
+ * function will then clear it. Since its use is extremely temporary,
+ * we reuse an existing location.
+ */
+#define TLS_SLOT_BIONIC_PREINIT (TLS_SLOT_ERRNO+1)
+
+/* small technical note: it is not possible to call pthread_setspecific
+ * on keys that are <= TLS_SLOT_MAX_WELL_KNOWN, which is why it is set to
+ * TLS_SLOT_ERRNO.
+ *
+ * later slots like TLS_SLOT_OPENGL are pre-allocated through the use of
+ * TLS_DEFAULT_ALLOC_MAP. this means that there is no need to use
+ * pthread_key_create() to initialize them. on the other hand, there is
+ * no destructor associated to them (we might need to implement this later)
+ */
+#define TLS_SLOT_MAX_WELL_KNOWN TLS_SLOT_ERRNO
+
+#define TLS_DEFAULT_ALLOC_MAP 0x0000001F
+
+/* set the Thread Local Storage, must contain at least BIONIC_TLS_SLOTS pointers */
+extern void __init_tls(void** tls, void* thread_info);
+
+/* syscall only, do not call directly */
+extern int __set_tls(void *ptr);
+
+/* get the TLS */
+#ifdef __arm__
+/* The standard way to get the TLS is to call a kernel helper
+ * function (i.e. a function provided at a fixed address in a
+ * "magic page" mapped in all user-space address spaces ), which
+ * contains the most appropriate code path for the target device.
+ *
+ * However, for performance reasons, we're going to use our own
+ * machine code for the system's C shared library.
+ *
+ * We cannot use this optimization in the static version of the
+ * C library, because we don't know where the corresponding code
+ * is going to run.
+ */
+# ifdef LIBC_STATIC
+
+/* Use the kernel helper in static C library. */
+ typedef volatile void* (__kernel_get_tls_t)(void);
+# define __get_tls() (*(__kernel_get_tls_t *)0xffff0fe0)()
+
+# else /* !LIBC_STATIC */
+/* Use optimized code path.
+ * Note that HAVE_ARM_TLS_REGISTER is build-specific
+ * (it must match your kernel configuration)
+ */
+# ifdef HAVE_ARM_TLS_REGISTER
+ /* We can read the address directly from a coprocessor
+ * register, which avoids touching the data cache
+ * completely.
+ */
+# define __get_tls() \
+ ({ register unsigned int __val asm("r0"); \
+ asm ("mrc p15, 0, r0, c13, c0, 3" : "=r"(__val) ); \
+ (volatile void*)__val; })
+# else /* !HAVE_ARM_TLS_REGISTER */
+ /* The kernel provides the address of the TLS at a fixed
+ * address of the magic page too.
+ */
+# define __get_tls() ( *((volatile void **) 0xffff0ff0) )
+# endif
+# endif /* !LIBC_STATIC */
+#else /* !ARM */
+extern void* __get_tls( void );
+#endif /* !ARM */
+
+/* return the stack base and size, used by our malloc debugger */
+extern void* __get_stack_base(int *p_stack_size);
+
+__END_DECLS
+
+#endif /* _SYS_TLS_H */
diff --git a/src/linker/dlfcn.c b/src/linker/dlfcn.c
new file mode 100644
index 0000000..3f76e92
--- /dev/null
+++ b/src/linker/dlfcn.c
@@ -0,0 +1,333 @@
+/*
+ * Copyright (C) 2007 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.
+ */
+#include <dlfcn.h>
+#include <pthread.h>
+#include <time.h>
+#include <stdio.h>
+#include <string.h>
+#include "linker.h"
+#include "linker_format.h"
+
+/* for apkenv_get_hooked_symbol */
+// #include "../compat/hooks.h"
+
+/* for create_wrapper */
+// #include "../debug/wrappers.h"
+
+#include "linker_debug.h"
+
+#ifdef APKENV_DEBUG
+# define LINKER_DEBUG_PRINTF(...) PRINT(__VA_ARGS__)
+#else
+# define LINKER_DEBUG_PRINTF(...)
+#endif
+/* This file hijacks the symbols stubbed out in libdl.so. */
+
+#define DL_SUCCESS 0
+#define DL_ERR_CANNOT_LOAD_LIBRARY 1
+#define DL_ERR_INVALID_LIBRARY_HANDLE 2
+#define DL_ERR_BAD_SYMBOL_NAME 3
+#define DL_ERR_SYMBOL_NOT_FOUND 4
+#define DL_ERR_SYMBOL_NOT_GLOBAL 5
+
+static char dl_err_buf[1024];
+static const char *dl_err_str;
+
+static const char *dl_errors[] = {
+ [DL_ERR_CANNOT_LOAD_LIBRARY] = "Cannot load library",
+ [DL_ERR_INVALID_LIBRARY_HANDLE] = "Invalid library handle",
+ [DL_ERR_BAD_SYMBOL_NAME] = "Invalid symbol name",
+ [DL_ERR_SYMBOL_NOT_FOUND] = "Symbol not found",
+ [DL_ERR_SYMBOL_NOT_GLOBAL] = "Symbol is not global",
+};
+
+#define likely(expr) __builtin_expect (expr, 1)
+#define unlikely(expr) __builtin_expect (expr, 0)
+
+pthread_mutex_t apkenv_dl_lock = PTHREAD_MUTEX_INITIALIZER;
+
+static void set_dlerror(int err)
+{
+ format_buffer(dl_err_buf, sizeof(dl_err_buf), "%s: %s", dl_errors[err],
+ apkenv_linker_get_error());
+ dl_err_str = (const char *)&dl_err_buf[0];
+}
+
+void *apkenv_android_dlopen(const char *filename, int flag)
+{
+ soinfo *ret;
+
+ pthread_mutex_lock(&apkenv_dl_lock);
+ ret = apkenv_find_library(filename);
+
+ if (unlikely(ret == NULL)) {
+ set_dlerror(DL_ERR_CANNOT_LOAD_LIBRARY);
+ } else {
+ apkenv_call_constructors_recursive(ret);
+ ret->refcount++;
+ }
+ pthread_mutex_unlock(&apkenv_dl_lock);
+ return ret;
+}
+
+static void *apkenv_android_dlopen_wrap(const char *filename, int flag)
+{
+#if 0
+ void *ret = get_builtin_lib_handle(filename);
+ if (ret)
+ return ret;
+#endif
+
+ return apkenv_android_dlopen(filename, flag);
+}
+
+const char *apkenv_android_dlerror(void)
+{
+ const char *tmp = dl_err_str;
+ dl_err_str = NULL;
+ return (const char *)tmp;
+}
+
+enum {
+ WRAPPER_DYNHOOK,
+};
+
+void *apkenv_android_dlsym(void *handle, const char *symbol)
+{
+ soinfo *found;
+ Elf32_Sym *sym;
+ unsigned bind;
+
+ pthread_mutex_lock(&apkenv_dl_lock);
+
+ if(unlikely(handle == 0)) {
+ set_dlerror(DL_ERR_INVALID_LIBRARY_HANDLE);
+ goto err;
+ }
+ if(unlikely(symbol == 0)) {
+ set_dlerror(DL_ERR_BAD_SYMBOL_NAME);
+ goto err;
+ }
+
+#if 0
+ void *sym_addr;
+ if(0 != (sym_addr = apkenv_get_hooked_symbol_dlfcn(handle, symbol)))
+ {
+ LINKER_DEBUG_PRINTF("symbol %s hooked to %x\n",symbol,sym_addr);
+ pthread_mutex_unlock(&apkenv_dl_lock);
+ return sym_addr;
+ }
+
+ if (is_builtin_lib_handle(handle)) {
+ /* must be hooked.. */
+ set_dlerror(DL_ERR_SYMBOL_NOT_FOUND);
+ goto err;
+ }
+#endif
+
+ if(handle == RTLD_DEFAULT) {
+ sym = apkenv_lookup(symbol, &found, NULL);
+ } else if(handle == RTLD_NEXT) {
+ void *ret_addr = __builtin_return_address(0);
+ soinfo *si = apkenv_find_containing_library(ret_addr);
+
+ sym = NULL;
+ if(si && si->next) {
+ sym = apkenv_lookup(symbol, &found, si->next);
+ }
+ } else {
+ found = (soinfo*)handle;
+ sym = apkenv_lookup_in_library(found, symbol);
+ }
+
+ if(likely(sym != 0)) {
+ bind = ELF32_ST_BIND(sym->st_info);
+
+ if(likely((bind == STB_GLOBAL) && (sym->st_shndx != 0))) {
+ unsigned ret = sym->st_value + found->base;
+ pthread_mutex_unlock(&apkenv_dl_lock);
+ return create_wrapper((char*)symbol, (void*)ret, WRAPPER_DYNHOOK);
+ }
+
+ set_dlerror(DL_ERR_SYMBOL_NOT_GLOBAL);
+ }
+ else
+ set_dlerror(DL_ERR_SYMBOL_NOT_FOUND);
+
+err:
+ LINKER_DEBUG_PRINTF("symbol %s has not been hooked\n",symbol);
+ pthread_mutex_unlock(&apkenv_dl_lock);
+ return 0;
+}
+
+int apkenv_android_dladdr(const void *addr, Dl_info *info)
+{
+ int ret = 0;
+
+ pthread_mutex_lock(&apkenv_dl_lock);
+
+ /* Determine if this address can be found in any library currently mapped */
+ soinfo *si = apkenv_find_containing_library(addr);
+
+ if(si) {
+ memset(info, 0, sizeof(*info));
+
+ info->dli_fname = si->name;
+ info->dli_fbase = (void*)(uintptr_t)si->base;
+
+ /* Determine if any symbol in the library contains the specified address */
+ Elf32_Sym *sym = apkenv_find_containing_symbol(addr, si);
+
+ if(sym != NULL) {
+ info->dli_sname = si->strtab + sym->st_name;
+ info->dli_saddr = (void*)(uintptr_t)(si->base + sym->st_value);
+ }
+
+ ret = 1;
+ }
+
+ pthread_mutex_unlock(&apkenv_dl_lock);
+
+ return ret;
+}
+
+int apkenv_android_dlclose(void *handle)
+{
+#if 0
+ if (is_builtin_lib_handle(handle))
+ return 0;
+#endif
+
+ pthread_mutex_lock(&apkenv_dl_lock);
+ (void)apkenv_unload_library((soinfo*)handle);
+ pthread_mutex_unlock(&apkenv_dl_lock);
+ return 0;
+}
+
+
+#if defined(ANDROID_ARM_LINKER)
+// 0000000 00011111 111112 22222222 2333333 333344444444445555555
+// 0123456 78901234 567890 12345678 9012345 678901234567890123456
+#define ANDROID_LIBDL_STRTAB \
+ "dlopen\0dlclose\0dlsym\0dlerror\0dladdr\0dl_unwind_find_exidx\0"
+
+_Unwind_Ptr apkenv_android_dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount);
+
+#elif defined(ANDROID_X86_LINKER)
+// 0000000 00011111 111112 22222222 2333333 3333444444444455
+// 0123456 78901234 567890 12345678 9012345 6789012345678901
+#define ANDROID_LIBDL_STRTAB \
+ "dlopen\0dlclose\0dlsym\0dlerror\0dladdr\0dl_iterate_phdr\0"
+int
+apkenv_android_dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
+ void *data);
+
+#else
+#error Unsupported architecture. Only ARM and x86 are presently supported.
+#endif
+
+static Elf32_Sym apkenv_libdl_symtab[7];
+
+/* Fake out a hash table with a single bucket.
+ * A search of the hash table will look through
+ * apkenv_libdl_symtab starting with index [1], then
+ * use apkenv_libdl_chains to find the next index to
+ * look at. apkenv_libdl_chains should be set up to
+ * walk through every element in apkenv_libdl_symtab,
+ * and then end with 0 (sentinel value).
+ *
+ * I.e., apkenv_libdl_chains should look like
+ * { 0, 2, 3, ... N, 0 } where N is the number
+ * of actual symbols, or nelems(apkenv_libdl_symtab)-1
+ * (since the first element of apkenv_libdl_symtab is not
+ * a real symbol).
+ *
+ * (see _elf_lookup())
+ *
+ * Note that adding any new symbols here requires
+ * stubbing them out in libdl.
+ */
+static unsigned apkenv_libdl_buckets[1] = { 1 };
+static unsigned apkenv_libdl_chains[7] = { 0, 2, 3, 4, 5, 6, 0 };
+
+soinfo apkenv_libdl_info = {
+ .name = "libdl.so",
+ .flags = FLAG_LINKED,
+
+ .strtab = ANDROID_LIBDL_STRTAB,
+ .symtab = apkenv_libdl_symtab,
+
+ .nbucket = 1,
+ .nchain = 7,
+ .bucket = apkenv_libdl_buckets,
+ .chain = apkenv_libdl_chains,
+};
+
+__attribute__((constructor))
+void
+construct(void)
+{
+ const Elf32_Sym symtab[sizeof(apkenv_libdl_symtab) / sizeof(apkenv_libdl_symtab[0])] = {
+ // total length of apkenv_libdl_info.strtab, including trailing 0
+ // This is actually the the STH_UNDEF entry. Technically, it's
+ // supposed to have st_name == 0, but instead, it points to an index
+ // in the strtab with a \0 to make iterating through the symtab easier.
+ {
+ .st_name = sizeof(ANDROID_LIBDL_STRTAB) - 1,
+ }, {
+ .st_name = 0, // starting index of the name in apkenv_libdl_info.strtab
+ .st_value = (Elf32_Addr)(uintptr_t)apkenv_android_dlopen_wrap,
+ .st_info = STB_GLOBAL << 4,
+ .st_shndx = 1,
+ }, {
+ .st_name = 7,
+ .st_value = (Elf32_Addr)(uintptr_t)apkenv_android_dlclose,
+ .st_info = STB_GLOBAL << 4,
+ .st_shndx = 1,
+ }, {
+ .st_name = 15,
+ .st_value = (Elf32_Addr)(uintptr_t)apkenv_android_dlsym,
+ .st_info = STB_GLOBAL << 4,
+ .st_shndx = 1,
+ }, {
+ .st_name = 21,
+ .st_value = (Elf32_Addr)(uintptr_t)apkenv_android_dlerror,
+ .st_info = STB_GLOBAL << 4,
+ .st_shndx = 1,
+ }, {
+ .st_name = 29,
+ .st_value = (Elf32_Addr)(uintptr_t)apkenv_android_dladdr,
+ .st_info = STB_GLOBAL << 4,
+ .st_shndx = 1,
+ },
+#ifdef ANDROID_ARM_LINKER
+ {
+ .st_name = 36,
+ .st_value = (Elf32_Addr)(uintptr_t)apkenv_android_dl_unwind_find_exidx,
+ .st_info = STB_GLOBAL << 4,
+ .st_shndx = 1,
+ },
+#elif defined(ANDROID_X86_LINKER)
+ {
+ .st_name = 36,
+ .st_value = (Elf32_Addr)(uintptr_t)apkenv_android_dl_iterate_phdr,
+ .st_info = STB_GLOBAL << 4,
+ .st_shndx = 1,
+ },
+#endif
+ };
+ memcpy(apkenv_libdl_symtab, symtab, sizeof(symtab));
+}
diff --git a/src/linker/linker.c b/src/linker/linker.c
new file mode 100644
index 0000000..8f95472
--- /dev/null
+++ b/src/linker/linker.c
@@ -0,0 +1,2541 @@
+/*
+ * Copyright (C) 2008, 2009 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.
+ */
+
+#ifdef APKENV_DEBUG
+# define LINKER_DEBUG_PRINTF(...) PRINT(__VA_ARGS__)
+#else
+# define LINKER_DEBUG_PRINTF(...)
+#endif
+
+
+#include <linux/auxvec.h>
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dlfcn.h>
+#include <sys/stat.h>
+#include <assert.h>
+
+#include <pthread.h>
+
+#include <sys/mman.h>
+
+/* special private C library header - see Android.mk */
+#include "bionic_tls.h"
+
+#include "strlcpy.h"
+
+/* for apkenv_get_hooked_symbol */
+// #include "../compat/hooks.h"
+/* for create_wrapper */
+// #include "../debug/wrappers.h"
+
+#include "linker.h"
+#include "linker_debug.h"
+#include "linker_environ.h"
+#include "linker_format.h"
+
+#define ALLOW_SYMBOLS_FROM_MAIN 1
+#define SO_MAX 128
+
+/* Assume average path length of 64 and max 8 paths */
+#define LDPATH_BUFSIZE 512
+#define LDPATH_MAX 8
+
+#define LDPRELOAD_BUFSIZE 512
+#define LDPRELOAD_MAX 8
+
+/* >>> IMPORTANT NOTE - READ ME BEFORE MODIFYING <<<
+ *
+ * Do NOT use malloc() and friends or pthread_*() code here.
+ * Don't use printf() either; it's caused mysterious memory
+ * corruption in the past.
+ * The linker runs before we bring up libc and it's easiest
+ * to make sure it does not depend on any complex libc features
+ *
+ * open issues / todo:
+ *
+ * - are we doing everything we should for ARM_COPY relocations?
+ * - cleaner error reporting
+ * - after linking, set as much stuff as possible to READONLY
+ * and NOEXEC
+ * - linker hardcodes PAGE_SIZE and PAGE_MASK because the kernel
+ * headers provide versions that are negative...
+ * - allocate space for soinfo structs dynamically instead of
+ * having a hard limit (64)
+*/
+
+
+static int apkenv_link_image(soinfo *si, unsigned wr_offset);
+
+static int apkenv_socount = 0;
+static soinfo apkenv_sopool[SO_MAX];
+static soinfo *apkenv_freelist = NULL;
+static soinfo *apkenv_solist = &apkenv_libdl_info;
+static soinfo *apkenv_sonext = &apkenv_libdl_info;
+#if ALLOW_SYMBOLS_FROM_MAIN
+static soinfo *apkenv_somain; /* main process, always the one after apkenv_libdl_info */
+#endif
+
+
+static inline int apkenv_validate_soinfo(soinfo *si)
+{
+ return (si >= apkenv_sopool && si < apkenv_sopool + SO_MAX) ||
+ si == &apkenv_libdl_info;
+}
+
+static char apkenv_ldpaths_buf[LDPATH_BUFSIZE];
+static const char *apkenv_ldpaths[LDPATH_MAX + 1];
+
+static char apkenv_ldpreloads_buf[LDPRELOAD_BUFSIZE];
+static const char *apkenv_ldpreload_names[LDPRELOAD_MAX + 1];
+
+static soinfo *apkenv_preloads[LDPRELOAD_MAX + 1];
+
+#if LINKER_DEBUG
+int apkenv_debug_verbosity = 5;
+#endif
+
+static int apkenv_pid;
+
+/* This boolean is set if the program being loaded is setuid */
+static int apkenv_program_is_setuid;
+
+#if STATS
+struct _link_stats apkenv_linker_stats;
+#endif
+
+#if COUNT_PAGES
+unsigned apkenv_bitmask[4096];
+#endif
+
+#ifndef PT_ARM_EXIDX
+#define PT_ARM_EXIDX 0x70000001 /* .ARM.exidx segment */
+#endif
+
+static char apkenv_tmp_err_buf[768];
+static char apkenv___linker_dl_err_buf[768];
+#define DL_ERR(fmt, x...) \
+ do { \
+ format_buffer(apkenv___linker_dl_err_buf, sizeof(apkenv___linker_dl_err_buf), \
+ "%s[%d]: " fmt, __func__, __LINE__, ##x); \
+ ERROR(fmt "\n", ##x); \
+ } while(0)
+
+const char *apkenv_linker_get_error(void)
+{
+ return (const char *)&apkenv___linker_dl_err_buf[0];
+}
+
+enum {
+ WRAPPER_DYNHOOK,
+ WRAPPER_THUMB_INJECTION,
+ WRAPPER_UNHOOKED,
+ WRAPPER_ARM_INJECTION,
+};
+
+static void
+trace(const char *const symbol)
+{
+ printf("trace: %s\n", symbol);
+}
+
+__asm__(
+ "wrapper_start: nop\n"
+ "wrapper_symbol: pushl $0xFAFBFCFD\n"
+ "wrapper_trace: movl $0xFAFBFCFD, %eax\ncall *%eax\npop %eax\n"
+ "wrapper_call: movl $0xFAFBFCFD, %eax\njmp *%eax\n"
+ "wrapper_end: nop\n"
+);
+
+extern char wrapper_start, wrapper_symbol, wrapper_trace, wrapper_call, wrapper_end;
+
+void*
+create_wrapper(const char *const symbol, void *function, int wrapper_type)
+{
+ const size_t sz = &wrapper_end - &wrapper_start;
+ unsigned char *fun = mmap(NULL, sz, PROT_READ | PROT_WRITE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
+ assert(fun != MAP_FAILED);
+ memcpy(fun, &wrapper_start, sz);
+ memcpy(fun + (&wrapper_symbol - &wrapper_start) + 1, &symbol, sizeof(symbol));
+ memcpy(fun + (&wrapper_trace - &wrapper_start) + 1, (uintptr_t[]){ (uintptr_t)trace }, sizeof(uintptr_t));
+ memcpy(fun + (&wrapper_call - &wrapper_start) + 1, &function, sizeof(function));
+ mprotect(fun, sz, PROT_READ | PROT_EXEC);
+ return fun;
+}
+
+/*
+ * This function is an empty stub where GDB locates a breakpoint to get notified
+ * about linker activity.
+ */
+//extern void __attribute__((noinline)) rtld_db_dlactivity(void);
+
+//static struct r_debug _r_debug = {1, NULL, &rtld_db_dlactivity,
+// RT_CONSISTENT, 0};
+/* apkenv */
+#define rtld_db_dlactivity() ((void (*)(void))_r_debug.r_brk)()
+
+static struct link_map *apkenv_r_debug_head, *apkenv_r_debug_tail;
+
+static pthread_mutex_t apkenv__r_debug_lock = PTHREAD_MUTEX_INITIALIZER;
+
+static void apkenv_insert_soinfo_into_debug_map(soinfo * info)
+{
+ struct link_map * map;
+
+ /* Copy the necessary fields into the debug structure.
+ */
+ map = &(info->linkmap);
+ map->l_addr = info->base;
+ map->l_name = info->fullpath;
+ map->l_ld = (void *)info->dynamic;
+
+ /* Stick the new library at the end of the list.
+ * gdb tends to care more about libc than it does
+ * about leaf libraries, and ordering it this way
+ * reduces the back-and-forth over the wire.
+ */
+ if (apkenv_r_debug_tail) {
+ apkenv_r_debug_tail->l_next = map;
+ map->l_prev = apkenv_r_debug_tail;
+ map->l_next = 0;
+ } else {
+ /* apkenv: for sending to gdb */
+ apkenv_r_debug_head = map;
+ map->l_prev = 0;
+ map->l_next = 0;
+ }
+ apkenv_r_debug_tail = map;
+}
+
+static void apkenv_remove_soinfo_from_debug_map(soinfo * info)
+{
+ struct link_map * map = &(info->linkmap);
+
+ if (apkenv_r_debug_tail == map)
+ apkenv_r_debug_tail = map->l_prev;
+
+ if (map->l_prev) map->l_prev->l_next = map->l_next;
+ if (map->l_next) map->l_next->l_prev = map->l_prev;
+}
+
+void apkenv_notify_gdb_of_libraries(void);
+
+static void apkenv_notify_gdb_of_load(soinfo * info)
+{
+ if (info->flags & FLAG_EXE) {
+ // GDB already knows about the main executable
+ return;
+ }
+
+ pthread_mutex_lock(&apkenv__r_debug_lock);
+
+ _r_debug.r_state = RT_ADD;
+ rtld_db_dlactivity();
+
+ apkenv_insert_soinfo_into_debug_map(info);
+
+ _r_debug.r_state = RT_CONSISTENT;
+ rtld_db_dlactivity();
+
+ apkenv_notify_gdb_of_libraries();
+ pthread_mutex_unlock(&apkenv__r_debug_lock);
+}
+
+static void apkenv_notify_gdb_of_unload(soinfo * info)
+{
+ if (info->flags & FLAG_EXE) {
+ // GDB already knows about the main executable
+ return;
+ }
+
+ pthread_mutex_lock(&apkenv__r_debug_lock);
+
+ _r_debug.r_state = RT_DELETE;
+ rtld_db_dlactivity();
+
+ apkenv_remove_soinfo_from_debug_map(info);
+
+ _r_debug.r_state = RT_CONSISTENT;
+ rtld_db_dlactivity();
+
+ apkenv_notify_gdb_of_libraries();
+ pthread_mutex_unlock(&apkenv__r_debug_lock);
+}
+
+void apkenv_notify_gdb_of_libraries(void)
+{
+ struct link_map *tmap = _r_debug.r_map;
+ while (tmap->l_next != NULL)
+ tmap = tmap->l_next;
+
+ _r_debug.r_state = RT_ADD;
+ rtld_db_dlactivity();
+
+ /* append android libs before notifying gdb */
+ tmap->l_next = apkenv_r_debug_head;
+ apkenv_r_debug_head->l_prev = tmap;
+
+ _r_debug.r_state = RT_CONSISTENT;
+ rtld_db_dlactivity();
+
+ /* restore so that ld-linux doesn't freak out */
+ tmap->l_next = NULL;
+}
+
+static soinfo *apkenv_alloc_info(const char *name)
+{
+ soinfo *si;
+
+ if(strlen(name) >= SOINFO_NAME_LEN) {
+ DL_ERR("%5d library name %s too long", apkenv_pid, name);
+ return NULL;
+ }
+
+ /* The apkenv_freelist is populated when we call apkenv_free_info(), which in turn is
+ done only by dlclose(), which is not likely to be used.
+ */
+ if (!apkenv_freelist) {
+ if(apkenv_socount == SO_MAX) {
+ DL_ERR("%5d too many libraries when loading %s", apkenv_pid, name);
+ return NULL;
+ }
+ apkenv_freelist = apkenv_sopool + apkenv_socount++;
+ apkenv_freelist->next = NULL;
+ }
+
+ si = apkenv_freelist;
+ apkenv_freelist = apkenv_freelist->next;
+
+ /* Make sure we get a clean block of soinfo */
+ memset(si, 0, sizeof(soinfo));
+ apkenv_strlcpy((char*) si->name, name, sizeof(si->name));
+ apkenv_sonext->next = si;
+ si->next = NULL;
+ si->refcount = 0;
+ apkenv_sonext = si;
+
+ TRACE("%5d name %s: allocated soinfo @ %p\n", apkenv_pid, name, si);
+ return si;
+}
+
+static void apkenv_free_info(soinfo *si)
+{
+ soinfo *prev = NULL, *trav;
+
+ TRACE("%5d name %s: freeing soinfo @ %p\n", apkenv_pid, si->name, si);
+
+ for(trav = apkenv_solist; trav != NULL; trav = trav->next){
+ if (trav == si)
+ break;
+ prev = trav;
+ }
+ if (trav == NULL) {
+ /* si was not ni apkenv_solist */
+ DL_ERR("%5d name %s is not in apkenv_solist!", apkenv_pid, si->name);
+ return;
+ }
+
+ /* prev will never be NULL, because the first entry in apkenv_solist is
+ always the static apkenv_libdl_info.
+ */
+ prev->next = si->next;
+ if (si == apkenv_sonext) apkenv_sonext = prev;
+ si->next = apkenv_freelist;
+ apkenv_freelist = si;
+}
+
+static const char *apkenv_addr_to_name(unsigned addr)
+{
+ soinfo *si;
+
+ for(si = apkenv_solist; si != 0; si = si->next){
+ if((addr >= si->base) && (addr < (si->base + si->size))) {
+ return si->name;
+ }
+ }
+
+ return "";
+}
+
+/* For a given PC, find the .so that it belongs to.
+ * Returns the base address of the .ARM.exidx section
+ * for that .so, and the number of 8-byte entries
+ * in that section (via *pcount).
+ *
+ * Intended to be called by libc's __gnu_Unwind_Find_exidx().
+ *
+ * This function is exposed via dlfcn.c and libdl.so.
+ */
+#ifdef ANDROID_ARM_LINKER
+_Unwind_Ptr apkenv_android_dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount)
+{
+ soinfo *si;
+ unsigned addr = (unsigned)pc;
+
+ for (si = apkenv_solist; si != 0; si = si->next){
+ if ((addr >= si->base) && (addr < (si->base + si->size))) {
+ *pcount = si->ARM_exidx_count;
+ return (_Unwind_Ptr)(si->base + (unsigned long)si->ARM_exidx);
+ }
+ }
+ *pcount = 0;
+ return NULL;
+}
+#elif defined(ANDROID_X86_LINKER)
+/* Here, we only have to provide a callback to iterate across all the
+ * loaded libraries. gcc_eh does the rest. */
+int
+apkenv_android_dl_iterate_phdr(int (*cb)(struct dl_phdr_info *info, size_t size, void *data),
+ void *data)
+{
+ soinfo *si;
+ struct dl_phdr_info dl_info;
+ int rv = 0;
+
+ for (si = apkenv_solist; si != NULL; si = si->next) {
+ dl_info.dlpi_addr = si->linkmap.l_addr;
+ dl_info.dlpi_name = si->linkmap.l_name;
+ dl_info.dlpi_phdr = (void*)si->phdr;
+ dl_info.dlpi_phnum = si->phnum;
+ rv = cb(&dl_info, sizeof (struct dl_phdr_info), data);
+ if (rv != 0)
+ break;
+ }
+ return rv;
+}
+#endif
+
+static Elf32_Sym *apkenv__elf_lookup(soinfo *si, unsigned hash, const char *name)
+{
+ Elf32_Sym *s;
+ Elf32_Sym *symtab = si->symtab;
+ const char *strtab = si->strtab;
+ unsigned n;
+
+ TRACE_TYPE(LOOKUP, "%5d SEARCH %s in %s@0x%08x %08x %d\n", apkenv_pid,
+ name, si->name, si->base, hash, hash % si->nbucket);
+ if (si->nbucket == 0) {
+ return NULL;
+ }
+ n = hash % si->nbucket;
+
+ for(n = si->bucket[hash % si->nbucket]; n != 0; n = si->chain[n]){
+ s = symtab + n;
+ if(strcmp(strtab + s->st_name, name)) continue;
+
+ /* only concern ourselves with global and weak symbol definitions */
+ switch(ELF32_ST_BIND(s->st_info)){
+ case STB_GLOBAL:
+ case STB_WEAK:
+ /* no section == undefined */
+ if(s->st_shndx == 0) continue;
+
+ TRACE_TYPE(LOOKUP, "%5d FOUND %s in %s (%08x) %d\n", apkenv_pid,
+ name, si->name, s->st_value, s->st_size);
+ return s;
+ }
+ }
+
+ return NULL;
+}
+
+static unsigned apkenv_elfhash(const char *_name)
+{
+ const unsigned char *name = (const unsigned char *) _name;
+ unsigned h = 0, g;
+
+ while(*name) {
+ h = (h << 4) + *name++;
+ g = h & 0xf0000000;
+ h ^= g;
+ h ^= g >> 24;
+ }
+ return h;
+}
+
+const char *apkenv_last_library_used = NULL;
+
+static Elf32_Sym *
+apkenv__do_lookup(soinfo *si, const char *name, unsigned *base)
+{
+ unsigned elf_hash = apkenv_elfhash(name);
+ Elf32_Sym *s;
+ unsigned *d;
+ soinfo *lsi = si;
+ int i;
+
+ /* Look for symbols in the local scope (the object who is
+ * searching). This happens with C++ templates on i386 for some
+ * reason.
+ *
+ * Notes on weak symbols:
+ * The ELF specs are ambigious about treatment of weak definitions in
+ * dynamic linking. Some systems return the first definition found
+ * and some the first non-weak definition. This is system dependent.
+ * Here we return the first definition found for simplicity. */
+
+ s = apkenv__elf_lookup(si, elf_hash, name);
+ if(s != NULL)
+ goto done;
+
+ /* Next, look for it in the apkenv_preloads list */
+ for(i = 0; apkenv_preloads[i] != NULL; i++) {
+ lsi = apkenv_preloads[i];
+ s = apkenv__elf_lookup(lsi, elf_hash, name);
+ if(s != NULL)
+ goto done;
+ }
+
+ for(d = si->dynamic; *d; d += 2) {
+ if(d[0] == DT_NEEDED){
+ lsi = (soinfo *)d[1];
+ if (!apkenv_validate_soinfo(lsi)) {
+ DL_ERR("%5d bad DT_NEEDED pointer in %s",
+ apkenv_pid, si->name);
+ return NULL;
+ }
+
+ DEBUG("%5d %s: looking up %s in %s\n",
+ apkenv_pid, si->name, name, lsi->name);
+ s = apkenv__elf_lookup(lsi, elf_hash, name);
+ if ((s != NULL) && (s->st_shndx != SHN_UNDEF))
+ goto done;
+ }
+ }
+
+#if ALLOW_SYMBOLS_FROM_MAIN
+ /* If we are resolving relocations while dlopen()ing a library, it's OK for
+ * the library to resolve a symbol that's defined in the executable itself,
+ * although this is rare and is generally a bad idea.
+ */
+ if (apkenv_somain) {
+ lsi = apkenv_somain;
+ DEBUG("%5d %s: looking up %s in executable %s\n",
+ apkenv_pid, si->name, name, lsi->name);
+ s = apkenv__elf_lookup(lsi, elf_hash, name);
+ }
+#endif
+
+done:
+ if(s != NULL) {
+ TRACE_TYPE(LOOKUP, "%5d si %s sym %s s->st_value = 0x%08x, "
+ "found in %s, base = 0x%08x\n",
+ apkenv_pid, si->name, name, s->st_value, lsi->name, lsi->base);
+ apkenv_last_library_used = lsi->name;
+ *base = lsi->base;
+ return s;
+ }
+
+ return NULL;
+}
+
+/* This is used by dl_sym(). It performs symbol lookup only within the
+ specified soinfo object and not in any of its dependencies.
+ */
+Elf32_Sym *apkenv_lookup_in_library(soinfo *si, const char *name)
+{
+ return apkenv__elf_lookup(si, apkenv_elfhash(name), name);
+}
+
+/* This is used by dl_sym(). It performs a global symbol lookup.
+ */
+Elf32_Sym *apkenv_lookup(const char *name, soinfo **found, soinfo *start)
+{
+ unsigned elf_hash = apkenv_elfhash(name);
+ Elf32_Sym *s = NULL;
+ soinfo *si;
+
+ if(start == NULL) {
+ start = apkenv_solist;
+ }
+
+ for(si = start; (s == NULL) && (si != NULL); si = si->next)
+ {
+ if(si->flags & FLAG_ERROR)
+ continue;
+ s = apkenv__elf_lookup(si, elf_hash, name);
+ if (s != NULL) {
+ *found = si;
+ break;
+ }
+ }
+
+ if(s != NULL) {
+ TRACE_TYPE(LOOKUP, "%5d %s s->st_value = 0x%08x, "
+ "si->base = 0x%08x\n", apkenv_pid, name, s->st_value, si->base);
+ return s;
+ }
+
+ return NULL;
+}
+
+soinfo *apkenv_find_containing_library(const void *addr)
+{
+ soinfo *si;
+
+ for(si = apkenv_solist; si != NULL; si = si->next)
+ {
+ if((unsigned)addr >= si->base && (unsigned)addr - si->base < si->size) {
+ return si;
+ }
+ }
+
+ return NULL;
+}
+
+Elf32_Sym *apkenv_find_containing_symbol(const void *addr, soinfo *si)
+{
+ unsigned int i;
+ unsigned soaddr = (unsigned)addr - si->base;
+
+ /* Search the library's symbol table for any defined symbol which
+ * contains this address */
+ for(i=0; i<si->nchain; i++) {
+ Elf32_Sym *sym = &si->symtab[i];
+
+ if(sym->st_shndx != SHN_UNDEF &&
+ soaddr >= sym->st_value &&
+ soaddr < sym->st_value + sym->st_size) {
+ return sym;
+ }
+ }
+
+ return NULL;
+}
+
+#if 0
+static void dump(soinfo *si)
+{
+ Elf32_Sym *s = si->symtab;
+ unsigned n;
+
+ for(n = 0; n < si->nchain; n++) {
+ TRACE("%5d %04d> %08x: %02x %04x %08x %08x %s\n", apkenv_pid, n, s,
+ s->st_info, s->st_shndx, s->st_value, s->st_size,
+ si->strtab + s->st_name);
+ s++;
+ }
+}
+#endif
+
+#define SOPATH_MAX 8
+
+static const char *apkenv_sopaths[SOPATH_MAX + 1] = {
+ "/vendor/lib",
+ "/system/lib",
+ // APKENV_PREFIX "/lib/" APKENV_TARGET "/bionic/",
+#ifdef APKENV_LOCAL_BIONIC_PATH
+ APKENV_LOCAL_BIONIC_PATH,
+#endif
+};
+
+int apkenv_add_sopath(const char *path)
+{
+ int i;
+ for (i = 0; i < SOPATH_MAX; i++) {
+ if (apkenv_sopaths[i] == NULL) {
+ apkenv_sopaths[i] = path;
+ return 0;
+ }
+
+ if (strcmp(path, apkenv_sopaths[i]) == 0)
+ return 0;
+ }
+
+ ERROR("too many apkenv_sopaths\n");
+ return -1;
+}
+
+static int apkenv__open_lib(const char *name)
+{
+ int fd;
+ struct stat filestat;
+
+ if ((stat(name, &filestat) >= 0) && S_ISREG(filestat.st_mode)) {
+ if ((fd = open(name, O_RDONLY)) >= 0)
+ return fd;
+ }
+
+ return -1;
+}
+
+static int apkenv_open_library(const char *name, char *fullpath)
+{
+ int fd;
+ char buf[512];
+ const char **path;
+ int n;
+
+ TRACE("[ %5d opening %s ]\n", apkenv_pid, name);
+
+ if(name == 0) return -1;
+ if(strlen(name) > 256) return -1;
+
+ strcpy(fullpath, name);
+
+ if ((name[0] == '/') && ((fd = apkenv__open_lib(name)) >= 0))
+ return fd;
+
+ if (((fd = apkenv__open_lib(name)) >= 0))
+ return fd;
+
+ for (path = apkenv_ldpaths; *path; path++) {
+ n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
+ if (n < 0 || n >= (int)sizeof(buf)) {
+ WARN("Ignoring very long library path: %s/%s\n", *path, name);
+ continue;
+ }
+ if ((fd = apkenv__open_lib(buf)) >= 0) {
+ strcpy(fullpath, buf);
+ return fd;
+ }
+ }
+ for (path = apkenv_sopaths; *path; path++) {
+ n = format_buffer(buf, sizeof(buf), "%s/%s", *path, name);
+ if (n < 0 || n >= (int)sizeof(buf)) {
+ WARN("Ignoring very long library path: %s/%s\n", *path, name);
+ continue;
+ }
+ if ((fd = apkenv__open_lib(buf)) >= 0) {
+ strcpy(fullpath, buf);
+ return fd;
+ }
+ }
+
+ return -1;
+}
+
+typedef struct {
+ long mmap_addr;
+ char tag[4]; /* 'P', 'R', 'E', ' ' */
+} prelink_info_t;
+
+/* Returns the requested base address if the library is prelinked,
+ * and 0 otherwise. */
+static unsigned long
+apkenv_is_prelinked(int fd, const char *name)
+{
+ off_t sz;
+ prelink_info_t info;
+
+ sz = lseek(fd, -sizeof(prelink_info_t), SEEK_END);
+ if (sz < 0) {
+ DL_ERR("lseek() failed!");
+ return 0;
+ }
+
+ if (read(fd, &info, sizeof(info)) != sizeof(info)) {
+ WARN("Could not read prelink_info_t structure for `%s`\n", name);
+ return 0;
+ }
+
+ if (strncmp(info.tag, "PRE ", 4)) {
+ WARN("`%s` is not a prelinked library\n", name);
+ return 0;
+ }
+
+ return (unsigned long)info.mmap_addr;
+}
+
+/* apkenv_verify_elf_object
+ * Verifies if the object @ base is a valid ELF object
+ *
+ * Args:
+ *
+ * Returns:
+ * 0 on success
+ * -1 if no valid ELF object is found @ base.
+ */
+static int
+apkenv_verify_elf_object(void *base, const char *name)
+{
+ Elf32_Ehdr *hdr = (Elf32_Ehdr *) base;
+
+ if (hdr->e_ident[EI_MAG0] != ELFMAG0) return -1;
+ if (hdr->e_ident[EI_MAG1] != ELFMAG1) return -1;
+ if (hdr->e_ident[EI_MAG2] != ELFMAG2) return -1;
+ if (hdr->e_ident[EI_MAG3] != ELFMAG3) return -1;
+
+ /* TODO: Should we verify anything else in the header? */
+#ifdef ANDROID_ARM_LINKER
+ if (hdr->e_machine != EM_ARM) return -1;
+#elif defined(ANDROID_X86_LINKER)
+ if (hdr->e_machine != EM_386) return -1;
+#endif
+ return 0;
+}
+
+
+/* apkenv_get_lib_extents
+ * Retrieves the base (*base) address where the ELF object should be
+ * mapped and its overall memory size (*total_sz).
+ *
+ * Args:
+ * fd: Opened file descriptor for the library
+ * name: The name of the library
+ * _hdr: Pointer to the header page of the library
+ * total_sz: Total size of the memory that should be allocated for
+ * this library
+ *
+ * Returns:
+ * -1 if there was an error while trying to get the lib extents.
+ * The possible reasons are:
+ * - Could not determine if the library was prelinked.
+ * - The library provided is not a valid ELF object
+ * 0 if the library did not request a specific base offset (normal
+ * for non-prelinked libs)
+ * > 0 if the library requests a specific address to be mapped to.
+ * This indicates a pre-linked library.
+ */
+static unsigned
+apkenv_get_lib_extents(int fd, const char *name, void *__hdr, unsigned *total_sz)
+{
+ unsigned req_base;
+ unsigned min_vaddr = 0xffffffff;
+ unsigned max_vaddr = 0;
+ unsigned char *_hdr = (unsigned char *)__hdr;
+ Elf32_Ehdr *ehdr = (Elf32_Ehdr *)_hdr;
+ Elf32_Phdr *phdr;
+ int cnt;
+
+ TRACE("[ %5d Computing extents for '%s'. ]\n", apkenv_pid, name);
+ if (apkenv_verify_elf_object(_hdr, name) < 0) {
+ DL_ERR("%5d - %s is not a valid ELF object", apkenv_pid, name);
+ return (unsigned)-1;
+ }
+
+ req_base = (unsigned) apkenv_is_prelinked(fd, name);
+ if (req_base == (unsigned)-1)
+ return -1;
+ else if (req_base != 0) {
+ TRACE("[ %5d - Prelinked library '%s' requesting base @ 0x%08x ]\n",
+ apkenv_pid, name, req_base);
+ } else {
+ TRACE("[ %5d - Non-prelinked library '%s' found. ]\n", apkenv_pid, name);
+ }
+
+ phdr = (Elf32_Phdr *)(_hdr + ehdr->e_phoff);
+
+ /* find the min/max p_vaddrs from all the PT_LOAD segments so we can
+ * get the range. */
+ for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
+ if (phdr->p_type == PT_LOAD) {
+ if ((phdr->p_vaddr + phdr->p_memsz) > max_vaddr)
+ max_vaddr = phdr->p_vaddr + phdr->p_memsz;
+ if (phdr->p_vaddr < min_vaddr)
+ min_vaddr = phdr->p_vaddr;
+ }
+ }
+
+ if ((min_vaddr == 0xffffffff) && (max_vaddr == 0)) {
+ DL_ERR("%5d - No loadable segments found in %s.", apkenv_pid, name);
+ return (unsigned)-1;
+ }
+
+ /* truncate min_vaddr down to page boundary */
+ min_vaddr &= ~PAGE_MASK;
+
+ /* round max_vaddr up to the next page */
+ max_vaddr = (max_vaddr + PAGE_SIZE - 1) & ~PAGE_MASK;
+
+ *total_sz = (max_vaddr - min_vaddr);
+ return (unsigned)req_base;
+}
+
+/* apkenv_reserve_mem_region
+ *
+ * This function reserves a chunk of memory to be used for mapping in
+ * a prelinked shared library. We reserve the entire memory region here, and
+ * then the rest of the linker will relocate the individual loadable
+ * segments into the correct locations within this memory range.
+ *
+ * Args:
+ * si->base: The requested base of the allocation.
+ * si->size: The size of the allocation.
+ *
+ * Returns:
+ * -1 on failure, and 0 on success. On success, si->base will contain
+ * the virtual address at which the library will be mapped.
+ */
+
+static int apkenv_reserve_mem_region(soinfo *si)
+{
+ void *base = mmap((void *)si->base, si->size, PROT_NONE,
+ MAP_FIXED | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if (base == MAP_FAILED) {
+ DL_ERR("%5d can NOT map (%sprelinked) library '%s' at 0x%08x "
+ "as requested, will try general pool: %d (%s)",
+ apkenv_pid, (si->base ? "" : "non-"), si->name, si->base,
+ errno, strerror(errno));
+ return -1;
+ } else if (base != (void *)si->base) {
+ DL_ERR("OOPS: %5d %sprelinked library '%s' mapped at 0x%08x, "
+ "not at 0x%08x", apkenv_pid, (si->base ? "" : "non-"),
+ si->name, (unsigned)base, si->base);
+ munmap(base, si->size);
+ return -1;
+ }
+ return 0;
+}
+
+static int apkenv_alloc_mem_region(soinfo *si)
+{
+ if (si->base) {
+ /* Attempt to mmap a prelinked library. */
+ return apkenv_reserve_mem_region(si);
+ }
+
+ /* This is not a prelinked library, so we use the kernel's default
+ allocator.
+ */
+
+ void *base = mmap(NULL, si->size, PROT_NONE,
+ MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
+ if (base == MAP_FAILED) {
+ DL_ERR("%5d mmap of library '%s' failed: %d (%s)\n",
+ apkenv_pid, si->name,
+ errno, strerror(errno));
+ goto err;
+ }
+ si->base = (unsigned) base;
+ PRINT("%5d mapped library '%s' to %08x via kernel allocator.\n",
+ apkenv_pid, si->name, si->base);
+ return 0;
+
+err:
+ DL_ERR("OOPS: %5d cannot map library '%s'. no vspace available.",
+ apkenv_pid, si->name);
+ return -1;
+}
+
+#define MAYBE_MAP_FLAG(x,from,to) (((x) & (from)) ? (to) : 0)
+#define PFLAGS_TO_PROT(x) (MAYBE_MAP_FLAG((x), PF_X, PROT_EXEC) | \
+ MAYBE_MAP_FLAG((x), PF_R, PROT_READ) | \
+ MAYBE_MAP_FLAG((x), PF_W, PROT_WRITE))
+/* apkenv_load_segments
+ *
+ * This function loads all the loadable (PT_LOAD) segments into memory
+ * at their appropriate memory offsets off the base address.
+ *
+ * Args:
+ * fd: Open file descriptor to the library to load.
+ * header: Pointer to a header page that contains the ELF header.
+ * This is needed since we haven't mapped in the real file yet.
+ * si: ptr to soinfo struct describing the shared object.
+ *
+ * Returns:
+ * 0 on success, -1 on failure.
+ */
+static int
+apkenv_load_segments(int fd, void *header, soinfo *si)
+{
+ Elf32_Ehdr *ehdr = (Elf32_Ehdr *)header;
+ Elf32_Phdr *phdr = (Elf32_Phdr *)((unsigned char *)header + ehdr->e_phoff);
+ Elf32_Addr base = (Elf32_Addr) si->base;
+ int cnt;
+ unsigned len;
+ Elf32_Addr tmp;
+ unsigned char *pbase;
+ unsigned char *extra_base;
+ unsigned extra_len;
+ unsigned total_sz = 0;
+
+ si->wrprotect_start = 0xffffffff;
+ si->wrprotect_end = 0;
+
+ TRACE("[ %5d - Begin loading segments for '%s' @ 0x%08x ]\n",
+ apkenv_pid, si->name, (unsigned)si->base);
+ /* Now go through all the PT_LOAD segments and map them into memory
+ * at the appropriate locations. */
+ for (cnt = 0; cnt < ehdr->e_phnum; ++cnt, ++phdr) {
+ if (phdr->p_type == PT_LOAD) {
+ DEBUG_DUMP_PHDR(phdr, "PT_LOAD", apkenv_pid);
+ /* we want to map in the segment on a page boundary */
+ tmp = base + (phdr->p_vaddr & (~PAGE_MASK));
+ /* add the # of bytes we masked off above to the total length. */
+ len = phdr->p_filesz + (phdr->p_vaddr & PAGE_MASK);
+
+ TRACE("[ %d - Trying to load segment from '%s' @ 0x%08x "
+ "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x ]\n", apkenv_pid, si->name,
+ (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
+ pbase = mmap((void *)tmp, len, PFLAGS_TO_PROT(phdr->p_flags),
+ MAP_PRIVATE | MAP_FIXED, fd,
+ phdr->p_offset & (~PAGE_MASK));
+ if (pbase == MAP_FAILED) {
+ DL_ERR("%d failed to map segment from '%s' @ 0x%08x (0x%08x). "
+ "p_vaddr=0x%08x p_offset=0x%08x", apkenv_pid, si->name,
+ (unsigned)tmp, len, phdr->p_vaddr, phdr->p_offset);
+ goto fail;
+ }
+
+ /* If 'len' didn't end on page boundary, and it's a writable
+ * segment, zero-fill the rest. */
+ if ((len & PAGE_MASK) && (phdr->p_flags & PF_W))
+ memset((void *)(pbase + len), 0, PAGE_SIZE - (len & PAGE_MASK));
+
+ /* Check to see if we need to extend the map for this segment to
+ * cover the diff between filesz and memsz (i.e. for bss).
+ *
+ * base _+---------------------+ page boundary
+ * . .
+ * | |
+ * . .
+ * pbase _+---------------------+ page boundary
+ * | |
+ * . .
+ * base + p_vaddr _| |
+ * . \ \ .
+ * . | filesz | .
+ * pbase + len _| / | |
+ * <0 pad> . . .
+ * extra_base _+------------|--------+ page boundary
+ * / . . .
+ * | . . .
+ * | +------------|--------+ page boundary
+ * extra_len-> | | | |
+ * | . | memsz .
+ * | . | .
+ * \ _| / |
+ * . .
+ * | |
+ * _+---------------------+ page boundary
+ */
+ tmp = (Elf32_Addr)(((unsigned)pbase + len + PAGE_SIZE - 1) &
+ (~PAGE_MASK));
+ if (tmp < (base + phdr->p_vaddr + phdr->p_memsz)) {
+ extra_len = base + phdr->p_vaddr + phdr->p_memsz - tmp;
+ TRACE("[ %5d - Need to extend segment from '%s' @ 0x%08x "
+ "(0x%08x) ]\n", apkenv_pid, si->name, (unsigned)tmp, extra_len);
+ /* map in the extra page(s) as anonymous into the range.
+ * This is probably not necessary as we already mapped in
+ * the entire region previously, but we just want to be
+ * sure. This will also set the right flags on the region
+ * (though we can probably accomplish the same thing with
+ * mprotect).
+ */
+ extra_base = mmap((void *)tmp, extra_len,
+ PFLAGS_TO_PROT(phdr->p_flags),
+ MAP_PRIVATE | MAP_FIXED | MAP_ANONYMOUS,
+ -1, 0);
+ if (extra_base == MAP_FAILED) {
+ DL_ERR("[ %5d - failed to extend segment from '%s' @ 0x%08x"
+ " (0x%08x) ]", apkenv_pid, si->name, (unsigned)tmp,
+ extra_len);
+ goto fail;
+ }
+ /* TODO: Check if we need to memset-0 this region.
+ * Anonymous mappings are zero-filled copy-on-writes, so we
+ * shouldn't need to. */
+ TRACE("[ %5d - Segment from '%s' extended @ 0x%08x "
+ "(0x%08x)\n", apkenv_pid, si->name, (unsigned)extra_base,
+ extra_len);
+ }
+ /* set the len here to show the full extent of the segment we
+ * just loaded, mostly for debugging */
+ len = (((unsigned)base + phdr->p_vaddr + phdr->p_memsz +
+ PAGE_SIZE - 1) & (~PAGE_MASK)) - (unsigned)pbase;
+ TRACE("[ %5d - Successfully loaded segment from '%s' @ 0x%08x "
+ "(0x%08x). p_vaddr=0x%08x p_offset=0x%08x\n", apkenv_pid, si->name,
+ (unsigned)pbase, len, phdr->p_vaddr, phdr->p_offset);
+ total_sz += len;
+ /* Make the section writable just in case we'll have to write to
+ * it during relocation (i.e. text segment). However, we will
+ * remember what range of addresses should be write protected.
+ *
+ */
+ if (!(phdr->p_flags & PF_W)) {
+ if ((unsigned)pbase < si->wrprotect_start)
+ si->wrprotect_start = (unsigned)pbase;
+ if (((unsigned)pbase + len) > si->wrprotect_end)
+ si->wrprotect_end = (unsigned)pbase + len;
+ mprotect(pbase, len,
+ PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
+ }
+ } else if (phdr->p_type == PT_DYNAMIC) {
+ DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", apkenv_pid);
+ /* this segment contains the dynamic linking information */
+ si->dynamic = (unsigned *)(base + phdr->p_vaddr);
+ } else if (phdr->p_type == PT_GNU_RELRO) {
+ if ((phdr->p_vaddr >= si->size)
+ || ((phdr->p_vaddr + phdr->p_memsz) > si->size)
+ || ((base + phdr->p_vaddr + phdr->p_memsz) < base)) {
+ DL_ERR("%d invalid GNU_RELRO in '%s' "
+ "p_vaddr=0x%08x p_memsz=0x%08x", apkenv_pid, si->name,
+ phdr->p_vaddr, phdr->p_memsz);
+ goto fail;
+ }
+ si->gnu_relro_start = (Elf32_Addr) (base + phdr->p_vaddr);
+ si->gnu_relro_len = (unsigned) phdr->p_memsz;
+ } else {
+#ifdef ANDROID_ARM_LINKER
+ if (phdr->p_type == PT_ARM_EXIDX) {
+ DEBUG_DUMP_PHDR(phdr, "PT_ARM_EXIDX", apkenv_pid);
+ /* exidx entries (used for stack unwinding) are 8 bytes each.
+ */
+ si->ARM_exidx = (unsigned *)phdr->p_vaddr;
+ si->ARM_exidx_count = phdr->p_memsz / 8;
+ }
+#endif
+ }
+
+ }
+
+ /* Sanity check */
+ if (total_sz > si->size) {
+ DL_ERR("%5d - Total length (0x%08x) of mapped segments from '%s' is "
+ "greater than what was allocated (0x%08x). THIS IS BAD!",
+ apkenv_pid, total_sz, si->name, si->size);
+ goto fail;
+ }
+
+ TRACE("[ %5d - Finish loading segments for '%s' @ 0x%08x. "
+ "Total memory footprint: 0x%08x bytes ]\n", apkenv_pid, si->name,
+ (unsigned)si->base, si->size);
+ return 0;
+
+fail:
+ /* We can just blindly unmap the entire region even though some things
+ * were mapped in originally with anonymous and others could have been
+ * been mapped in from the file before we failed. The kernel will unmap
+ * all the pages in the range, irrespective of how they got there.
+ */
+ munmap((void *)si->base, si->size);
+ si->flags |= FLAG_ERROR;
+ return -1;
+}
+
+/* TODO: Implement this to take care of the fact that Android ARM
+ * ELF objects shove everything into a single loadable segment that has the
+ * write bit set. wr_offset is then used to set non-(data|bss) pages to be
+ * non-writable.
+ */
+#if 0
+static unsigned
+get_wr_offset(int fd, const char *name, Elf32_Ehdr *ehdr)
+{
+ Elf32_Shdr *shdr_start;
+ Elf32_Shdr *shdr;
+ int shdr_sz = ehdr->e_shnum * sizeof(Elf32_Shdr);
+ int cnt;
+ unsigned wr_offset = 0xffffffff;
+
+ shdr_start = mmap(0, shdr_sz, PROT_READ, MAP_PRIVATE, fd,
+ ehdr->e_shoff & (~PAGE_MASK));
+ if (shdr_start == MAP_FAILED) {
+ WARN("%5d - Could not read section header info from '%s'. Will not "
+ "not be able to determine write-protect offset.\n", apkenv_pid, name);
+ return (unsigned)-1;
+ }
+
+ for(cnt = 0, shdr = shdr_start; cnt < ehdr->e_shnum; ++cnt, ++shdr) {
+ if ((shdr->sh_type != SHT_NULL) && (shdr->sh_flags & SHF_WRITE) &&
+ (shdr->sh_addr < wr_offset)) {
+ wr_offset = shdr->sh_addr;
+ }
+ }
+
+ munmap(shdr_start, shdr_sz);
+ return wr_offset;
+}
+#endif
+
+static soinfo *
+apkenv_load_library(const char *name)
+{
+ char fullpath[512];
+ int fd = apkenv_open_library(name, fullpath);
+ int cnt;
+ unsigned ext_sz;
+ unsigned req_base;
+ const char *bname;
+ soinfo *si = NULL;
+ Elf32_Ehdr *hdr;
+
+ if(fd == -1) {
+#if !LINKER_DEBUG
+ if (!is_lib_optional(name))
+#endif
+ DL_ERR("Library '%s' not found", name);
+ return NULL;
+ }
+
+ off_t end;
+ if ((end = lseek(fd, 0, SEEK_END)) < 0) {
+ DL_ERR("lseek() failed!");
+ goto fail;
+ }
+
+ uint8_t *bytes;
+ if (!(bytes = calloc(1, end))) {
+ DL_ERR("calloc() failed!");
+ goto fail;
+ }
+
+ /* We have to read the ELF header to figure out what to do with this image
+ */
+ if (lseek(fd, 0, SEEK_SET) < 0) {
+ DL_ERR("lseek() failed!");
+ goto fail;
+ }
+
+
+ if ((cnt = read(fd, bytes, end)) < 0) {
+ DL_ERR("read() failed!");
+ goto fail;
+ }
+
+ /* Parse the ELF header and get the size of the memory footprint for
+ * the library */
+ req_base = apkenv_get_lib_extents(fd, name, bytes, &ext_sz);
+ if (req_base == (unsigned)-1)
+ goto fail;
+ TRACE("[ %5d - '%s' (%s) wants base=0x%08x sz=0x%08x ]\n", apkenv_pid, name,
+ (req_base ? "prelinked" : "not pre-linked"), req_base, ext_sz);
+
+ /* Now configure the soinfo struct where we'll store all of our data
+ * for the ELF object. If the loading fails, we waste the entry, but
+ * same thing would happen if we failed during linking. Configuring the
+ * soinfo struct here is a lot more convenient.
+ */
+ bname = strrchr(name, '/');
+ si = apkenv_alloc_info(bname ? bname + 1 : name);
+ if (si == NULL)
+ goto fail;
+
+ /* apkenv */
+ strncpy(si->fullpath, fullpath, sizeof(si->fullpath));
+ si->fullpath[sizeof(si->fullpath) - 1] = 0;
+
+ /* Carve out a chunk of memory where we will map in the individual
+ * segments */
+ si->base = req_base;
+ si->size = ext_sz;
+ si->flags = 0;
+ si->entry = 0;
+ si->dynamic = (unsigned *)-1;
+ if (apkenv_alloc_mem_region(si) < 0)
+ goto fail;
+
+ TRACE("[ %5d allocated memory for %s @ %p (0x%08x) ]\n",
+ apkenv_pid, name, (void *)si->base, (unsigned) ext_sz);
+
+ /* Now actually load the library's segments into right places in memory */
+ if (apkenv_load_segments(fd, bytes, si) < 0) {
+ goto fail;
+ }
+
+ /* this might not be right. Technically, we don't even need this info
+ * once we go through 'apkenv_load_segments'. */
+ hdr = (Elf32_Ehdr *)si->base;
+ si->phdr = (Elf32_Phdr *)((unsigned char *)si->base + hdr->e_phoff);
+ si->phnum = hdr->e_phnum;
+ /**/
+
+ close(fd);
+ return si;
+
+fail:
+ if (si) apkenv_free_info(si);
+ close(fd);
+ return NULL;
+}
+
+static soinfo *
+apkenv_init_library(soinfo *si)
+{
+ unsigned wr_offset = 0xffffffff;
+
+ /* At this point we know that whatever is loaded @ base is a valid ELF
+ * shared library whose segments are properly mapped in. */
+ TRACE("[ %5d apkenv_init_library base=0x%08x sz=0x%08x name='%s') ]\n",
+ apkenv_pid, si->base, si->size, si->name);
+ if(apkenv_link_image(si, wr_offset)) {
+ /* We failed to link. However, we can only restore libbase
+ ** if no additional libraries have moved it since we updated it.
+ */
+ munmap((void *)si->base, si->size);
+ return NULL;
+ }
+
+ return si;
+}
+
+soinfo *apkenv_find_library(const char *name)
+{
+ soinfo *si;
+ const char *bname;
+
+#if ALLOW_SYMBOLS_FROM_MAIN
+ if (name == NULL)
+ return apkenv_somain;
+#else
+ if (name == NULL)
+ return NULL;
+#endif
+
+ bname = strrchr(name, '/');
+ bname = bname ? bname + 1 : name;
+
+ for(si = apkenv_solist; si != 0; si = si->next){
+ if(!strcmp(bname, si->name)) {
+ if(si->flags & FLAG_ERROR) {
+ DL_ERR("%5d '%s' failed to load previously", apkenv_pid, bname);
+ return NULL;
+ }
+ if(si->flags & FLAG_LINKED) return si;
+ DL_ERR("OOPS: %5d recursive link to '%s'", apkenv_pid, si->name);
+ return NULL;
+ }
+ }
+
+ TRACE("[ %5d '%s' has not been loaded yet. Locating...]\n", apkenv_pid, name);
+ si = apkenv_load_library(name);
+ if(si == NULL)
+ return NULL;
+ return apkenv_init_library(si);
+}
+
+/* TODO:
+ * notify gdb of unload
+ * for non-prelinked libraries, find a way to decrement libbase
+ */
+static void apkenv_call_destructors(soinfo *si);
+unsigned apkenv_unload_library(soinfo *si)
+{
+ unsigned *d;
+ if (si->refcount == 1) {
+ TRACE("%5d unloading '%s'\n", apkenv_pid, si->name);
+ apkenv_call_destructors(si);
+
+ /*
+ * Make sure that we undo the PT_GNU_RELRO protections we added
+ * in apkenv_link_image. This is needed to undo the DT_NEEDED hack below.
+ */
+ if ((si->gnu_relro_start != 0) && (si->gnu_relro_len != 0)) {
+ Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
+ unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
+ if (mprotect((void *) start, len, PROT_READ | PROT_WRITE) < 0)
+ DL_ERR("%5d %s: could not undo GNU_RELRO protections. "
+ "Expect a crash soon. errno=%d (%s)",
+ apkenv_pid, si->name, errno, strerror(errno));
+
+ }
+
+ for(d = si->dynamic; *d; d += 2) {
+ if(d[0] == DT_NEEDED){
+ soinfo *lsi = (soinfo *)d[1];
+
+ // The next line will segfault if the we don't undo the
+ // PT_GNU_RELRO protections (see comments above and in
+ // apkenv_link_image().
+ d[1] = 0;
+
+ if (apkenv_validate_soinfo(lsi)) {
+ TRACE("%5d %s needs to unload %s\n", apkenv_pid,
+ si->name, lsi->name);
+ apkenv_unload_library(lsi);
+ }
+ else
+ DL_ERR("%5d %s: could not unload dependent library",
+ apkenv_pid, si->name);
+ }
+ }
+
+ munmap((char *)si->base, si->size);
+ apkenv_notify_gdb_of_unload(si);
+ apkenv_free_info(si);
+ si->refcount = 0;
+ }
+ else {
+ si->refcount--;
+ PRINT("%5d not unloading '%s', decrementing refcount to %d\n",
+ apkenv_pid, si->name, si->refcount);
+ }
+ return si->refcount;
+}
+
+#define MIN(a,b) (((a)<(b))?(a):(b))
+
+/* TODO: don't use unsigned for addrs below. It works, but is not
+ * ideal. They should probably be either uint32_t, Elf32_Addr, or unsigned
+ * long.
+ */
+static int apkenv_reloc_library(soinfo *si, Elf32_Rel *rel, unsigned count)
+{
+ Elf32_Sym *symtab = si->symtab;
+ const char *strtab = si->strtab;
+ Elf32_Sym *s;
+ unsigned base;
+ Elf32_Rel *start = rel;
+ unsigned idx;
+
+ for (idx = 0; idx < count; ++idx) {
+ unsigned type = ELF32_R_TYPE(rel->r_info);
+ unsigned sym = ELF32_R_SYM(rel->r_info);
+ unsigned reloc = (unsigned)(rel->r_offset + si->base);
+ unsigned sym_addr = 0;
+ char *sym_name = NULL;
+ char wrap_sym_name[1024] = { 'b', 'i', 'o', 'n', 'i', 'c', '_' };
+
+ DEBUG("%5d Processing '%s' relocation at index %d\n", apkenv_pid,
+ si->name, idx);
+ if(sym != 0) {
+ sym_name = (char *)(strtab + symtab[sym].st_name);
+ memcpy(wrap_sym_name + 7, sym_name, MIN(sizeof(wrap_sym_name) - 7, strlen(sym_name)));
+ sym_addr = 0;
+ if ((sym_addr = dlsym(RTLD_DEFAULT, wrap_sym_name))) {
+ LINKER_DEBUG_PRINTF("%s hooked symbol %s to %x\n", si->name, wrap_sym_name, sym_addr);
+ } else if ((sym_addr = dlsym(RTLD_DEFAULT, sym_name))) {
+ LINKER_DEBUG_PRINTF("%s hooked symbol %s to %x\n", si->name, sym_name, sym_addr);
+ }
+#if 0
+ if ((sym_addr = (unsigned)apkenv_get_hooked_symbol(sym_name, 1)) != 0) {
+ LINKER_DEBUG_PRINTF("%s hooked symbol %s to %x\n", si->name, sym_name, sym_addr);
+ }
+#endif
+ else
+ {
+ s = apkenv__do_lookup(si, sym_name, &base);
+ }
+ if(sym_addr != 0)
+ {
+ sym_addr = (unsigned)create_wrapper(sym_name, (void*)sym_addr, WRAPPER_UNHOOKED);
+ } else
+ if(s == NULL) {
+ /* We only allow an undefined symbol if this is a weak
+ reference.. */
+ s = &symtab[sym];
+ if (ELF32_ST_BIND(s->st_info) != STB_WEAK) {
+ DL_ERR("%5d cannot locate '%s'...\n", apkenv_pid, sym_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 nominial base address if the relocation
+ type is base-relative.
+ */
+
+ switch (type) {
+#if defined(ANDROID_ARM_LINKER)
+ case R_ARM_JUMP_SLOT:
+ case R_ARM_GLOB_DAT:
+ case R_ARM_ABS32:
+ case R_ARM_RELATIVE: /* Don't care. */
+ case R_ARM_NONE: /* Don't care. */
+#elif defined(ANDROID_X86_LINKER)
+ case R_386_JUMP_SLOT:
+ case R_386_GLOB_DAT:
+ case R_386_32:
+ case R_386_RELATIVE: /* Dont' care. */
+#endif /* ANDROID_*_LINKER */
+ /* 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;
+
+#if defined(ANDROID_X86_LINKER)
+ case R_386_PC32:
+ sym_addr = reloc;
+ break;
+#endif /* ANDROID_X86_LINKER */
+
+#if defined(ANDROID_ARM_LINKER)
+ case R_ARM_COPY:
+ /* Fall through. Can't really copy if weak symbol is
+ not found in run-time. */
+#endif /* ANDROID_ARM_LINKER */
+ default:
+ DL_ERR("%5d unknown weak reloc type %d @ %p (%d)\n",
+ apkenv_pid, type, rel, (int) (rel - start));
+ return -1;
+ }
+ } else {
+ /* We got a definition. */
+#if 0
+ if((base == 0) && (si->base != 0)){
+ /* linking from libraries to main image is bad */
+ DL_ERR("%5d cannot locate '%s'...",
+ apkenv_pid, strtab + symtab[sym].st_name);
+ return -1;
+ }
+#endif
+ sym_addr = (unsigned)(s->st_value + base);
+ LINKER_DEBUG_PRINTF("%s symbol (from %s) %s to %x\n", si->name, apkenv_last_library_used, sym_name, sym_addr);
+ if(ELF32_ST_TYPE(s->st_info) == STT_FUNC) {
+ sym_addr = (unsigned)create_wrapper(sym_name, (void*)sym_addr, WRAPPER_UNHOOKED);
+ }
+
+ }
+ COUNT_RELOC(RELOC_SYMBOL);
+ } else {
+ s = NULL;
+ }
+
+/* TODO: This is ugly. Split up the relocations by arch into
+ * different files.
+ */
+ switch(type){
+#if defined(ANDROID_ARM_LINKER)
+ case R_ARM_JUMP_SLOT:
+ COUNT_RELOC(RELOC_ABSOLUTE);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", apkenv_pid,
+ reloc, sym_addr, sym_name);
+ *((unsigned*)reloc) = sym_addr;
+ break;
+ case R_ARM_GLOB_DAT:
+ COUNT_RELOC(RELOC_ABSOLUTE);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", apkenv_pid,
+ reloc, sym_addr, sym_name);
+ *((unsigned*)reloc) = sym_addr;
+ break;
+ case R_ARM_ABS32:
+ COUNT_RELOC(RELOC_ABSOLUTE);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO ABS %08x <- %08x %s\n", apkenv_pid,
+ reloc, sym_addr, sym_name);
+ *((unsigned*)reloc) += sym_addr;
+ break;
+ case R_ARM_REL32:
+ COUNT_RELOC(RELOC_RELATIVE);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO REL32 %08x <- %08x - %08x %s\n", apkenv_pid,
+ reloc, sym_addr, rel->r_offset, sym_name);
+ *((unsigned*)reloc) += sym_addr - rel->r_offset;
+ break;
+#elif defined(ANDROID_X86_LINKER)
+ case R_386_JUMP_SLOT:
+ COUNT_RELOC(RELOC_ABSOLUTE);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO JMP_SLOT %08x <- %08x %s\n", apkenv_pid,
+ reloc, sym_addr, sym_name);
+ *((unsigned*)reloc) = sym_addr;
+ break;
+ case R_386_GLOB_DAT:
+ COUNT_RELOC(RELOC_ABSOLUTE);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO GLOB_DAT %08x <- %08x %s\n", apkenv_pid,
+ reloc, sym_addr, sym_name);
+ *((unsigned*)reloc) = sym_addr;
+ break;
+#endif /* ANDROID_*_LINKER */
+
+#if defined(ANDROID_ARM_LINKER)
+ case R_ARM_RELATIVE:
+#elif defined(ANDROID_X86_LINKER)
+ case R_386_RELATIVE:
+#endif /* ANDROID_*_LINKER */
+ COUNT_RELOC(RELOC_RELATIVE);
+ MARK(rel->r_offset);
+ if(sym){
+ DL_ERR("%5d odd RELATIVE form...", apkenv_pid);
+ return -1;
+ }
+ TRACE_TYPE(RELO, "%5d RELO RELATIVE %08x <- +%08x\n", apkenv_pid,
+ reloc, si->base);
+ *((unsigned*)reloc) += si->base;
+ break;
+
+#if defined(ANDROID_X86_LINKER)
+ case R_386_32:
+ COUNT_RELOC(RELOC_RELATIVE);
+ MARK(rel->r_offset);
+
+ TRACE_TYPE(RELO, "%5d RELO R_386_32 %08x <- +%08x %s\n", apkenv_pid,
+ reloc, sym_addr, sym_name);
+ *((unsigned *)reloc) += (unsigned)sym_addr;
+ break;
+
+ case R_386_PC32:
+ COUNT_RELOC(RELOC_RELATIVE);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO R_386_PC32 %08x <- "
+ "+%08x (%08x - %08x) %s\n", apkenv_pid, reloc,
+ (sym_addr - reloc), sym_addr, reloc, sym_name);
+ *((unsigned *)reloc) += (unsigned)(sym_addr - reloc);
+ break;
+#endif /* ANDROID_X86_LINKER */
+
+#ifdef ANDROID_ARM_LINKER
+ case R_ARM_COPY:
+ COUNT_RELOC(RELOC_COPY);
+ MARK(rel->r_offset);
+ TRACE_TYPE(RELO, "%5d RELO %08x <- %d @ %08x %s\n", apkenv_pid,
+ reloc, s->st_size, sym_addr, sym_name);
+ memcpy((void*)reloc, (void*)sym_addr, s->st_size);
+ break;
+ case R_ARM_NONE:
+ break;
+#endif /* ANDROID_ARM_LINKER */
+
+ default:
+ DL_ERR("%5d unknown reloc type %d @ %p (%d)",
+ apkenv_pid, type, rel, (int) (rel - start));
+ return -1;
+ }
+ rel++;
+ }
+ return 0;
+}
+
+/* Please read the "Initialization and Termination functions" functions.
+ * of the linker design note in bionic/linker/README.TXT to understand
+ * what the following code is doing.
+ *
+ * The important things to remember are:
+ *
+ * DT_PREINIT_ARRAY must be called first for executables, and should
+ * not appear in shared libraries.
+ *
+ * DT_INIT should be called before DT_INIT_ARRAY if both are present
+ *
+ * DT_FINI should be called after DT_FINI_ARRAY if both are present
+ *
+ * DT_FINI_ARRAY must be parsed in reverse order.
+ */
+
+static void apkenv_call_array(unsigned *ctor, int count, int reverse)
+{
+ int n, inc = 1;
+
+ if (reverse) {
+ ctor += (count-1);
+ inc = -1;
+ }
+
+ for(n = count; n > 0; n--) {
+ TRACE("[ %5d Looking at %s *0x%08x == 0x%08x ]\n", apkenv_pid,
+ reverse ? "dtor" : "ctor",
+ (unsigned)ctor, (unsigned)*ctor);
+ void (*func)() = (void (*)()) *ctor;
+ ctor += inc;
+ if(((int) func == 0) || ((int) func == -1)) continue;
+ TRACE("[ %5d Calling func @ 0x%08x ]\n", apkenv_pid, (unsigned)func);
+ func();
+ }
+}
+
+void apkenv_call_constructors_recursive(soinfo *si)
+{
+ if (si->constructors_called)
+ return;
+ if (strcmp(si->name, "libc.so") == 0)
+return;
+ // Set this before actually calling the constructors, otherwise it doesn't
+ // protect against recursive constructor calls. One simple example of
+ // constructor recursion is the libc debug malloc, which is implemented in
+ // libc_malloc_debug_leak.so:
+ // 1. The program depends on libc, so libc's constructor is called here.
+ // 2. The libc constructor calls dlopen() to load libc_malloc_debug_leak.so.
+ // 3. dlopen() calls apkenv_call_constructors_recursive() with the newly created
+ // soinfo for libc_malloc_debug_leak.so.
+ // 4. The debug so depends on libc, so apkenv_call_constructors_recursive() is
+ // called again with the libc soinfo. If it doesn't trigger the early-
+ // out above, the libc constructor will be called again (recursively!).
+ si->constructors_called = 1;
+
+ if (si->flags & FLAG_EXE) {
+ TRACE("[ %5d Calling preinit_array @ 0x%08x [%d] for '%s' ]\n",
+ apkenv_pid, (unsigned)si->preinit_array, si->preinit_array_count,
+ si->name);
+ apkenv_call_array(si->preinit_array, si->preinit_array_count, 0);
+ TRACE("[ %5d Done calling preinit_array for '%s' ]\n", apkenv_pid, si->name);
+ } else {
+ if (si->preinit_array) {
+ DL_ERR("%5d Shared library '%s' has a preinit_array table @ 0x%08x."
+ " This is INVALID.", apkenv_pid, si->name,
+ (unsigned)si->preinit_array);
+ }
+ }
+
+ if (si->dynamic) {
+ unsigned *d;
+ for(d = si->dynamic; *d; d += 2) {
+ if(d[0] == DT_NEEDED){
+ soinfo* lsi = (soinfo *)d[1];
+ if (!apkenv_validate_soinfo(lsi)) {
+ DL_ERR("%5d bad DT_NEEDED pointer in %s",
+ apkenv_pid, si->name);
+ } else {
+ apkenv_call_constructors_recursive(lsi);
+ }
+ }
+ }
+ }
+
+ if (si->init_func) {
+ TRACE("[ %5d Calling init_func @ 0x%08x for '%s' ]\n", apkenv_pid,
+ (unsigned)si->init_func, si->name);
+ si->init_func();
+ TRACE("[ %5d Done calling init_func for '%s' ]\n", apkenv_pid, si->name);
+ }
+
+ if (si->init_array) {
+ TRACE("[ %5d Calling init_array @ 0x%08x [%d] for '%s' ]\n", apkenv_pid,
+ (unsigned)si->init_array, si->init_array_count, si->name);
+ apkenv_call_array(si->init_array, si->init_array_count, 0);
+ TRACE("[ %5d Done calling init_array for '%s' ]\n", apkenv_pid, si->name);
+ }
+
+}
+
+static void apkenv_call_destructors(soinfo *si)
+{
+ if (si->fini_array) {
+ TRACE("[ %5d Calling fini_array @ 0x%08x [%d] for '%s' ]\n", apkenv_pid,
+ (unsigned)si->fini_array, si->fini_array_count, si->name);
+ apkenv_call_array(si->fini_array, si->fini_array_count, 1);
+ TRACE("[ %5d Done calling fini_array for '%s' ]\n", apkenv_pid, si->name);
+ }
+
+ if (si->fini_func) {
+ TRACE("[ %5d Calling fini_func @ 0x%08x for '%s' ]\n", apkenv_pid,
+ (unsigned)si->fini_func, si->name);
+ si->fini_func();
+ TRACE("[ %5d Done calling fini_func for '%s' ]\n", apkenv_pid, si->name);
+ }
+}
+
+/* Force any of the closed stdin, stdout and stderr to be associated with
+ /dev/null. */
+static int apkenv_nullify_closed_stdio (void)
+{
+ int dev_null, i, status;
+ int return_value = 0;
+
+ dev_null = open("/dev/null", O_RDWR);
+ if (dev_null < 0) {
+ DL_ERR("Cannot open /dev/null.");
+ return -1;
+ }
+ TRACE("[ %5d Opened /dev/null file-descriptor=%d]\n", apkenv_pid, dev_null);
+
+ /* If any of the stdio file descriptors is valid and not associated
+ with /dev/null, dup /dev/null to it. */
+ for (i = 0; i < 3; i++) {
+ /* If it is /dev/null already, we are done. */
+ if (i == dev_null)
+ continue;
+
+ TRACE("[ %5d Nullifying stdio file descriptor %d]\n", apkenv_pid, i);
+ /* The man page of fcntl does not say that fcntl(..,F_GETFL)
+ can be interrupted but we do this just to be safe. */
+ do {
+ status = fcntl(i, F_GETFL);
+ } while (status < 0 && errno == EINTR);
+
+ /* If file is openned, we are good. */
+ if (status >= 0)
+ continue;
+
+ /* The only error we allow is that the file descriptor does not
+ exist, in which case we dup /dev/null to it. */
+ if (errno != EBADF) {
+ DL_ERR("nullify_stdio: unhandled error %s", strerror(errno));
+ return_value = -1;
+ continue;
+ }
+
+ /* Try dupping /dev/null to this stdio file descriptor and
+ repeat if there is a signal. Note that any errors in closing
+ the stdio descriptor are lost. */
+ do {
+ status = dup2(dev_null, i);
+ } while (status < 0 && errno == EINTR);
+
+ if (status < 0) {
+ DL_ERR("nullify_stdio: dup2 error %s", strerror(errno));
+ return_value = -1;
+ continue;
+ }
+ }
+
+ /* If /dev/null is not one of the stdio file descriptors, close it. */
+ if (dev_null > 2) {
+ TRACE("[ %5d Closing /dev/null file-descriptor=%d]\n", apkenv_pid, dev_null);
+ do {
+ status = close(dev_null);
+ } while (status < 0 && errno == EINTR);
+
+ if (status < 0) {
+ DL_ERR("nullify_stdio: close error %s", strerror(errno));
+ return_value = -1;
+ }
+ }
+
+ return return_value;
+}
+
+static void apkenv_wrap_function(void *sym_addr, char *sym_name, int is_thumb, soinfo *si)
+{
+ void *hook = NULL;
+#ifdef APKENV_LATEHOOKS
+ if((hook = apkenv_get_hooked_symbol(sym_name, 0)) != NULL)
+ {
+ // if we have a hook redirect the call to that by overwriting
+ // the first 2 instruction of the function
+ // this should work in any case unless the hook is wrong
+ // or the function shorter than 64-bit (2 32-Bit instructions)
+ if(!is_thumb)
+ {
+ DEBUG("HOOKING INTERNAL (ARM) FUNCTION %s@%x (in %s) TO: %x\n",sym_name,sym_addr,si->name,hook);
+ ((int32_t*)sym_addr)[0] = 0xe51ff004; // ldr pc, [pc, -#4] (load the hooks address into pc)
+ ((int32_t*)sym_addr)[1] = (uint32_t)create_wrapper(sym_name, hook, WRAPPER_LATEHOOK);
+
+ __clear_cache((int32_t*)sym_addr, (int32_t*)sym_addr + 2);
+ }
+ else
+ {
+ DEBUG("HOOKING INTERNAL (THUMB) FUNCTION %s@%x (in %s) TO: %x\n",sym_name,sym_addr,si->name,hook);
+ sym_addr = (void*)((char*)sym_addr - 1); // get actual sym_addr
+
+ ((int16_t*)sym_addr)[0] = 0xB401; /* push {r0} */
+ ((int16_t*)sym_addr)[1] = 0xF8DF; /* ldr r0, [pc, #8] */
+ ((int16_t*)sym_addr)[2] = 0x0008; /* continuation of last instruction */
+ ((int16_t*)sym_addr)[3] = 0x4684; /* mov ip, r0 */
+ ((int16_t*)sym_addr)[4] = 0xBC01; /* pop {r0} */
+ ((int16_t*)sym_addr)[5] = 0x4760; /* bx ip */
+
+ void *wrp = create_wrapper(sym_name, hook, WRAPPER_LATEHOOK);
+
+ // store the hooks address
+ ((int16_t*)sym_addr)[6] = (uint32_t)wrp & 0x0000FFFF;
+ ((int16_t*)sym_addr)[7] = (uint32_t)wrp >> 16;
+
+ __clear_cache((int16_t*)sym_addr, (int16_t*)sym_addr + 8);
+ }
+ }
+ else
+#endif /* APKENV_LATEHOOKS */
+ // TODO: this will fail if the first 2 instructions do something pc related
+ // (this DOES NOT happen very often)
+ if(sym_addr && !is_thumb)
+ {
+ DEBUG("CREATING ARM WRAPPER FOR: %s@%x (in %s)\n", sym_name, (unsigned)sym_addr, si->name);
+
+ create_wrapper(sym_name, sym_addr, WRAPPER_ARM_INJECTION);
+ }
+ // TODO: this will fail if the first 2-5 instructions do something pc related
+ // (this DOES happen very often)
+ else if(sym_addr && is_thumb)
+ {
+ DEBUG("CREATING THUMB WRAPPER FOR: %s@%x (in %s)\n",sym_name, (unsigned)sym_addr,si->name);
+
+ create_wrapper(sym_name, sym_addr, WRAPPER_THUMB_INJECTION);
+ }
+}
+
+
+/* Franz-Josef Haider apkenv_create_latehook_wrappers */
+static void apkenv_create_latehook_wrappers(soinfo *si)
+{
+ Elf32_Sym *s;
+
+ unsigned int n = 0;
+ for(n=0;n<si->nchain;n++)
+ {
+ s = si->symtab + n;
+ switch(ELF32_ST_BIND(s->st_info))
+ {
+ case STB_GLOBAL:
+ case STB_WEAK:
+ if(s->st_shndx == 0) continue;
+
+ if(ELF32_ST_TYPE(s->st_info) == STT_FUNC) // only wrap functions
+ {
+ char *sym_name = (char*)(si->strtab + s->st_name);
+ void *sym_addr = (void*)(intptr_t)(si->base + s->st_value);
+
+ int is_thumb = ((int32_t)(intptr_t)sym_addr) & 0x00000001;
+
+ apkenv_wrap_function(sym_addr,sym_name,is_thumb,si);
+ }
+ }
+ }
+}
+
+
+static int apkenv_link_image(soinfo *si, unsigned wr_offset)
+{
+ unsigned *d;
+ Elf32_Phdr *phdr = si->phdr;
+ int phnum = si->phnum;
+
+ INFO("[ %5d linking %s ]\n", apkenv_pid, si->name);
+ DEBUG("%5d si->base = 0x%08x si->flags = 0x%08x\n", apkenv_pid,
+ si->base, si->flags);
+
+ if (si->flags & (FLAG_EXE | FLAG_LINKER)) {
+ /* Locate the needed program segments (DYNAMIC/ARM_EXIDX) for
+ * linkage info if this is the executable or the linker itself.
+ * If this was a dynamic lib, that would have been done at load time.
+ *
+ * TODO: It's unfortunate that small pieces of this are
+ * repeated from the apkenv_load_library routine. Refactor this just
+ * slightly to reuse these bits.
+ */
+ si->size = 0;
+ for(; phnum > 0; --phnum, ++phdr) {
+#ifdef ANDROID_ARM_LINKER
+ if(phdr->p_type == PT_ARM_EXIDX) {
+ /* exidx entries (used for stack unwinding) are 8 bytes each.
+ */
+ si->ARM_exidx = (unsigned *)phdr->p_vaddr;
+ si->ARM_exidx_count = phdr->p_memsz / 8;
+ }
+#endif
+ if (phdr->p_type == PT_LOAD) {
+ /* For the executable, we use the si->size field only in
+ dl_unwind_find_exidx(), so the meaning of si->size
+ is not the size of the executable; it is the distance
+ between the load location of the executable and the last
+ address of the loadable part of the executable.
+ We use the range [si->base, si->base + si->size) to
+ determine whether a PC value falls within the executable
+ section. Of course, if a value is between si->base and
+ (si->base + phdr->p_vaddr), it's not in the executable
+ section, but a) we shouldn't be asking for such a value
+ anyway, and b) if we have to provide an EXIDX for such a
+ value, then the executable's EXIDX is probably the better
+ choice.
+ */
+ DEBUG_DUMP_PHDR(phdr, "PT_LOAD", apkenv_pid);
+ if (phdr->p_vaddr + phdr->p_memsz > si->size)
+ si->size = phdr->p_vaddr + phdr->p_memsz;
+ /* try to remember what range of addresses should be write
+ * protected */
+ if (!(phdr->p_flags & PF_W)) {
+ unsigned _end;
+
+ if (si->base + phdr->p_vaddr < si->wrprotect_start)
+ si->wrprotect_start = si->base + phdr->p_vaddr;
+ _end = (((si->base + phdr->p_vaddr + phdr->p_memsz + PAGE_SIZE - 1) &
+ (~PAGE_MASK)));
+ if (_end > si->wrprotect_end)
+ si->wrprotect_end = _end;
+ /* Make the section writable just in case we'll have to
+ * write to it during relocation (i.e. text segment).
+ * However, we will remember what range of addresses
+ * should be write protected.
+ */
+ mprotect((void *) (si->base + phdr->p_vaddr),
+ phdr->p_memsz,
+ PFLAGS_TO_PROT(phdr->p_flags) | PROT_WRITE);
+ }
+ } else if (phdr->p_type == PT_DYNAMIC) {
+ if (si->dynamic != (unsigned *)-1) {
+ DL_ERR("%5d multiple PT_DYNAMIC segments found in '%s'. "
+ "Segment at 0x%08x, previously one found at 0x%08x",
+ apkenv_pid, si->name, si->base + phdr->p_vaddr,
+ (unsigned)si->dynamic);
+ goto fail;
+ }
+ DEBUG_DUMP_PHDR(phdr, "PT_DYNAMIC", apkenv_pid);
+ si->dynamic = (unsigned *) (si->base + phdr->p_vaddr);
+ } else if (phdr->p_type == PT_GNU_RELRO) {
+ if ((phdr->p_vaddr >= si->size)
+ || ((phdr->p_vaddr + phdr->p_memsz) > si->size)
+ || ((si->base + phdr->p_vaddr + phdr->p_memsz) < si->base)) {
+ DL_ERR("%d invalid GNU_RELRO in '%s' "
+ "p_vaddr=0x%08x p_memsz=0x%08x", apkenv_pid, si->name,
+ phdr->p_vaddr, phdr->p_memsz);
+ goto fail;
+ }
+ si->gnu_relro_start = (Elf32_Addr) (si->base + phdr->p_vaddr);
+ si->gnu_relro_len = (unsigned) phdr->p_memsz;
+ }
+ }
+ }
+
+ if (si->dynamic == (unsigned *)-1) {
+ DL_ERR("%5d missing PT_DYNAMIC?!", apkenv_pid);
+ goto fail;
+ }
+
+ DEBUG("%5d dynamic = %p\n", apkenv_pid, si->dynamic);
+
+ /* extract useful information from dynamic section */
+ for(d = si->dynamic; *d; d++){
+ DEBUG("%5d d = %p, d[0] = 0x%08x d[1] = 0x%08x\n", apkenv_pid, d, d[0], d[1]);
+ switch(*d++){
+ case DT_HASH:
+ si->nbucket = ((unsigned *) (si->base + *d))[0];
+ si->nchain = ((unsigned *) (si->base + *d))[1];
+ si->bucket = (unsigned *) (si->base + *d + 8);
+ si->chain = (unsigned *) (si->base + *d + 8 + si->nbucket * 4);
+ break;
+ case DT_STRTAB:
+ si->strtab = (const char *) (si->base + *d);
+ break;
+ case DT_SYMTAB:
+ si->symtab = (Elf32_Sym *) (si->base + *d);
+ break;
+ case DT_PLTREL:
+ if(*d != DT_REL) {
+ DL_ERR("DT_RELA not supported");
+ goto fail;
+ }
+ break;
+ case DT_JMPREL:
+ si->plt_rel = (Elf32_Rel*) (si->base + *d);
+ break;
+ case DT_PLTRELSZ:
+ si->plt_rel_count = *d / 8;
+ break;
+ case DT_REL:
+ si->rel = (Elf32_Rel*) (si->base + *d);
+ break;
+ case DT_RELSZ:
+ si->rel_count = *d / 8;
+ break;
+ case DT_PLTGOT:
+ /* Save this in case we decide to do lazy binding. We don't yet. */
+ si->plt_got = (unsigned *)(si->base + *d);
+ break;
+ case DT_DEBUG:
+ // Set the DT_DEBUG entry to the addres of _r_debug for GDB
+ *d = (int) &_r_debug;
+ break;
+ case DT_RELA:
+ DL_ERR("%5d DT_RELA not supported", apkenv_pid);
+ goto fail;
+ case DT_INIT:
+ si->init_func = (void (*)(void))(si->base + *d);
+ DEBUG("%5d %s constructors (init func) found at %p\n",
+ apkenv_pid, si->name, si->init_func);
+ break;
+ case DT_FINI:
+ si->fini_func = (void (*)(void))(si->base + *d);
+ DEBUG("%5d %s destructors (fini func) found at %p\n",
+ apkenv_pid, si->name, si->fini_func);
+ break;
+ case DT_INIT_ARRAY:
+ si->init_array = (unsigned *)(si->base + *d);
+ DEBUG("%5d %s constructors (init_array) found at %p\n",
+ apkenv_pid, si->name, si->init_array);
+ break;
+ case DT_INIT_ARRAYSZ:
+ si->init_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
+ break;
+ case DT_FINI_ARRAY:
+ si->fini_array = (unsigned *)(si->base + *d);
+ DEBUG("%5d %s destructors (fini_array) found at %p\n",
+ apkenv_pid, si->name, si->fini_array);
+ break;
+ case DT_FINI_ARRAYSZ:
+ si->fini_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
+ break;
+ case DT_PREINIT_ARRAY:
+ si->preinit_array = (unsigned *)(si->base + *d);
+ DEBUG("%5d %s constructors (preinit_array) found at %p\n",
+ apkenv_pid, si->name, si->preinit_array);
+ break;
+ case DT_PREINIT_ARRAYSZ:
+ si->preinit_array_count = ((unsigned)*d) / sizeof(Elf32_Addr);
+ break;
+ case DT_TEXTREL:
+ /* TODO: make use of this. */
+ /* this means that we might have to write into where the text
+ * segment was loaded during relocation... Do something with
+ * it.
+ */
+ DEBUG("%5d Text segment should be writable during relocation.\n",
+ apkenv_pid);
+ break;
+ }
+ }
+
+ DEBUG("%5d si->base = 0x%08x, si->strtab = %p, si->symtab = %p\n",
+ apkenv_pid, si->base, si->strtab, si->symtab);
+
+ if((si->strtab == 0) || (si->symtab == 0)) {
+ DL_ERR("%5d missing essential tables", apkenv_pid);
+ goto fail;
+ }
+
+ /* if this is the main executable, then load all of the apkenv_preloads now */
+ if(si->flags & FLAG_EXE) {
+ int i;
+ memset(apkenv_preloads, 0, sizeof(apkenv_preloads));
+ for(i = 0; apkenv_ldpreload_names[i] != NULL; i++) {
+ soinfo *lsi = apkenv_find_library(apkenv_ldpreload_names[i]);
+ if(lsi == 0) {
+ apkenv_strlcpy(apkenv_tmp_err_buf, apkenv_linker_get_error(), sizeof(apkenv_tmp_err_buf));
+ DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
+ apkenv_pid, apkenv_ldpreload_names[i], si->name, apkenv_tmp_err_buf);
+ goto fail;
+ }
+ lsi->refcount++;
+ apkenv_preloads[i] = lsi;
+ }
+ }
+
+ for(d = si->dynamic; *d; d += 2) {
+ if(d[0] == DT_NEEDED){
+ DEBUG("%5d %s needs %s\n", apkenv_pid, si->name, si->strtab + d[1]);
+ soinfo *lsi = NULL;
+#if 1
+ // if (get_builtin_lib_handle(si->strtab + d[1]) == NULL)
+ lsi = apkenv_find_library(si->strtab + d[1]);
+ if (!lsi && dlopen(si->strtab + d[1], RTLD_NOW | RTLD_GLOBAL)) {
+ DEBUG("Loaded %s with glibc dlopen\n", si->strtab + d[1]);
+ }
+#endif
+ if(lsi == 0) {
+ /**
+ * XXX Dirty Hack Alarm --thp XXX
+ *
+ * For libraries that are not found, simply use libdl's soinfo,
+ * in order to not break downstream users of the library while
+ * still allowing the application to start up.
+ **/
+ lsi = &apkenv_libdl_info;
+ //apkenv_strlcpy(apkenv_tmp_err_buf, apkenv_linker_get_error(), sizeof(apkenv_tmp_err_buf));
+ //DL_ERR("%5d could not load needed library '%s' for '%s' (%s)",
+ // apkenv_pid, si->strtab + d[1], si->name, apkenv_tmp_err_buf);
+ //continue;
+ //goto fail;
+ }
+ /* Save the soinfo of the loaded DT_NEEDED library in the payload
+ of the DT_NEEDED entry itself, so that we can retrieve the
+ soinfo directly later from the dynamic segment. This is a hack,
+ but it allows us to map from DT_NEEDED to soinfo efficiently
+ later on when we resolve relocations, trying to look up a symbol
+ with dlsym().
+ */
+ d[1] = (intptr_t)lsi;
+ lsi->refcount++;
+ }
+ }
+
+ if(si->plt_rel) {
+ DEBUG("[ %5d relocating %s plt ]\n", apkenv_pid, si->name );
+ if(apkenv_reloc_library(si, si->plt_rel, si->plt_rel_count))
+ goto fail;
+ }
+ if(si->rel) {
+ DEBUG("[ %5d relocating %s ]\n", apkenv_pid, si->name );
+ if(apkenv_reloc_library(si, si->rel, si->rel_count))
+ goto fail;
+ }
+
+ apkenv_create_latehook_wrappers(si);
+
+ si->flags |= FLAG_LINKED;
+ DEBUG("[ %5d finished linking %s ]\n", apkenv_pid, si->name);
+
+#if 0
+ /* This is the way that the old dynamic linker did protection of
+ * non-writable areas. It would scan section headers and find where
+ * .text ended (rather where .data/.bss began) and assume that this is
+ * the upper range of the non-writable area. This is too coarse,
+ * and is kept here for reference until we fully move away from single
+ * segment elf objects. See the code in get_wr_offset (also #if'd 0)
+ * that made this possible.
+ */
+ if(wr_offset < 0xffffffff){
+ mprotect((void*) si->base, wr_offset, PROT_READ | PROT_EXEC);
+ }
+#else
+ /* TODO: Verify that this does the right thing in all cases, as it
+ * presently probably does not. It is possible that an ELF image will
+ * come with multiple read-only segments. What we ought to do is scan
+ * the program headers again and mprotect all the read-only segments.
+ * To prevent re-scanning the program header, we would have to build a
+ * list of loadable segments in si, and then scan that instead. */
+ if (si->wrprotect_start != 0xffffffff && si->wrprotect_end != 0) {
+ mprotect((void *)(intptr_t)si->wrprotect_start,
+ si->wrprotect_end - si->wrprotect_start,
+ PROT_READ | PROT_EXEC);
+ }
+#endif
+
+ if (si->gnu_relro_start != 0 && si->gnu_relro_len != 0) {
+ Elf32_Addr start = (si->gnu_relro_start & ~PAGE_MASK);
+ unsigned len = (si->gnu_relro_start - start) + si->gnu_relro_len;
+ if (mprotect((void *)(intptr_t)start, len, PROT_READ) < 0) {
+ DL_ERR("%5d GNU_RELRO mprotect of library '%s' failed: %d (%s)\n",
+ apkenv_pid, si->name, errno, strerror(errno));
+ goto fail;
+ }
+ }
+
+ /* If this is a SET?ID program, dup /dev/null to opened stdin,
+ stdout and stderr to close a security hole described in:
+
+ ftp://ftp.freebsd.org/pub/FreeBSD/CERT/advisories/FreeBSD-SA-02:23.stdio.asc
+
+ */
+ if (apkenv_program_is_setuid)
+ apkenv_nullify_closed_stdio ();
+ apkenv_notify_gdb_of_load(si);
+ return 0;
+
+fail:
+ ERROR("failed to link %s\n", si->name);
+ si->flags |= FLAG_ERROR;
+ return -1;
+}
+
+void apkenv_parse_library_path(const char *path, char *delim)
+{
+ size_t len;
+ char *apkenv_ldpaths_bufp = apkenv_ldpaths_buf;
+ int i = 0;
+
+ len = apkenv_strlcpy(apkenv_ldpaths_buf, path, sizeof(apkenv_ldpaths_buf));
+
+ while (i < LDPATH_MAX && (apkenv_ldpaths[i] = strsep(&apkenv_ldpaths_bufp, delim))) {
+ if (*apkenv_ldpaths[i] != '\0')
+ ++i;
+ }
+
+ /* Forget the last path if we had to truncate; this occurs if the 2nd to
+ * last char isn't '\0' (i.e. not originally a delim). */
+ if (i > 0 && len >= sizeof(apkenv_ldpaths_buf) &&
+ apkenv_ldpaths_buf[sizeof(apkenv_ldpaths_buf) - 2] != '\0') {
+ apkenv_ldpaths[i - 1] = NULL;
+ } else {
+ apkenv_ldpaths[i] = NULL;
+ }
+}
+
+static void apkenv_parse_apkenv_preloads(const char *path, char *delim)
+{
+ size_t len;
+ char *apkenv_ldpreloads_bufp = apkenv_ldpreloads_buf;
+ int i = 0;
+
+ len = apkenv_strlcpy(apkenv_ldpreloads_buf, path, sizeof(apkenv_ldpreloads_buf));
+
+ while (i < LDPRELOAD_MAX && (apkenv_ldpreload_names[i] = strsep(&apkenv_ldpreloads_bufp, delim))) {
+ if (*apkenv_ldpreload_names[i] != '\0') {
+ ++i;
+ }
+ }
+
+ /* Forget the last path if we had to truncate; this occurs if the 2nd to
+ * last char isn't '\0' (i.e. not originally a delim). */
+ if (i > 0 && len >= sizeof(apkenv_ldpreloads_buf) &&
+ apkenv_ldpreloads_buf[sizeof(apkenv_ldpreloads_buf) - 2] != '\0') {
+ apkenv_ldpreload_names[i - 1] = NULL;
+ } else {
+ apkenv_ldpreload_names[i] = NULL;
+ }
+}
+
+/*
+ * This code is called after the linker has linked itself and
+ * fixed it's own GOT. It is safe to make references to externs
+ * and other non-local data at this point.
+ */
+static unsigned apkenv___linker_init_post_relocation(unsigned **elfdata)
+{
+ static soinfo linker_soinfo;
+
+ int argc = (int)(intptr_t)*elfdata;
+ char **argv = (char**) (elfdata + 1);
+ unsigned *vecs = (unsigned*) (argv + argc + 1);
+ unsigned *v;
+ soinfo *si;
+ struct link_map * map;
+ const char *ldpath_env = NULL;
+ const char *ldpreload_env = NULL;
+
+ /* NOTE: we store the elfdata pointer on a special location
+ * of the temporary TLS area in order to pass it to
+ * the C Library's runtime initializer.
+ *
+ * The initializer must clear the slot and reset the TLS
+ * to point to a different location to ensure that no other
+ * shared library constructor can access it.
+ */
+#if 0
+ __libc_init_tls(elfdata);
+#endif
+
+ apkenv_pid = getpid();
+
+#if TIMING
+ struct timeval t0, t1;
+ gettimeofday(&t0, 0);
+#endif
+
+ /* Initialize environment functions, and get to the ELF aux vectors table */
+ vecs = apkenv_linker_env_init(vecs);
+
+ /* Check auxv for AT_SECURE first to see if program is setuid, setgid,
+ has file caps, or caused a SELinux/AppArmor domain transition. */
+ for (v = vecs; v[0]; v += 2) {
+ if (v[0] == AT_SECURE) {
+ /* kernel told us whether to enable secure mode */
+ apkenv_program_is_setuid = v[1];
+ goto sanitize;
+ }
+ }
+
+ /* Kernel did not provide AT_SECURE - fall back on legacy test. */
+ apkenv_program_is_setuid = (getuid() != geteuid()) || (getgid() != getegid());
+
+sanitize:
+ /* Sanitize environment if we're loading a setuid program */
+ if (apkenv_program_is_setuid)
+ apkenv_linker_env_secure();
+
+#if 0
+ apkenv_debugger_init();
+#endif
+
+ /* Get a few environment variables */
+ {
+#if LINKER_DEBUG
+ const char* env;
+ env = apkenv_linker_env_get("DEBUG"); /* XXX: TODO: Change to LD_DEBUG */
+ if (env)
+ apkenv_debug_verbosity = atoi(env);
+#endif
+
+ /* Normally, these are cleaned by linker_env_secure, but the test
+ * against apkenv_program_is_setuid doesn't cost us anything */
+ if (!apkenv_program_is_setuid) {
+ ldpath_env = getenv("LD_LIBRARY_PATH");
+ ldpreload_env = getenv("LD_PRELOAD");
+ }
+ }
+
+ INFO("[ android linker & debugger ]\n");
+ DEBUG("%5d elfdata @ 0x%08x\n", apkenv_pid, (unsigned)elfdata);
+
+ si = apkenv_alloc_info(argv[0]);
+ if(si == 0) {
+ exit(-1);
+ }
+
+ /* bootstrap the link map, the main exe always needs to be first */
+ si->flags |= FLAG_EXE;
+ map = &(si->linkmap);
+
+ map->l_addr = 0;
+ map->l_name = argv[0];
+ map->l_prev = NULL;
+ map->l_next = NULL;
+
+ _r_debug.r_map = map;
+ apkenv_r_debug_tail = map;
+
+ /* gdb expects the linker to be in the debug shared object list,
+ * and we need to make sure that the reported load address is zero.
+ * Without this, gdb gets the wrong idea of where rtld_db_dlactivity()
+ * is. Don't use apkenv_alloc_info(), because the linker shouldn't
+ * be on the soinfo list.
+ */
+ apkenv_strlcpy((char*) linker_soinfo.name, "/system/bin/linker", sizeof linker_soinfo.name);
+ linker_soinfo.flags = 0;
+ linker_soinfo.base = 0; // This is the important part; must be zero.
+ apkenv_insert_soinfo_into_debug_map(&linker_soinfo);
+
+ /* extract information passed from the kernel */
+ while(vecs[0] != 0){
+ switch(vecs[0]){
+ case AT_PHDR:
+ si->phdr = (Elf32_Phdr*)(intptr_t)vecs[1];
+ break;
+ case AT_PHNUM:
+ si->phnum = (int) vecs[1];
+ break;
+ case AT_ENTRY:
+ si->entry = vecs[1];
+ break;
+ }
+ vecs += 2;
+ }
+
+ /* Compute the value of si->base. We can't rely on the fact that
+ * the first entry is the PHDR because this will not be true
+ * for certain executables (e.g. some in the NDK unit test suite)
+ */
+ int nn;
+ si->base = 0;
+ for ( nn = 0; nn < si->phnum; nn++ ) {
+ if (si->phdr[nn].p_type == PT_PHDR) {
+ si->base = (Elf32_Addr)(intptr_t)si->phdr - si->phdr[nn].p_vaddr;
+ break;
+ }
+ }
+ si->dynamic = (unsigned *)-1;
+ si->wrprotect_start = 0xffffffff;
+ si->wrprotect_end = 0;
+ si->refcount = 1;
+ si->gnu_relro_start = 0;
+ si->gnu_relro_len = 0;
+
+ /* Use LD_LIBRARY_PATH if we aren't setuid/setgid */
+ if (ldpath_env)
+ apkenv_parse_library_path(ldpath_env, ":");
+
+ if (ldpreload_env) {
+ apkenv_parse_apkenv_preloads(ldpreload_env, " :");
+ }
+ if(apkenv_link_image(si, 0)) {
+ char errmsg[] = "CANNOT LINK EXECUTABLE\n";
+ write(2, apkenv___linker_dl_err_buf, strlen(apkenv___linker_dl_err_buf));
+ write(2, errmsg, sizeof(errmsg));
+ exit(-1);
+ }
+
+ apkenv_call_constructors_recursive(si);
+
+#if ALLOW_SYMBOLS_FROM_MAIN
+ /* Set apkenv_somain after we've loaded all the libraries in order to prevent
+ * linking of symbols back to the main image, which is not set up at that
+ * point yet.
+ */
+ apkenv_somain = si;
+#endif
+
+#if TIMING
+ gettimeofday(&t1,NULL);
+ PRINT("LINKER TIME: %s: %d microseconds\n", argv[0], (int) (
+ (((long long)t1.tv_sec * 1000000LL) + (long long)t1.tv_usec) -
+ (((long long)t0.tv_sec * 1000000LL) + (long long)t0.tv_usec)
+ ));
+#endif
+#if STATS
+ PRINT("RELO STATS: %s: %d abs, %d rel, %d copy, %d symbol\n", argv[0],
+ apkenv_linker_stats.reloc[RELOC_ABSOLUTE],
+ apkenv_linker_stats.reloc[RELOC_RELATIVE],
+ apkenv_linker_stats.reloc[RELOC_COPY],
+ apkenv_linker_stats.reloc[RELOC_SYMBOL]);
+#endif
+#if COUNT_PAGES
+ {
+ unsigned n;
+ unsigned i;
+ unsigned count = 0;
+ for(n = 0; n < 4096; n++){
+ if(apkenv_bitmask[n]){
+ unsigned x = apkenv_bitmask[n];
+ for(i = 0; i < 8; i++){
+ if(x & 1) count++;
+ x >>= 1;
+ }
+ }
+ }
+ PRINT("PAGES MODIFIED: %s: %d (%dKB)\n", argv[0], count, count * 4);
+ }
+#endif
+
+#if TIMING || STATS || COUNT_PAGES
+ fflush(stdout);
+#endif
+
+ TRACE("[ %5d Ready to execute '%s' @ 0x%08x ]\n", apkenv_pid, si->name,
+ si->entry);
+ return si->entry;
+}
+
+/*
+ * Find the value of AT_BASE passed to us by the kernel. This is the load
+ * location of the linker.
+ */
+static unsigned apkenv_find_linker_base(unsigned **elfdata) {
+ int argc = (int)(intptr_t)*elfdata;
+ char **argv = (char**) (elfdata + 1);
+ unsigned *vecs = (unsigned*) (argv + argc + 1);
+ while (vecs[0] != 0) {
+ vecs++;
+ }
+
+ /* The end of the environment block is marked by two NULL pointers */
+ vecs++;
+
+ while(vecs[0]) {
+ if (vecs[0] == AT_BASE) {
+ return vecs[1];
+ }
+ vecs += 2;
+ }
+
+ return 0; // should never happen
+}
+
+/*
+ * This is the entry point for the linker, called from begin.S. This
+ * method is responsible for fixing the linker's own relocations, and
+ * then calling apkenv___linker_init_post_relocation().
+ *
+ * Because this method is called before the linker has fixed it's own
+ * relocations, any attempt to reference an extern variable, extern
+ * function, or other GOT reference will generate a segfault.
+ */
+unsigned apkenv___linker_init(unsigned **elfdata) {
+ unsigned linker_addr = apkenv_find_linker_base(elfdata);
+ Elf32_Ehdr *elf_hdr = (Elf32_Ehdr *)(intptr_t)linker_addr;
+ Elf32_Phdr *phdr =
+ (Elf32_Phdr *)((unsigned char *)(intptr_t)linker_addr + elf_hdr->e_phoff);
+
+ soinfo linker_so;
+ memset(&linker_so, 0, sizeof(soinfo));
+
+ linker_so.base = linker_addr;
+ linker_so.dynamic = (unsigned *) -1;
+ linker_so.phdr = phdr;
+ linker_so.phnum = elf_hdr->e_phnum;
+ linker_so.flags |= FLAG_LINKER;
+ linker_so.wrprotect_start = 0xffffffff;
+ linker_so.wrprotect_end = 0;
+ linker_so.gnu_relro_start = 0;
+ linker_so.gnu_relro_len = 0;
+ if (apkenv_link_image(&linker_so, 0)) {
+ // It would be nice to print an error message, but if the linker
+ // can't link itself, there's no guarantee that we'll be able to
+ // call write() (because it involves a GOT reference).
+ //
+ // This situation should never occur unless the linker itself
+ // is corrupt.
+ exit(-1);
+ }
+
+ // We have successfully fixed our own relocations. It's safe to run
+ // the main part of the linker now.
+ return apkenv___linker_init_post_relocation(elfdata);
+}
diff --git a/src/linker/linker.h b/src/linker/linker.h
new file mode 100644
index 0000000..13d9bff
--- /dev/null
+++ b/src/linker/linker.h
@@ -0,0 +1,226 @@
+/*
+ * Copyright (C) 2008 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 _LINKER_H_
+#define _LINKER_H_
+
+#include <unistd.h>
+#include <sys/types.h>
+#include <elf.h>
+#include <link.h>
+
+#undef PAGE_MASK
+#undef PAGE_SIZE
+#define PAGE_SIZE 4096
+#define PAGE_MASK 4095
+
+void apkenv_debugger_init();
+
+/* magic shared structures that GDB knows about */
+
+#if 0
+struct link_map
+{
+ uintptr_t l_addr;
+ char * l_name;
+ uintptr_t l_ld;
+ struct link_map * l_next;
+ struct link_map * l_prev;
+};
+
+/* needed for dl_iterate_phdr to be passed to the callbacks provided */
+struct dl_phdr_info
+{
+ Elf32_Addr dlpi_addr;
+ const char *dlpi_name;
+ const Elf32_Phdr *dlpi_phdr;
+ Elf32_Half dlpi_phnum;
+};
+
+
+// Values for r_debug->state
+enum {
+ RT_CONSISTENT,
+ RT_ADD,
+ RT_DELETE
+};
+
+struct r_debug
+{
+ int32_t r_version;
+ struct link_map * r_map;
+ void (*r_brk)(void);
+ int32_t r_state;
+ uintptr_t r_ldbase;
+};
+#endif
+
+typedef struct soinfo soinfo;
+
+#define FLAG_LINKED 0x00000001
+#define FLAG_ERROR 0x00000002
+#define FLAG_EXE 0x00000004 // The main executable
+#define FLAG_LINKER 0x00000010 // The linker itself
+
+#define SOINFO_NAME_LEN 128
+
+struct soinfo
+{
+ const char name[SOINFO_NAME_LEN];
+ Elf32_Phdr *phdr;
+ int phnum;
+ unsigned entry;
+ unsigned base;
+ unsigned size;
+
+ int unused; // DO NOT USE, maintained for compatibility.
+
+ unsigned *dynamic;
+
+ unsigned wrprotect_start;
+ unsigned wrprotect_end;
+
+ soinfo *next;
+ unsigned flags;
+
+ const char *strtab;
+ Elf32_Sym *symtab;
+
+ unsigned nbucket;
+ unsigned nchain;
+ unsigned *bucket;
+ unsigned *chain;
+
+ unsigned *plt_got;
+
+ Elf32_Rel *plt_rel;
+ unsigned plt_rel_count;
+
+ Elf32_Rel *rel;
+ unsigned rel_count;
+
+ unsigned *preinit_array;
+ unsigned preinit_array_count;
+
+ unsigned *init_array;
+ unsigned init_array_count;
+ unsigned *fini_array;
+ unsigned fini_array_count;
+
+ void (*init_func)(void);
+ void (*fini_func)(void);
+
+#ifdef ANDROID_ARM_LINKER
+ /* ARM EABI section used for stack unwinding. */
+ unsigned *ARM_exidx;
+ unsigned ARM_exidx_count;
+#endif
+
+ unsigned refcount;
+ struct link_map linkmap;
+
+ int constructors_called;
+
+ Elf32_Addr gnu_relro_start;
+ unsigned gnu_relro_len;
+
+ /* apkenv stuff */
+ char fullpath[SOINFO_NAME_LEN];
+};
+
+
+extern soinfo apkenv_libdl_info;
+
+#ifdef ANDROID_ARM_LINKER
+
+#define R_ARM_COPY 20
+#define R_ARM_GLOB_DAT 21
+#define R_ARM_JUMP_SLOT 22
+#define R_ARM_RELATIVE 23
+
+/* According to the AAPCS specification, we only
+ * need the above relocations. However, in practice,
+ * the following ones turn up from time to time.
+ */
+#define R_ARM_ABS32 2
+#define R_ARM_REL32 3
+
+#elif defined(ANDROID_X86_LINKER)
+
+#define R_386_32 1
+#define R_386_PC32 2
+#define R_386_GLOB_DAT 6
+#define R_386_JUMP_SLOT 7
+#define R_386_RELATIVE 8
+
+#endif
+
+#ifndef DT_INIT_ARRAY
+#define DT_INIT_ARRAY 25
+#endif
+
+#ifndef DT_FINI_ARRAY
+#define DT_FINI_ARRAY 26
+#endif
+
+#ifndef DT_INIT_ARRAYSZ
+#define DT_INIT_ARRAYSZ 27
+#endif
+
+#ifndef DT_FINI_ARRAYSZ
+#define DT_FINI_ARRAYSZ 28
+#endif
+
+#ifndef DT_PREINIT_ARRAY
+#define DT_PREINIT_ARRAY 32
+#endif
+
+#ifndef DT_PREINIT_ARRAYSZ
+#define DT_PREINIT_ARRAYSZ 33
+#endif
+
+soinfo *apkenv_find_library(const char *name);
+unsigned apkenv_unload_library(soinfo *si);
+Elf32_Sym *apkenv_lookup_in_library(soinfo *si, const char *name);
+Elf32_Sym *apkenv_lookup(const char *name, soinfo **found, soinfo *start);
+soinfo *apkenv_find_containing_library(const void *addr);
+Elf32_Sym *apkenv_find_containing_symbol(const void *addr, soinfo *si);
+const char *apkenv_linker_get_error(void);
+void apkenv_call_constructors_recursive(soinfo *si);
+
+#ifdef ANDROID_ARM_LINKER
+typedef long unsigned int *_Unwind_Ptr;
+_Unwind_Ptr apkenv_dl_unwind_find_exidx(_Unwind_Ptr pc, int *pcount);
+#elif defined(ANDROID_X86_LINKER)
+int apkenv_dl_iterate_phdr(int (*cb)(struct dl_phdr_info *, size_t, void *), void *);
+#endif
+
+void apkenv_notify_gdb_of_libraries(void);
+int apkenv_add_sopath(const char *path);
+
+#endif
diff --git a/src/linker/linker_debug.h b/src/linker/linker_debug.h
new file mode 100644
index 0000000..2ab7a40
--- /dev/null
+++ b/src/linker/linker_debug.h
@@ -0,0 +1,154 @@
+/*
+ * Copyright (C) 2008-2010 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 _LINKER_DEBUG_H_
+#define _LINKER_DEBUG_H_
+
+#include <stdio.h>
+
+#ifndef LINKER_DEBUG
+#error LINKER_DEBUG should be defined to either 1 or 0 in Android.mk
+#endif
+
+/* set LINKER_DEBUG_TO_LOG to 1 to send the logs to logcat,
+ * or 0 to use stdout instead.
+ */
+#define LINKER_DEBUG_TO_LOG 0
+#define TRACE_DEBUG 1
+#define DO_TRACE_LOOKUP 1
+#define DO_TRACE_RELO 1
+#define TIMING 0
+#define STATS 0
+#define COUNT_PAGES 0
+
+/*********************************************************************
+ * You shouldn't need to modify anything below unless you are adding
+ * more debugging information.
+ *
+ * To enable/disable specific debug options, change the defines above
+ *********************************************************************/
+
+
+/*********************************************************************/
+#undef TRUE
+#undef FALSE
+#define TRUE 1
+#define FALSE 0
+
+/* Only use printf() during debugging. We have seen occasional memory
+ * corruption when the linker uses printf().
+ */
+#if LINKER_DEBUG
+#include "linker_format.h"
+extern int apkenv_debug_verbosity;
+#if LINKER_DEBUG_TO_LOG
+extern int apkenv_format_log(int, const char *, const char *, ...);
+#define _PRINTVF(v,f,x...) \
+ do { \
+ if (apkenv_debug_verbosity > (v)) apkenv_format_log(5-(v),"linker",x); \
+ } while (0)
+#else /* !LINKER_DEBUG_TO_LOG */
+#define _PRINTVF(v,f,x...) \
+ do { \
+ if (apkenv_debug_verbosity > (v)) printf(x); \
+ } while (0)
+#endif /* !LINKER_DEBUG_TO_LOG */
+#else /* !LINKER_DEBUG */
+#define _PRINTVF(v,f,x...) do {} while(0)
+#endif /* LINKER_DEBUG */
+
+#define PRINT(x...) _PRINTVF(-1, FALSE, x)
+#define INFO(x...) _PRINTVF(1, TRUE, x)
+#define TRACE(x...) _PRINTVF(1, TRUE, x)
+#define WARN(fmt,args...) \
+ _PRINTVF(-1, TRUE, "%s:%d| WARNING: " fmt, __FILE__, __LINE__, ## args)
+#define ERROR(fmt,args...) \
+ printf("%s:%d| ERROR: " fmt, __FILE__, __LINE__, ## args)
+
+
+#if TRACE_DEBUG
+#define DEBUG(x...) _PRINTVF(2, TRUE, "DEBUG: " x)
+#else /* !TRACE_DEBUG */
+#define DEBUG(x...) do {} while (0)
+#endif /* TRACE_DEBUG */
+
+#if LINKER_DEBUG
+#define TRACE_TYPE(t,x...) do { if (DO_TRACE_##t) { TRACE(x); } } while (0)
+#else /* !LINKER_DEBUG */
+#define TRACE_TYPE(t,x...) do {} while (0)
+#endif /* LINKER_DEBUG */
+
+#if STATS
+#define RELOC_ABSOLUTE 0
+#define RELOC_RELATIVE 1
+#define RELOC_COPY 2
+#define RELOC_SYMBOL 3
+#define NUM_RELOC_STATS 4
+
+struct _link_stats {
+ int reloc[NUM_RELOC_STATS];
+};
+extern struct _link_stats apkenv_linker_stats;
+
+#define COUNT_RELOC(type) \
+ do { if (type >= 0 && type < NUM_RELOC_STATS) { \
+ apkenv_linker_stats.reloc[type] += 1; \
+ } else { \
+ PRINT("Unknown reloc stat requested\n"); \
+ } \
+ } while(0)
+#else /* !STATS */
+#define COUNT_RELOC(type) do {} while(0)
+#endif /* STATS */
+
+#if TIMING
+#undef WARN
+#define WARN(x...) do {} while (0)
+#endif /* TIMING */
+
+#if COUNT_PAGES
+extern unsigned apkenv_bitmask[];
+#define MARK(offset) do { \
+ apkenv_bitmask[((offset) >> 12) >> 3] |= (1 << (((offset) >> 12) & 7)); \
+ } while(0)
+#else
+#define MARK(x) do {} while (0)
+#endif
+
+#define DEBUG_DUMP_PHDR(phdr, name, pid) do { \
+ DEBUG("%5d %s (phdr = 0x%08x)\n", (pid), (name), (unsigned)(phdr)); \
+ DEBUG("\t\tphdr->offset = 0x%08x\n", (unsigned)((phdr)->p_offset)); \
+ DEBUG("\t\tphdr->p_vaddr = 0x%08x\n", (unsigned)((phdr)->p_vaddr)); \
+ DEBUG("\t\tphdr->p_paddr = 0x%08x\n", (unsigned)((phdr)->p_paddr)); \
+ DEBUG("\t\tphdr->p_filesz = 0x%08x\n", (unsigned)((phdr)->p_filesz)); \
+ DEBUG("\t\tphdr->p_memsz = 0x%08x\n", (unsigned)((phdr)->p_memsz)); \
+ DEBUG("\t\tphdr->p_flags = 0x%08x\n", (unsigned)((phdr)->p_flags)); \
+ DEBUG("\t\tphdr->p_align = 0x%08x\n", (unsigned)((phdr)->p_align)); \
+ } while (0)
+
+#endif /* _LINKER_DEBUG_H_ */
diff --git a/src/linker/linker_environ.c b/src/linker/linker_environ.c
new file mode 100644
index 0000000..ca8b1d9
--- /dev/null
+++ b/src/linker/linker_environ.c
@@ -0,0 +1,204 @@
+/*
+ * Copyright (C) 2010 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_environ.h"
+#include <stddef.h>
+
+static char** apkenv__envp;
+
+/* Returns 1 if 'str' points to a valid environment variable definition.
+ * For now, we check that:
+ * - It is smaller than MAX_ENV_LEN (to detect non-zero terminated strings)
+ * - It contains at least one equal sign that is not the first character
+ */
+static int
+apkenv__is_valid_definition(const char* str)
+{
+ int pos = 0;
+ int first_equal_pos = -1;
+
+ /* According to its sources, the kernel uses 32*PAGE_SIZE by default
+ * as the maximum size for an env. variable definition.
+ */
+ const int MAX_ENV_LEN = 32*4096;
+
+ if (str == NULL)
+ return 0;
+
+ /* Parse the string, looking for the first '=' there, and its size */
+ do {
+ if (str[pos] == '\0')
+ break;
+ if (str[pos] == '=' && first_equal_pos < 0)
+ first_equal_pos = pos;
+ pos++;
+ } while (pos < MAX_ENV_LEN);
+
+ if (pos >= MAX_ENV_LEN) /* Too large */
+ return 0;
+
+ if (first_equal_pos < 1) /* No equal sign, or it is the first character */
+ return 0;
+
+ return 1;
+}
+
+unsigned*
+apkenv_linker_env_init(unsigned* vecs)
+{
+ /* Store environment pointer - can't be NULL */
+ apkenv__envp = (char**) vecs;
+
+ /* Skip over all definitions */
+ while (vecs[0] != 0)
+ vecs++;
+ /* The end of the environment block is marked by two NULL pointers */
+ vecs++;
+
+ /* As a sanity check, we're going to remove all invalid variable
+ * definitions from the environment array.
+ */
+ {
+ char** readp = apkenv__envp;
+ char** writep = apkenv__envp;
+ for ( ; readp[0] != NULL; readp++ ) {
+ if (!apkenv__is_valid_definition(readp[0]))
+ continue;
+ writep[0] = readp[0];
+ writep++;
+ }
+ writep[0] = NULL;
+ }
+
+ /* Return the address of the aux vectors table */
+ return vecs;
+}
+
+/* Check if the environment variable definition at 'envstr'
+ * starts with '<name>=', and if so return the address of the
+ * first character after the equal sign. Otherwise return NULL.
+ */
+static char*
+apkenv_env_match(char* envstr, const char* name)
+{
+ size_t cnt = 0;
+
+ while (envstr[cnt] == name[cnt] && name[cnt] != '\0')
+ cnt++;
+
+ if (name[cnt] == '\0' && envstr[cnt] == '=')
+ return envstr + cnt + 1;
+
+ return NULL;
+}
+
+#define MAX_ENV_LEN (16*4096)
+
+const char*
+apkenv_linker_env_get(const char* name)
+{
+ char** readp = apkenv__envp;
+
+ if (name == NULL || name[0] == '\0')
+ return NULL;
+
+ for ( ; readp[0] != NULL; readp++ ) {
+ char* val = apkenv_env_match(readp[0], name);
+ if (val != NULL) {
+ /* Return NULL for empty strings, or if it is too large */
+ if (val[0] == '\0')
+ val = NULL;
+ return val;
+ }
+ }
+ return NULL;
+}
+
+
+void
+apkenv_linker_env_unset(const char* name)
+{
+ char** readp = apkenv__envp;
+ char** writep = readp;
+
+ if (name == NULL || name[0] == '\0')
+ return;
+
+ for ( ; readp[0] != NULL; readp++ ) {
+ if (apkenv_env_match(readp[0], name))
+ continue;
+ writep[0] = readp[0];
+ writep++;
+ }
+ /* end list with a NULL */
+ writep[0] = NULL;
+}
+
+
+
+/* Remove unsafe environment variables. This should be used when
+ * running setuid programs. */
+void
+apkenv_linker_env_secure(void)
+{
+ /* The same list than GLibc at this point */
+ static const char* const unsec_vars[] = {
+ "GCONV_PATH",
+ "GETCONF_DIR",
+ "HOSTALIASES",
+ "LD_AUDIT",
+ "LD_DEBUG",
+ "LD_DEBUG_OUTPUT",
+ "LD_DYNAMIC_WEAK",
+ "LD_LIBRARY_PATH",
+ "LD_ORIGIN_PATH",
+ "LD_PRELOAD",
+ "LD_PROFILE",
+ "LD_SHOW_AUXV",
+ "LD_USE_LOAD_BIAS",
+ "LOCALDOMAIN",
+ "LOCPATH",
+ "MALLOC_TRACE",
+ "MALLOC_CHECK_",
+ "NIS_PATH",
+ "NLSPATH",
+ "RESOLV_HOST_CONF",
+ "RES_OPTIONS",
+ "TMPDIR",
+ "TZDIR",
+ "LD_AOUT_LIBRARY_PATH",
+ "LD_AOUT_PRELOAD",
+ };
+
+ const char* const* cp = unsec_vars;
+ const char* const* endp = cp + sizeof(unsec_vars)/sizeof(unsec_vars[0]);
+
+ while (cp < endp) {
+ apkenv_linker_env_unset(*cp);
+ cp++;
+ }
+}
diff --git a/src/linker/linker_environ.h b/src/linker/linker_environ.h
new file mode 100644
index 0000000..9bb24c4
--- /dev/null
+++ b/src/linker/linker_environ.h
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 2010 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 LINKER_ENVIRON_H
+#define LINKER_ENVIRON_H
+
+/* Call this function before anything else. 'vecs' must be the pointer
+ * to the environment block in the ELF data block. The function returns
+ * the start of the aux vectors after the env block.
+ */
+extern unsigned* apkenv_linker_env_init(unsigned* vecs);
+
+/* Unset a given environment variable. In case the variable is defined
+ * multiple times, unset all instances. This modifies the environment
+ * block, so any pointer returned by linker_env_get() after this call
+ * might become invalid */
+extern void apkenv_linker_env_unset(const char* name);
+
+
+/* Returns the value of environment variable 'name' if defined and not
+ * empty, or NULL otherwise. Note that the returned pointer may become
+ * invalid if linker_env_unset() or linker_env_secure() are called
+ * after this function. */
+extern const char* apkenv_linker_env_get(const char* name);
+
+/* Remove unsecure environment variables. This should be used when
+ * running setuid programs. */
+extern void apkenv_linker_env_secure(void);
+
+#endif /* LINKER_ENVIRON_H */
diff --git a/src/linker/linker_format.h b/src/linker/linker_format.h
new file mode 100644
index 0000000..e7b34b5
--- /dev/null
+++ b/src/linker/linker_format.h
@@ -0,0 +1,43 @@
+/*
+ * Copyright (C) 2010 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 _LINKER_FORMAT_H
+#define _LINKER_FORMAT_H
+
+#include <stdarg.h>
+#include <stddef.h>
+
+/* Formatting routines for the dynamic linker's debug traces */
+/* We want to avoid dragging the whole C library fprintf() */
+/* implementation into the dynamic linker since this creates */
+/* issues (it uses malloc()/free()) and increases code size */
+
+// apkenv: we can just use snprintf
+//int format_buffer(char *buffer, size_t bufsize, const char *format, ...);
+#define format_buffer snprintf
+
+#endif /* _LINKER_FORMAT_H */
diff --git a/src/linker/rt.c b/src/linker/rt.c
new file mode 100644
index 0000000..31db8ee
--- /dev/null
+++ b/src/linker/rt.c
@@ -0,0 +1,36 @@
+/*
+ * Copyright (C) 2008 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.
+ */
+
+/*
+ * This function is an empty stub where GDB locates a breakpoint to get notified
+ * about linker activity.
+ */
+void __attribute__((noinline)) apkenv_rtld_db_dlactivity(void)
+{
+}
+
diff --git a/src/linker/strlcpy.c b/src/linker/strlcpy.c
new file mode 100644
index 0000000..e0fd250
--- /dev/null
+++ b/src/linker/strlcpy.c
@@ -0,0 +1,50 @@
+/* $OpenBSD: strlcpy.c,v 1.11 2006/05/05 15:27:38 millert Exp $ */
+
+/*
+ * Copyright (c) 1998 Todd C. Miller <Todd.Miller@courtesan.com>
+ *
+ * Permission to use, copy, modify, and distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#include "strlcpy.h"
+
+/*
+ * Copy src to string dst of size siz. At most siz-1 characters
+ * will be copied. Always NUL terminates (unless siz == 0).
+ * Returns strlen(src); if retval >= siz, truncation occurred.
+ */
+size_t
+apkenv_strlcpy(char *dst, const char *src, size_t siz)
+{
+ char *d = dst;
+ const char *s = src;
+ size_t n = siz;
+
+ /* Copy as many bytes as will fit */
+ if (n != 0) {
+ while (--n != 0) {
+ if ((*d++ = *s++) == '\0')
+ break;
+ }
+ }
+
+ /* Not enough room in dst, add NUL and traverse rest of src */
+ if (n == 0) {
+ if (siz != 0)
+ *d = '\0'; /* NUL-terminate dst */
+ while (*s++)
+ ;
+ }
+
+ return(s - src - 1); /* count does not include NUL */
+}
diff --git a/src/linker/strlcpy.h b/src/linker/strlcpy.h
new file mode 100644
index 0000000..a524530
--- /dev/null
+++ b/src/linker/strlcpy.h
@@ -0,0 +1,10 @@
+#ifndef STRLCPY_H
+#define STRLCPY_H
+
+#include <sys/types.h>
+#include <string.h>
+
+size_t
+apkenv_strlcpy(char *dst, const char *src, size_t siz);
+
+#endif