Do proper cleanup of static block.

The static initializer of each HAL library adds
entries to global maps in a different static library,
but it never deletes them. This causes problems if
the HAL library is ever unloaded later, because the
map will be pointing to entries that no longer exist.

To fix this, switch to using __attribute__((constructor))
and ((destructor)), so we will clean up when we need to.

Bug: 34950358
Test: drm_hidl_test, hidl_test
Change-Id: If81b9712a651a07390fcc6641d86a77bb7a03f7c
diff --git a/generateCpp.cpp b/generateCpp.cpp
index 1a2b45b..6dcd3ca 100644
--- a/generateCpp.cpp
+++ b/generateCpp.cpp
@@ -438,8 +438,6 @@
         } else {
             declareServiceManagerInteractions(out, iface->localName());
         }
-
-        out << "private: static int hidlStaticBlock;\n";
     }
 
     if (isInterface) {
@@ -1011,10 +1009,8 @@
             << "::descriptor(\""
             << iface->fqName().string()
             << "\");\n\n";
-
-        out << "int "
-            << iface->localName()
-            << "::hidlStaticBlock = []() -> int {\n";
+        out << "__attribute__((constructor))";
+        out << "static void static_constructor() {\n";
         out.indent([&] {
             out << "::android::hardware::gBnConstructorMap["
                 << iface->localName()
@@ -1046,9 +1042,19 @@
                 });
                 out << "};\n";
             });
-            out << "return 1;\n";
         });
-        out << "}();\n\n";
+        out << "};\n\n";
+        out << "__attribute__((destructor))";
+        out << "static void static_destructor() {\n";
+        out.indent([&] {
+            out << "::android::hardware::gBnConstructorMap.erase("
+                << iface->localName()
+                << "::descriptor);\n";
+            out << "::android::hardware::gBsConstructorMap.erase("
+                << iface->localName()
+                << "::descriptor);\n";
+        });
+        out << "};\n\n";
 
         err = generateInterfaceSource(out);
     }