Fix CFI initialization crash on x86.

Third try.

Bug: 34752378
Test: bionic tests
Change-Id: I247c127489a8ee38404e104f28d916a704e35f36
diff --git a/tests/cfi_test.cpp b/tests/cfi_test.cpp
index 0f93edb..5e627a7 100644
--- a/tests/cfi_test.cpp
+++ b/tests/cfi_test.cpp
@@ -1,7 +1,26 @@
-#include <gtest/gtest.h>
+/*
+ * Copyright (C) 2017 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 <gtest/gtest.h>
+#include <sys/stat.h>
 
 #include "BionicDeathTest.h"
+#include "gtest_globals.h"
+#include "utils.h"
 
 // Private libdl interface.
 extern "C" {
@@ -12,6 +31,7 @@
 static void f() {}
 
 TEST(cfi_test, basic) {
+#if defined(__BIONIC__)
   void* handle;
   handle = dlopen("libcfi-test.so", RTLD_NOW | RTLD_LOCAL);
   ASSERT_TRUE(handle != nullptr) << dlerror();
@@ -82,13 +102,39 @@
   // CFI check for a function inside the unloaded DSO. This is always invalid and gets the process
   // killed.
   EXPECT_DEATH(__cfi_slowpath(45, reinterpret_cast<void*>(code_ptr)), "");
+#endif
 }
 
 TEST(cfi_test, invalid) {
+#if defined(__BIONIC__)
   void* handle;
   handle = dlopen("libcfi-test-bad.so", RTLD_NOW | RTLD_LOCAL);
   ASSERT_FALSE(handle != nullptr) << dlerror();
 
   handle = dlopen("libcfi-test-bad.so", RTLD_NOW | RTLD_LOCAL);
   ASSERT_FALSE(handle != nullptr) << dlerror();
+#endif
+}
+
+// cfi_test_helper exports __cfi_check, which triggers CFI initialization at startup.
+TEST(cfi_test, early_init) {
+#if defined(__BIONIC__)
+  std::string helper = get_testlib_root() + "/cfi_test_helper/cfi_test_helper";
+  chmod(helper.c_str(), 0755); // TODO: "x" lost in CTS, b/34945607
+  ExecTestHelper eth;
+  eth.SetArgs({ helper.c_str(), nullptr });
+  eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
+#endif
+}
+
+// cfi_test_helper2 depends on a library that exports __cfi_check, which triggers CFI initialization
+// at startup.
+TEST(cfi_test, early_init2) {
+#if defined(__BIONIC__)
+  std::string helper = get_testlib_root() + "/cfi_test_helper2/cfi_test_helper2";
+  chmod(helper.c_str(), 0755); // TODO: "x" lost in CTS, b/34945607
+  ExecTestHelper eth;
+  eth.SetArgs({ helper.c_str(), nullptr });
+  eth.Run([&]() { execve(helper.c_str(), eth.GetArgs(), eth.GetEnv()); }, 0, nullptr);
+#endif
 }