loader: fix d-tor call order

In the case when there are multiple dependencies on
the same library in the local_group the unload may
in some situations (covered now by tests) result
calling d-tors for some libraries prematurely.

In order to have correct call order loader checks if this
is last dependency in local group before adding it to BFS
queue.

Bug: http://b/35201832
Test: bionic-unit-tests --gtest_filter=dl*:Dl*
Test: bionic-unit-tests-glibc --gtest_filter=dl*
Change-Id: I4c6955b9032acc7147a51d9f09b61d9e0818700c
diff --git a/linker/linker.cpp b/linker/linker.cpp
index 522d5dc..ece6187 100644
--- a/linker/linker.cpp
+++ b/linker/linker.cpp
@@ -1661,12 +1661,14 @@
         TRACE("%s@%p needs to unload %s@%p", si->get_realpath(), si,
             child->get_realpath(), child);
 
+        child->get_parents().remove(si);
+
         if (local_unload_list.contains(child)) {
           continue;
         } else if (child->is_linked() && child->get_local_group_root() != root) {
           external_unload_list.push_back(child);
-        } else {
-          unload_list.push_front(child);
+        } else if (child->get_parents().empty()) {
+          unload_list.push_back(child);
         }
       }
     } else {