Fix dlsym(handle_of_main_executable, ...)

  According to man dlopen(3) and posix docs in the case when si is handle
  of the main executable we need to search not only in the executable and its
  dependencies but also in all libraries loaded with RTLD_GLOBAL.

  see also: http://pubs.opengroup.org/onlinepubs/9699919799/functions/dlopen.html

Bug: http://b/21528224
Bug: http://b/17512583
Bug: https://code.google.com/p/android/issues/detail?id=173822
Change-Id: Ib2801367ba48b6f3704da89a6d9f5e6911430013
diff --git a/linker/linker.cpp b/linker/linker.cpp
index 531cd19..1382a9c 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -948,6 +948,17 @@
 // This is used by dlsym(3).  It performs symbol lookup only within the
 // specified soinfo object and its dependencies in breadth first order.
 const ElfW(Sym)* dlsym_handle_lookup(soinfo* si, soinfo** found, const char* name) {
+  // According to man dlopen(3) and posix docs in the case when si is handle
+  // of the main executable we need to search not only in the executable and its
+  // dependencies but also in all libraries loaded with RTLD_GLOBAL.
+  //
+  // Since RTLD_GLOBAL is always set for the main executable and all dt_needed shared
+  // libraries and they are loaded in breath-first (correct) order we can just execute
+  // dlsym(RTLD_DEFAULT, ...); instead of doing two stage lookup.
+  if (si == somain) {
+    return dlsym_linear_lookup(name, found, nullptr, RTLD_DEFAULT);
+  }
+
   SymbolName symbol_name(name);
   return dlsym_handle_lookup(si, nullptr, found, symbol_name);
 }