• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #if defined(ART_TARGET_ANDROID)
18 
19 #include "native_loader_test.h"
20 
21 #include <dlfcn.h>
22 
23 #include <android-base/strings.h>
24 #include <gtest/gtest.h>
25 
26 #include "nativehelper/scoped_utf_chars.h"
27 #include "nativeloader/native_loader.h"
28 #include "public_libraries.h"
29 
30 namespace android {
31 namespace nativeloader {
32 
33 using ::testing::Eq;
34 using ::testing::NotNull;
35 using ::testing::StartsWith;
36 using ::testing::StrEq;
37 using internal::ConfigEntry;  // NOLINT - ConfigEntry is actually used
38 using internal::ParseApexLibrariesConfig;
39 using internal::ParseConfig;
40 
41 #if defined(__LP64__)
42 #define LIB_DIR "lib64"
43 #else
44 #define LIB_DIR "lib"
45 #endif
46 
47 static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
48 
49 // Custom matcher for comparing namespace handles
50 MATCHER_P(NsEq, other, "") {
51   *result_listener << "comparing " << reinterpret_cast<const char*>(arg) << " and " << other;
52   return strcmp(reinterpret_cast<const char*>(arg), reinterpret_cast<const char*>(other)) == 0;
53 }
54 
55 /////////////////////////////////////////////////////////////////
56 
57 // Test fixture
58 class NativeLoaderTest : public ::testing::TestWithParam<bool> {
59  protected:
IsBridged()60   bool IsBridged() { return GetParam(); }
61 
SetUp()62   void SetUp() override {
63     mock = std::make_unique<testing::NiceMock<MockPlatform>>(IsBridged());
64 
65     env = std::make_unique<JNIEnv>();
66     env->functions = CreateJNINativeInterface();
67   }
68 
SetExpectations()69   void SetExpectations() {
70     std::vector<std::string> default_public_libs =
71         android::base::Split(preloadable_public_libraries(), ":");
72     for (const std::string& l : default_public_libs) {
73       EXPECT_CALL(*mock,
74                   mock_dlopen_ext(false, StrEq(l.c_str()), RTLD_NOW | RTLD_NODELETE, NotNull()))
75           .WillOnce(Return(any_nonnull));
76     }
77   }
78 
RunTest()79   void RunTest() { InitializeNativeLoader(); }
80 
TearDown()81   void TearDown() override {
82     ResetNativeLoader();
83     delete env->functions;
84     mock.reset();
85   }
86 
87   std::unique_ptr<JNIEnv> env;
88 };
89 
90 /////////////////////////////////////////////////////////////////
91 
TEST_P(NativeLoaderTest,InitializeLoadsDefaultPublicLibraries)92 TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
93   SetExpectations();
94   RunTest();
95 }
96 
TEST_P(NativeLoaderTest,OpenNativeLibraryWithoutClassloaderInApex)97 TEST_P(NativeLoaderTest, OpenNativeLibraryWithoutClassloaderInApex) {
98   const char* test_lib_path = "libfoo.so";
99   void* fake_handle = &fake_handle;  // Arbitrary non-null value
100   EXPECT_CALL(*mock,
101               mock_dlopen_ext(false, StrEq(test_lib_path), RTLD_NOW, NsEq("com_android_art")))
102       .WillOnce(Return(fake_handle));
103 
104   bool needs_native_bridge = false;
105   char* errmsg = nullptr;
106   EXPECT_EQ(fake_handle,
107             OpenNativeLibrary(env.get(),
108                               /*target_sdk_version=*/17,
109                               test_lib_path,
110                               /*class_loader=*/nullptr,
111                               /*caller_location=*/"/apex/com.android.art/javalib/myloadinglib.jar",
112                               /*library_path=*/nullptr,
113                               &needs_native_bridge,
114                               &errmsg));
115   // OpenNativeLibrary never uses nativebridge when there's no classloader. That
116   // should maybe change.
117   EXPECT_EQ(needs_native_bridge, false);
118   EXPECT_EQ(errmsg, nullptr);
119 }
120 
TEST_P(NativeLoaderTest,OpenNativeLibraryWithoutClassloaderInFramework)121 TEST_P(NativeLoaderTest, OpenNativeLibraryWithoutClassloaderInFramework) {
122   const char* test_lib_path = "libfoo.so";
123   void* fake_handle = &fake_handle;  // Arbitrary non-null value
124   EXPECT_CALL(*mock, mock_dlopen_ext(false, StrEq(test_lib_path), RTLD_NOW, NsEq("system")))
125       .WillOnce(Return(fake_handle));
126 
127   bool needs_native_bridge = false;
128   char* errmsg = nullptr;
129   EXPECT_EQ(fake_handle,
130             OpenNativeLibrary(env.get(),
131                               /*target_sdk_version=*/17,
132                               test_lib_path,
133                               /*class_loader=*/nullptr,
134                               /*caller_location=*/"/system/framework/framework.jar!classes1.dex",
135                               /*library_path=*/nullptr,
136                               &needs_native_bridge,
137                               &errmsg));
138   // OpenNativeLibrary never uses nativebridge when there's no classloader. That
139   // should maybe change.
140   EXPECT_EQ(needs_native_bridge, false);
141   EXPECT_EQ(errmsg, nullptr);
142 }
143 
TEST_P(NativeLoaderTest,OpenNativeLibraryWithoutClassloaderAndCallerLocation)144 TEST_P(NativeLoaderTest, OpenNativeLibraryWithoutClassloaderAndCallerLocation) {
145   const char* test_lib_path = "libfoo.so";
146   void* fake_handle = &fake_handle;  // Arbitrary non-null value
147   EXPECT_CALL(*mock, mock_dlopen_ext(false, StrEq(test_lib_path), RTLD_NOW, NsEq("system")))
148       .WillOnce(Return(fake_handle));
149 
150   bool needs_native_bridge = false;
151   char* errmsg = nullptr;
152   EXPECT_EQ(fake_handle,
153             OpenNativeLibrary(env.get(),
154                               /*target_sdk_version=*/17,
155                               test_lib_path,
156                               /*class_loader=*/nullptr,
157                               /*caller_location=*/nullptr,
158                               /*library_path=*/nullptr,
159                               &needs_native_bridge,
160                               &errmsg));
161   // OpenNativeLibrary never uses nativebridge when there's no classloader. That
162   // should maybe change.
163   EXPECT_EQ(needs_native_bridge, false);
164   EXPECT_EQ(errmsg, nullptr);
165 }
166 
167 INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
168 
169 /////////////////////////////////////////////////////////////////
170 
append_extended_libraries(const std::string & libs)171 std::string append_extended_libraries(const std::string& libs) {
172   const std::string& ext_libs = extended_public_libraries();
173   if (!ext_libs.empty()) {
174     return libs + ":" + ext_libs;
175   }
176   return libs;
177 }
178 
default_public_and_extended_libraries()179 std::string default_public_and_extended_libraries() {
180   return append_extended_libraries(default_public_libraries());
181 }
182 
183 class NativeLoaderTest_Create : public NativeLoaderTest {
184  protected:
185   // Test inputs (initialized to the default values). Overriding these
186   // must be done before calling SetExpectations() and RunTest().
187   uint32_t target_sdk_version = 29;
188   std::string class_loader = "my_classloader";
189   bool is_shared = false;
190   std::string dex_path = "/data/app/foo/classes.dex";
191   std::string library_path = "/data/app/foo/" LIB_DIR "/arm";
192   std::string permitted_path = "/data/app/foo/" LIB_DIR;
193 
194   // expected output (.. for the default test inputs)
195   std::string expected_namespace_prefix = "clns";
196   uint64_t expected_namespace_flags =
197       ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS;
198   std::string expected_library_path = library_path;
199   std::string expected_permitted_path = std::string("/data:/mnt/expand:") + permitted_path;
200   std::string expected_parent_namespace = "system";
201   bool expected_link_with_platform_ns = true;
202   bool expected_link_with_art_ns = true;
203   bool expected_link_with_i18n_ns = true;
204   bool expected_link_with_conscrypt_ns = false;
205   bool expected_link_with_sphal_ns = !vendor_public_libraries().empty();
206   bool expected_link_with_product_ns = !product_public_libraries().empty();
207   bool expected_link_with_vndk_ns = false;
208   bool expected_link_with_vndk_product_ns = false;
209   bool expected_link_with_default_ns = false;
210   bool expected_link_with_neuralnetworks_ns = true;
211   std::string expected_shared_libs_to_platform_ns = default_public_and_extended_libraries();
212   std::string expected_shared_libs_to_art_ns = apex_public_libraries().at("com_android_art");
213   std::string expected_shared_libs_to_i18n_ns = apex_public_libraries().at("com_android_i18n");
214   std::string expected_shared_libs_to_conscrypt_ns = apex_jni_libraries("com_android_conscrypt");
215   std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
216   std::string expected_shared_libs_to_product_ns = product_public_libraries();
217   std::string expected_shared_libs_to_vndk_ns = vndksp_libraries_vendor();
218   std::string expected_shared_libs_to_vndk_product_ns = vndksp_libraries_product();
219   std::string expected_shared_libs_to_default_ns = default_public_and_extended_libraries();
220   std::string expected_shared_libs_to_neuralnetworks_ns = apex_public_libraries().at("com_android_neuralnetworks");
221 
SetExpectations()222   void SetExpectations() {
223     NativeLoaderTest::SetExpectations();
224 
225     ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
226 
227     EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(testing::AnyNumber());
228     EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(testing::AnyNumber());
229 
230     EXPECT_CALL(*mock, mock_create_namespace(
231                            Eq(IsBridged()), StartsWith(expected_namespace_prefix + "-"), nullptr,
232                            StrEq(expected_library_path), expected_namespace_flags,
233                            StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
234         .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
235     if (expected_link_with_platform_ns) {
236       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("system"),
237                                               StrEq(expected_shared_libs_to_platform_ns)))
238           .WillOnce(Return(true));
239     }
240     if (expected_link_with_art_ns) {
241       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_art"),
242                                               StrEq(expected_shared_libs_to_art_ns)))
243           .WillOnce(Return(true));
244     }
245     if (expected_link_with_i18n_ns) {
246       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_i18n"),
247                                               StrEq(expected_shared_libs_to_i18n_ns)))
248           .WillOnce(Return(true));
249     }
250     if (expected_link_with_sphal_ns) {
251       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
252                                               StrEq(expected_shared_libs_to_sphal_ns)))
253           .WillOnce(Return(true));
254     }
255     if (expected_link_with_product_ns) {
256       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("product"),
257                                               StrEq(expected_shared_libs_to_product_ns)))
258           .WillOnce(Return(true));
259     }
260     if (expected_link_with_vndk_ns) {
261       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
262                                               StrEq(expected_shared_libs_to_vndk_ns)))
263           .WillOnce(Return(true));
264     }
265     if (expected_link_with_vndk_product_ns) {
266       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk_product"),
267                                               StrEq(expected_shared_libs_to_vndk_product_ns)))
268           .WillOnce(Return(true));
269     }
270     if (expected_link_with_default_ns) {
271       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
272                                               StrEq(expected_shared_libs_to_default_ns)))
273           .WillOnce(Return(true));
274     }
275     if (expected_link_with_neuralnetworks_ns) {
276       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_neuralnetworks"),
277                                               StrEq(expected_shared_libs_to_neuralnetworks_ns)))
278           .WillOnce(Return(true));
279     }
280     if (expected_link_with_conscrypt_ns) {
281       EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_conscrypt"),
282                                               StrEq(expected_shared_libs_to_conscrypt_ns)))
283           .WillOnce(Return(true));
284     }
285   }
286 
RunTest()287   void RunTest() {
288     NativeLoaderTest::RunTest();
289 
290     jstring err = CreateClassLoaderNamespace(
291         env(), target_sdk_version, env()->NewStringUTF(class_loader.c_str()), is_shared,
292         env()->NewStringUTF(dex_path.c_str()), env()->NewStringUTF(library_path.c_str()),
293         env()->NewStringUTF(permitted_path.c_str()), /*uses_library_list=*/ nullptr);
294 
295     // no error
296     EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
297 
298     if (!IsBridged()) {
299       struct android_namespace_t* ns =
300           FindNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
301 
302       // The created namespace is for this apk
303       EXPECT_EQ(dex_path.c_str(), reinterpret_cast<const char*>(ns));
304     } else {
305       struct NativeLoaderNamespace* ns =
306           FindNativeLoaderNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
307 
308       // The created namespace is for the this apk
309       EXPECT_STREQ(dex_path.c_str(),
310                    reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
311     }
312   }
313 
env()314   JNIEnv* env() { return NativeLoaderTest::env.get(); }
315 };
316 
TEST_P(NativeLoaderTest_Create,DownloadedApp)317 TEST_P(NativeLoaderTest_Create, DownloadedApp) {
318   SetExpectations();
319   RunTest();
320 }
321 
TEST_P(NativeLoaderTest_Create,BundledSystemApp)322 TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
323   dex_path = "/system/app/foo/foo.apk";
324   is_shared = true;
325 
326   expected_namespace_prefix = "clns-shared";
327   expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
328   SetExpectations();
329   RunTest();
330 }
331 
TEST_P(NativeLoaderTest_Create,BundledVendorApp)332 TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
333   dex_path = "/vendor/app/foo/foo.apk";
334   is_shared = true;
335 
336   expected_namespace_prefix = "clns-shared";
337   expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
338   SetExpectations();
339   RunTest();
340 }
341 
TEST_P(NativeLoaderTest_Create,UnbundledVendorApp)342 TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
343   dex_path = "/vendor/app/foo/foo.apk";
344   is_shared = false;
345 
346   expected_namespace_prefix = "vendor-clns";
347   expected_library_path = expected_library_path + ":/vendor/" LIB_DIR;
348   expected_permitted_path = expected_permitted_path + ":/vendor/" LIB_DIR;
349   expected_shared_libs_to_platform_ns =
350       default_public_libraries() + ":" + llndk_libraries_vendor();
351   expected_link_with_vndk_ns = true;
352   SetExpectations();
353   RunTest();
354 }
355 
TEST_P(NativeLoaderTest_Create,BundledProductApp)356 TEST_P(NativeLoaderTest_Create, BundledProductApp) {
357   dex_path = "/product/app/foo/foo.apk";
358   is_shared = true;
359 
360   expected_namespace_prefix = "clns-shared";
361   expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
362   SetExpectations();
363   RunTest();
364 }
365 
TEST_P(NativeLoaderTest_Create,SystemServerWithApexJars)366 TEST_P(NativeLoaderTest_Create, SystemServerWithApexJars) {
367   dex_path = "/system/framework/services.jar:/apex/com.android.conscrypt/javalib/service-foo.jar";
368   is_shared = true;
369 
370   expected_namespace_prefix = "clns-shared";
371   expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
372   expected_link_with_conscrypt_ns = true;
373   SetExpectations();
374   RunTest();
375 }
376 
TEST_P(NativeLoaderTest_Create,UnbundledProductApp)377 TEST_P(NativeLoaderTest_Create, UnbundledProductApp) {
378   dex_path = "/product/app/foo/foo.apk";
379   is_shared = false;
380 
381   if (is_product_vndk_version_defined()) {
382     expected_namespace_prefix = "product-clns";
383     expected_library_path = expected_library_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
384     expected_permitted_path =
385         expected_permitted_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
386     expected_shared_libs_to_platform_ns =
387         append_extended_libraries(default_public_libraries() + ":" + llndk_libraries_product());
388     expected_link_with_vndk_product_ns = true;
389   }
390   SetExpectations();
391   RunTest();
392 }
393 
TEST_P(NativeLoaderTest_Create,NamespaceForSharedLibIsNotUsedAsAnonymousNamespace)394 TEST_P(NativeLoaderTest_Create, NamespaceForSharedLibIsNotUsedAsAnonymousNamespace) {
395   if (IsBridged()) {
396     // There is no shared lib in translated arch
397     // TODO(jiyong): revisit this
398     return;
399   }
400   // compared to apks, for java shared libs, library_path is empty; java shared
401   // libs don't have their own native libs. They use platform's.
402   library_path = "";
403   expected_library_path = library_path;
404   // no ALSO_USED_AS_ANONYMOUS
405   expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
406   SetExpectations();
407   RunTest();
408 }
409 
TEST_P(NativeLoaderTest_Create,TwoApks)410 TEST_P(NativeLoaderTest_Create, TwoApks) {
411   SetExpectations();
412   const uint32_t second_app_target_sdk_version = 29;
413   const std::string second_app_class_loader = "second_app_classloader";
414   const bool second_app_is_shared = false;
415   const std::string second_app_dex_path = "/data/app/bar/classes.dex";
416   const std::string second_app_library_path = "/data/app/bar/" LIB_DIR "/arm";
417   const std::string second_app_permitted_path = "/data/app/bar/" LIB_DIR;
418   const std::string expected_second_app_permitted_path =
419       std::string("/data:/mnt/expand:") + second_app_permitted_path;
420   const std::string expected_second_app_parent_namespace = "clns";
421   // no ALSO_USED_AS_ANONYMOUS
422   const uint64_t expected_second_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
423 
424   // The scenario is that second app is loaded by the first app.
425   // So the first app's classloader (`classloader`) is parent of the second
426   // app's classloader.
427   ON_CALL(*mock, JniObject_getParent(StrEq(second_app_class_loader)))
428       .WillByDefault(Return(class_loader.c_str()));
429 
430   // namespace for the second app is created. Its parent is set to the namespace
431   // of the first app.
432   EXPECT_CALL(*mock, mock_create_namespace(
433                          Eq(IsBridged()), StartsWith(expected_namespace_prefix + "-"), nullptr,
434                          StrEq(second_app_library_path), expected_second_namespace_flags,
435                          StrEq(expected_second_app_permitted_path), NsEq(dex_path.c_str())))
436       .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(second_app_dex_path.c_str()))));
437   EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), NsEq(second_app_dex_path.c_str()), _, _))
438       .WillRepeatedly(Return(true));
439 
440   RunTest();
441   jstring err = CreateClassLoaderNamespace(
442       env(), second_app_target_sdk_version, env()->NewStringUTF(second_app_class_loader.c_str()),
443       second_app_is_shared, env()->NewStringUTF(second_app_dex_path.c_str()),
444       env()->NewStringUTF(second_app_library_path.c_str()),
445       env()->NewStringUTF(second_app_permitted_path.c_str()), /*uses_library_list=*/ nullptr);
446 
447   // success
448   EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
449 
450   if (!IsBridged()) {
451     struct android_namespace_t* ns =
452         FindNamespaceByClassLoader(env(), env()->NewStringUTF(second_app_class_loader.c_str()));
453 
454     // The created namespace is for the second apk
455     EXPECT_EQ(second_app_dex_path.c_str(), reinterpret_cast<const char*>(ns));
456   } else {
457     struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
458         env(), env()->NewStringUTF(second_app_class_loader.c_str()));
459 
460     // The created namespace is for the second apk
461     EXPECT_STREQ(second_app_dex_path.c_str(),
462                  reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
463   }
464 }
465 
466 INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
467 
468 const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
__anon6ff7c58b0102(const struct ConfigEntry&) 469     [](const struct ConfigEntry&) -> Result<bool> { return true; };
470 
TEST(NativeLoaderConfigParser,NamesAndComments)471 TEST(NativeLoaderConfigParser, NamesAndComments) {
472   const char file_content[] = R"(
473 ######
474 
475 libA.so
476 #libB.so
477 
478 
479       libC.so
480 libD.so
481     #### libE.so
482 )";
483   const std::vector<std::string> expected_result = {"libA.so", "libC.so", "libD.so"};
484   Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
485   ASSERT_RESULT_OK(result);
486   ASSERT_EQ(expected_result, *result);
487 }
488 
TEST(NativeLoaderConfigParser,WithBitness)489 TEST(NativeLoaderConfigParser, WithBitness) {
490   const char file_content[] = R"(
491 libA.so 32
492 libB.so 64
493 libC.so
494 )";
495 #if defined(__LP64__)
496   const std::vector<std::string> expected_result = {"libB.so", "libC.so"};
497 #else
498   const std::vector<std::string> expected_result = {"libA.so", "libC.so"};
499 #endif
500   Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
501   ASSERT_RESULT_OK(result);
502   ASSERT_EQ(expected_result, *result);
503 }
504 
TEST(NativeLoaderConfigParser,WithNoPreload)505 TEST(NativeLoaderConfigParser, WithNoPreload) {
506   const char file_content[] = R"(
507 libA.so nopreload
508 libB.so nopreload
509 libC.so
510 )";
511 
512   const std::vector<std::string> expected_result = {"libC.so"};
513   Result<std::vector<std::string>> result =
514       ParseConfig(file_content,
515                   [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
516   ASSERT_RESULT_OK(result);
517   ASSERT_EQ(expected_result, *result);
518 }
519 
TEST(NativeLoaderConfigParser,WithNoPreloadAndBitness)520 TEST(NativeLoaderConfigParser, WithNoPreloadAndBitness) {
521   const char file_content[] = R"(
522 libA.so nopreload 32
523 libB.so 64 nopreload
524 libC.so 32
525 libD.so 64
526 libE.so nopreload
527 )";
528 
529 #if defined(__LP64__)
530   const std::vector<std::string> expected_result = {"libD.so"};
531 #else
532   const std::vector<std::string> expected_result = {"libC.so"};
533 #endif
534   Result<std::vector<std::string>> result =
535       ParseConfig(file_content,
536                   [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
537   ASSERT_RESULT_OK(result);
538   ASSERT_EQ(expected_result, *result);
539 }
540 
TEST(NativeLoaderConfigParser,RejectMalformed)541 TEST(NativeLoaderConfigParser, RejectMalformed) {
542   ASSERT_FALSE(ParseConfig("libA.so 32 64", always_true).ok());
543   ASSERT_FALSE(ParseConfig("libA.so 32 32", always_true).ok());
544   ASSERT_FALSE(ParseConfig("libA.so 32 nopreload 64", always_true).ok());
545   ASSERT_FALSE(ParseConfig("32 libA.so nopreload", always_true).ok());
546   ASSERT_FALSE(ParseConfig("nopreload libA.so 32", always_true).ok());
547   ASSERT_FALSE(ParseConfig("libA.so nopreload # comment", always_true).ok());
548 }
549 
TEST(NativeLoaderApexLibrariesConfigParser,BasicLoading)550 TEST(NativeLoaderApexLibrariesConfigParser, BasicLoading) {
551   const char file_content[] = R"(
552 # comment
553 jni com_android_foo libfoo.so
554 # Empty line is ignored
555 
556 jni com_android_bar libbar.so:libbar2.so
557 
558   public com_android_bar libpublic.so
559 )";
560 
561   auto jni_libs = ParseApexLibrariesConfig(file_content, "jni");
562   ASSERT_RESULT_OK(jni_libs);
563   std::map<std::string, std::string> expected_jni_libs {
564     {"com_android_foo", "libfoo.so"},
565     {"com_android_bar", "libbar.so:libbar2.so"},
566   };
567   ASSERT_EQ(expected_jni_libs, *jni_libs);
568 
569   auto public_libs = ParseApexLibrariesConfig(file_content, "public");
570   ASSERT_RESULT_OK(public_libs);
571   std::map<std::string, std::string> expected_public_libs {
572     {"com_android_bar", "libpublic.so"},
573   };
574   ASSERT_EQ(expected_public_libs, *public_libs);
575 }
576 
TEST(NativeLoaderApexLibrariesConfigParser,RejectMalformedLine)577 TEST(NativeLoaderApexLibrariesConfigParser, RejectMalformedLine) {
578   const char file_content[] = R"(
579 jni com_android_foo libfoo
580 # missing <library list>
581 jni com_android_bar
582 )";
583   auto result = ParseApexLibrariesConfig(file_content, "jni");
584   ASSERT_FALSE(result.ok());
585   ASSERT_EQ("Malformed line \"jni com_android_bar\"", result.error().message());
586 }
587 
TEST(NativeLoaderApexLibrariesConfigParser,RejectInvalidTag)588 TEST(NativeLoaderApexLibrariesConfigParser, RejectInvalidTag) {
589   const char file_content[] = R"(
590 jni apex1 lib
591 public apex2 lib
592 # unknown tag
593 unknown com_android_foo libfoo
594 )";
595   auto result = ParseApexLibrariesConfig(file_content, "jni");
596   ASSERT_FALSE(result.ok());
597   ASSERT_EQ("Invalid tag \"unknown com_android_foo libfoo\"", result.error().message());
598 }
599 
TEST(NativeLoaderApexLibrariesConfigParser,RejectInvalidApexNamespace)600 TEST(NativeLoaderApexLibrariesConfigParser, RejectInvalidApexNamespace) {
601   const char file_content[] = R"(
602 # apex linker namespace should be mangled ('.' -> '_')
603 jni com.android.foo lib
604 )";
605   auto result = ParseApexLibrariesConfig(file_content, "jni");
606   ASSERT_FALSE(result.ok());
607   ASSERT_EQ("Invalid apex_namespace \"jni com.android.foo lib\"", result.error().message());
608 }
609 
TEST(NativeLoaderApexLibrariesConfigParser,RejectInvalidLibraryList)610 TEST(NativeLoaderApexLibrariesConfigParser, RejectInvalidLibraryList) {
611   const char file_content[] = R"(
612 # library list is ":" separated list of filenames
613 jni com_android_foo lib64/libfoo.so
614 )";
615   auto result = ParseApexLibrariesConfig(file_content, "jni");
616   ASSERT_FALSE(result.ok());
617   ASSERT_EQ("Invalid library_list \"jni com_android_foo lib64/libfoo.so\"", result.error().message());
618 }
619 
620 }  // namespace nativeloader
621 }  // namespace android
622 
623 #endif  // defined(ART_TARGET_ANDROID)
624