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 #include <dlfcn.h>
18 #include <memory>
19 #include <unordered_map>
20
21 #include <android-base/strings.h>
22 #include <gmock/gmock.h>
23 #include <gtest/gtest.h>
24 #include <jni.h>
25
26 #include "native_loader_namespace.h"
27 #include "nativehelper/scoped_utf_chars.h"
28 #include "nativeloader/dlext_namespaces.h"
29 #include "nativeloader/native_loader.h"
30 #include "public_libraries.h"
31
32 namespace android {
33 namespace nativeloader {
34
35 using ::testing::Eq;
36 using ::testing::Return;
37 using ::testing::StrEq;
38 using ::testing::_;
39 using internal::ConfigEntry;
40 using internal::ParseConfig;
41
42 #if defined(__LP64__)
43 #define LIB_DIR "lib64"
44 #else
45 #define LIB_DIR "lib"
46 #endif
47
48 // gmock interface that represents interested platform APIs on libdl and libnativebridge
49 class Platform {
50 public:
~Platform()51 virtual ~Platform() {}
52
53 // libdl APIs
54 virtual void* dlopen(const char* filename, int flags) = 0;
55 virtual int dlclose(void* handle) = 0;
56 virtual char* dlerror(void) = 0;
57
58 // These mock_* are the APIs semantically the same across libdl and libnativebridge.
59 // Instead of having two set of mock APIs for the two, define only one set with an additional
60 // argument 'bool bridged' to identify the context (i.e., called for libdl or libnativebridge).
61 typedef char* mock_namespace_handle;
62 virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
63 const char* search_paths) = 0;
64 virtual mock_namespace_handle mock_create_namespace(
65 bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
66 uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
67 virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
68 mock_namespace_handle to, const char* sonames) = 0;
69 virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
70 virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
71 mock_namespace_handle ns) = 0;
72
73 // libnativebridge APIs for which libdl has no corresponding APIs
74 virtual bool NativeBridgeInitialized() = 0;
75 virtual const char* NativeBridgeGetError() = 0;
76 virtual bool NativeBridgeIsPathSupported(const char*) = 0;
77 virtual bool NativeBridgeIsSupported(const char*) = 0;
78
79 // To mock "ClassLoader Object.getParent()"
80 virtual const char* JniObject_getParent(const char*) = 0;
81 };
82
83 // The mock does not actually create a namespace object. But simply casts the pointer to the
84 // string for the namespace name as the handle to the namespace object.
85 #define TO_ANDROID_NAMESPACE(str) \
86 reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
87
88 #define TO_BRIDGED_NAMESPACE(str) \
89 reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
90
91 #define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
92
93 // These represents built-in namespaces created by the linker according to ld.config.txt
94 static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
95 {"system", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("system"))},
96 {"default", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("default"))},
97 {"com_android_art", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_art"))},
98 {"sphal", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("sphal"))},
99 {"vndk", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk"))},
100 {"vndk_product", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk_product"))},
101 {"com_android_neuralnetworks", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_neuralnetworks"))},
102 {"com_android_os_statsd", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_os_statsd"))},
103 };
104
105 // The actual gmock object
106 class MockPlatform : public Platform {
107 public:
MockPlatform(bool is_bridged)108 explicit MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
109 ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
110 ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
111 ON_CALL(*this, mock_get_exported_namespace(_, _))
112 .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
113 if (namespaces.find(name) != namespaces.end()) {
114 return namespaces[name];
115 }
116 return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("(namespace not found"));
117 }));
118 }
119
120 // Mocking libdl APIs
121 MOCK_METHOD2(dlopen, void*(const char*, int));
122 MOCK_METHOD1(dlclose, int(void*));
123 MOCK_METHOD0(dlerror, char*());
124
125 // Mocking the common APIs
126 MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
127 MOCK_METHOD7(mock_create_namespace,
128 mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
129 const char*, mock_namespace_handle));
130 MOCK_METHOD4(mock_link_namespaces,
131 bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
132 MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
133 MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
134
135 // Mocking libnativebridge APIs
136 MOCK_METHOD0(NativeBridgeInitialized, bool());
137 MOCK_METHOD0(NativeBridgeGetError, const char*());
138 MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
139 MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
140
141 // Mocking "ClassLoader Object.getParent()"
142 MOCK_METHOD1(JniObject_getParent, const char*(const char*));
143
144 private:
145 bool is_bridged_;
146 };
147
148 static std::unique_ptr<MockPlatform> mock;
149
150 // Provide C wrappers for the mock object.
151 extern "C" {
dlopen(const char * file,int flag)152 void* dlopen(const char* file, int flag) {
153 return mock->dlopen(file, flag);
154 }
155
dlclose(void * handle)156 int dlclose(void* handle) {
157 return mock->dlclose(handle);
158 }
159
dlerror(void)160 char* dlerror(void) {
161 return mock->dlerror();
162 }
163
android_init_anonymous_namespace(const char * sonames,const char * search_path)164 bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
165 return mock->mock_init_anonymous_namespace(false, sonames, search_path);
166 }
167
android_create_namespace(const char * name,const char * ld_library_path,const char * default_library_path,uint64_t type,const char * permitted_when_isolated_path,struct android_namespace_t * parent)168 struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
169 const char* default_library_path,
170 uint64_t type,
171 const char* permitted_when_isolated_path,
172 struct android_namespace_t* parent) {
173 return TO_ANDROID_NAMESPACE(
174 mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
175 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
176 }
177
android_link_namespaces(struct android_namespace_t * from,struct android_namespace_t * to,const char * sonames)178 bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
179 const char* sonames) {
180 return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
181 }
182
android_get_exported_namespace(const char * name)183 struct android_namespace_t* android_get_exported_namespace(const char* name) {
184 return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
185 }
186
android_dlopen_ext(const char * filename,int flags,const android_dlextinfo * info)187 void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
188 return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
189 }
190
191 // libnativebridge APIs
NativeBridgeIsSupported(const char * libpath)192 bool NativeBridgeIsSupported(const char* libpath) {
193 return mock->NativeBridgeIsSupported(libpath);
194 }
195
NativeBridgeGetExportedNamespace(const char * name)196 struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
197 return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
198 }
199
NativeBridgeCreateNamespace(const char * name,const char * ld_library_path,const char * default_library_path,uint64_t type,const char * permitted_when_isolated_path,struct native_bridge_namespace_t * parent)200 struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
201 const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
202 const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
203 return TO_BRIDGED_NAMESPACE(
204 mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
205 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
206 }
207
NativeBridgeLinkNamespaces(struct native_bridge_namespace_t * from,struct native_bridge_namespace_t * to,const char * sonames)208 bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
209 struct native_bridge_namespace_t* to, const char* sonames) {
210 return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
211 }
212
NativeBridgeLoadLibraryExt(const char * libpath,int flag,struct native_bridge_namespace_t * ns)213 void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
214 struct native_bridge_namespace_t* ns) {
215 return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
216 }
217
NativeBridgeInitialized()218 bool NativeBridgeInitialized() {
219 return mock->NativeBridgeInitialized();
220 }
221
NativeBridgeInitAnonymousNamespace(const char * public_ns_sonames,const char * anon_ns_library_path)222 bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
223 const char* anon_ns_library_path) {
224 return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
225 }
226
NativeBridgeGetError()227 const char* NativeBridgeGetError() {
228 return mock->NativeBridgeGetError();
229 }
230
NativeBridgeIsPathSupported(const char * path)231 bool NativeBridgeIsPathSupported(const char* path) {
232 return mock->NativeBridgeIsPathSupported(path);
233 }
234
235 } // extern "C"
236
237 // A very simple JNI mock.
238 // jstring is a pointer to utf8 char array. We don't need utf16 char here.
239 // jobject, jclass, and jmethodID are also a pointer to utf8 char array
240 // Only a few JNI methods that are actually used in libnativeloader are mocked.
CreateJNINativeInterface()241 JNINativeInterface* CreateJNINativeInterface() {
242 JNINativeInterface* inf = new JNINativeInterface();
243 memset(inf, 0, sizeof(JNINativeInterface));
244
245 inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
246 return reinterpret_cast<const char*>(s);
247 };
248
249 inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
250
251 inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
252 return reinterpret_cast<jstring>(const_cast<char*>(bytes));
253 };
254
255 inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
256 return reinterpret_cast<jclass>(const_cast<char*>(name));
257 };
258
259 inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
260 if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
261 // JniObject_getParent can be a valid jobject or nullptr if there is
262 // no parent classloader.
263 const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
264 return reinterpret_cast<jobject>(const_cast<char*>(ret));
265 }
266 return nullptr;
267 };
268
269 inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
270 return reinterpret_cast<jmethodID>(const_cast<char*>(name));
271 };
272
273 inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
274
275 inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
276 return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
277 };
278
279 return inf;
280 }
281
282 static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
283
284 // Custom matcher for comparing namespace handles
285 MATCHER_P(NsEq, other, "") {
286 *result_listener << "comparing " << reinterpret_cast<const char*>(arg) << " and " << other;
287 return strcmp(reinterpret_cast<const char*>(arg), reinterpret_cast<const char*>(other)) == 0;
288 }
289
290 /////////////////////////////////////////////////////////////////
291
292 // Test fixture
293 class NativeLoaderTest : public ::testing::TestWithParam<bool> {
294 protected:
IsBridged()295 bool IsBridged() { return GetParam(); }
296
SetUp()297 void SetUp() override {
298 mock = std::make_unique<testing::NiceMock<MockPlatform>>(IsBridged());
299
300 env = std::make_unique<JNIEnv>();
301 env->functions = CreateJNINativeInterface();
302 }
303
SetExpectations()304 void SetExpectations() {
305 std::vector<std::string> default_public_libs =
306 android::base::Split(preloadable_public_libraries(), ":");
307 for (auto l : default_public_libs) {
308 EXPECT_CALL(*mock, dlopen(StrEq(l.c_str()), RTLD_NOW | RTLD_NODELETE))
309 .WillOnce(Return(any_nonnull));
310 }
311 }
312
RunTest()313 void RunTest() { InitializeNativeLoader(); }
314
TearDown()315 void TearDown() override {
316 ResetNativeLoader();
317 delete env->functions;
318 mock.reset();
319 }
320
321 std::unique_ptr<JNIEnv> env;
322 };
323
324 /////////////////////////////////////////////////////////////////
325
TEST_P(NativeLoaderTest,InitializeLoadsDefaultPublicLibraries)326 TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
327 SetExpectations();
328 RunTest();
329 }
330
331 INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
332
333 /////////////////////////////////////////////////////////////////
334
335 class NativeLoaderTest_Create : public NativeLoaderTest {
336 protected:
337 // Test inputs (initialized to the default values). Overriding these
338 // must be done before calling SetExpectations() and RunTest().
339 uint32_t target_sdk_version = 29;
340 std::string class_loader = "my_classloader";
341 bool is_shared = false;
342 std::string dex_path = "/data/app/foo/classes.dex";
343 std::string library_path = "/data/app/foo/" LIB_DIR "/arm";
344 std::string permitted_path = "/data/app/foo/" LIB_DIR;
345
346 // expected output (.. for the default test inputs)
347 std::string expected_namespace_name = "classloader-namespace";
348 uint64_t expected_namespace_flags =
349 ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS;
350 std::string expected_library_path = library_path;
351 std::string expected_permitted_path = std::string("/data:/mnt/expand:") + permitted_path;
352 std::string expected_parent_namespace = "system";
353 bool expected_link_with_platform_ns = true;
354 bool expected_link_with_art_ns = true;
355 bool expected_link_with_sphal_ns = !vendor_public_libraries().empty();
356 bool expected_link_with_vndk_ns = false;
357 bool expected_link_with_vndk_product_ns = false;
358 bool expected_link_with_default_ns = false;
359 bool expected_link_with_neuralnetworks_ns = true;
360 bool expected_link_with_statsd_ns = true;
361 std::string expected_shared_libs_to_platform_ns = default_public_libraries();
362 std::string expected_shared_libs_to_art_ns = art_public_libraries();
363 std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
364 std::string expected_shared_libs_to_vndk_ns = vndksp_libraries_vendor();
365 std::string expected_shared_libs_to_vndk_product_ns = vndksp_libraries_product();
366 std::string expected_shared_libs_to_default_ns = default_public_libraries();
367 std::string expected_shared_libs_to_neuralnetworks_ns = neuralnetworks_public_libraries();
368 std::string expected_shared_libs_to_statsd_ns = statsd_public_libraries();
369
SetExpectations()370 void SetExpectations() {
371 NativeLoaderTest::SetExpectations();
372
373 ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
374
375 EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(testing::AnyNumber());
376 EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(testing::AnyNumber());
377
378 EXPECT_CALL(*mock, mock_create_namespace(
379 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
380 StrEq(expected_library_path), expected_namespace_flags,
381 StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
382 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
383 if (expected_link_with_platform_ns) {
384 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("system"),
385 StrEq(expected_shared_libs_to_platform_ns)))
386 .WillOnce(Return(true));
387 }
388 if (expected_link_with_art_ns) {
389 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_art"),
390 StrEq(expected_shared_libs_to_art_ns)))
391 .WillOnce(Return(true));
392 }
393 if (expected_link_with_sphal_ns) {
394 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
395 StrEq(expected_shared_libs_to_sphal_ns)))
396 .WillOnce(Return(true));
397 }
398 if (expected_link_with_vndk_ns) {
399 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
400 StrEq(expected_shared_libs_to_vndk_ns)))
401 .WillOnce(Return(true));
402 }
403 if (expected_link_with_vndk_product_ns) {
404 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk_product"),
405 StrEq(expected_shared_libs_to_vndk_product_ns)))
406 .WillOnce(Return(true));
407 }
408 if (expected_link_with_default_ns) {
409 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
410 StrEq(expected_shared_libs_to_default_ns)))
411 .WillOnce(Return(true));
412 }
413 if (expected_link_with_neuralnetworks_ns) {
414 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_neuralnetworks"),
415 StrEq(expected_shared_libs_to_neuralnetworks_ns)))
416 .WillOnce(Return(true));
417 }
418 if (expected_link_with_statsd_ns) {
419 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_os_statsd"),
420 StrEq(expected_shared_libs_to_statsd_ns)))
421 .WillOnce(Return(true));
422 }
423 }
424
RunTest()425 void RunTest() {
426 NativeLoaderTest::RunTest();
427
428 jstring err = CreateClassLoaderNamespace(
429 env(), target_sdk_version, env()->NewStringUTF(class_loader.c_str()), is_shared,
430 env()->NewStringUTF(dex_path.c_str()), env()->NewStringUTF(library_path.c_str()),
431 env()->NewStringUTF(permitted_path.c_str()));
432
433 // no error
434 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
435
436 if (!IsBridged()) {
437 struct android_namespace_t* ns =
438 FindNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
439
440 // The created namespace is for this apk
441 EXPECT_EQ(dex_path.c_str(), reinterpret_cast<const char*>(ns));
442 } else {
443 struct NativeLoaderNamespace* ns =
444 FindNativeLoaderNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
445
446 // The created namespace is for the this apk
447 EXPECT_STREQ(dex_path.c_str(),
448 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
449 }
450 }
451
env()452 JNIEnv* env() { return NativeLoaderTest::env.get(); }
453 };
454
TEST_P(NativeLoaderTest_Create,DownloadedApp)455 TEST_P(NativeLoaderTest_Create, DownloadedApp) {
456 SetExpectations();
457 RunTest();
458 }
459
TEST_P(NativeLoaderTest_Create,BundledSystemApp)460 TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
461 dex_path = "/system/app/foo/foo.apk";
462 is_shared = true;
463
464 expected_namespace_name = "classloader-namespace-shared";
465 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
466 SetExpectations();
467 RunTest();
468 }
469
TEST_P(NativeLoaderTest_Create,BundledVendorApp)470 TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
471 dex_path = "/vendor/app/foo/foo.apk";
472 is_shared = true;
473
474 expected_namespace_name = "classloader-namespace-shared";
475 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
476 SetExpectations();
477 RunTest();
478 }
479
TEST_P(NativeLoaderTest_Create,UnbundledVendorApp)480 TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
481 dex_path = "/vendor/app/foo/foo.apk";
482 is_shared = false;
483
484 expected_namespace_name = "vendor-classloader-namespace";
485 expected_library_path = expected_library_path + ":/vendor/" LIB_DIR;
486 expected_permitted_path = expected_permitted_path + ":/vendor/" LIB_DIR;
487 expected_shared_libs_to_platform_ns =
488 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_vendor();
489 expected_link_with_vndk_ns = true;
490 SetExpectations();
491 RunTest();
492 }
493
TEST_P(NativeLoaderTest_Create,BundledProductApp)494 TEST_P(NativeLoaderTest_Create, BundledProductApp) {
495 dex_path = "/product/app/foo/foo.apk";
496 is_shared = true;
497
498 expected_namespace_name = "classloader-namespace-shared";
499 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
500 SetExpectations();
501 RunTest();
502 }
503
TEST_P(NativeLoaderTest_Create,UnbundledProductApp)504 TEST_P(NativeLoaderTest_Create, UnbundledProductApp) {
505 dex_path = "/product/app/foo/foo.apk";
506 is_shared = false;
507
508 if (is_product_vndk_version_defined()) {
509 expected_namespace_name = "vendor-classloader-namespace";
510 expected_library_path = expected_library_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
511 expected_permitted_path =
512 expected_permitted_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
513 expected_shared_libs_to_platform_ns =
514 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_product();
515 expected_link_with_vndk_product_ns = true;
516 }
517 SetExpectations();
518 RunTest();
519 }
520
TEST_P(NativeLoaderTest_Create,NamespaceForSharedLibIsNotUsedAsAnonymousNamespace)521 TEST_P(NativeLoaderTest_Create, NamespaceForSharedLibIsNotUsedAsAnonymousNamespace) {
522 if (IsBridged()) {
523 // There is no shared lib in translated arch
524 // TODO(jiyong): revisit this
525 return;
526 }
527 // compared to apks, for java shared libs, library_path is empty; java shared
528 // libs don't have their own native libs. They use platform's.
529 library_path = "";
530 expected_library_path = library_path;
531 // no ALSO_USED_AS_ANONYMOUS
532 expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
533 SetExpectations();
534 RunTest();
535 }
536
TEST_P(NativeLoaderTest_Create,TwoApks)537 TEST_P(NativeLoaderTest_Create, TwoApks) {
538 SetExpectations();
539 const uint32_t second_app_target_sdk_version = 29;
540 const std::string second_app_class_loader = "second_app_classloader";
541 const bool second_app_is_shared = false;
542 const std::string second_app_dex_path = "/data/app/bar/classes.dex";
543 const std::string second_app_library_path = "/data/app/bar/" LIB_DIR "/arm";
544 const std::string second_app_permitted_path = "/data/app/bar/" LIB_DIR;
545 const std::string expected_second_app_permitted_path =
546 std::string("/data:/mnt/expand:") + second_app_permitted_path;
547 const std::string expected_second_app_parent_namespace = "classloader-namespace";
548 // no ALSO_USED_AS_ANONYMOUS
549 const uint64_t expected_second_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
550
551 // The scenario is that second app is loaded by the first app.
552 // So the first app's classloader (`classloader`) is parent of the second
553 // app's classloader.
554 ON_CALL(*mock, JniObject_getParent(StrEq(second_app_class_loader)))
555 .WillByDefault(Return(class_loader.c_str()));
556
557 // namespace for the second app is created. Its parent is set to the namespace
558 // of the first app.
559 EXPECT_CALL(*mock, mock_create_namespace(
560 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
561 StrEq(second_app_library_path), expected_second_namespace_flags,
562 StrEq(expected_second_app_permitted_path), NsEq(dex_path.c_str())))
563 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(second_app_dex_path.c_str()))));
564 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), NsEq(second_app_dex_path.c_str()), _, _))
565 .WillRepeatedly(Return(true));
566
567 RunTest();
568 jstring err = CreateClassLoaderNamespace(
569 env(), second_app_target_sdk_version, env()->NewStringUTF(second_app_class_loader.c_str()),
570 second_app_is_shared, env()->NewStringUTF(second_app_dex_path.c_str()),
571 env()->NewStringUTF(second_app_library_path.c_str()),
572 env()->NewStringUTF(second_app_permitted_path.c_str()));
573
574 // success
575 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
576
577 if (!IsBridged()) {
578 struct android_namespace_t* ns =
579 FindNamespaceByClassLoader(env(), env()->NewStringUTF(second_app_class_loader.c_str()));
580
581 // The created namespace is for the second apk
582 EXPECT_EQ(second_app_dex_path.c_str(), reinterpret_cast<const char*>(ns));
583 } else {
584 struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
585 env(), env()->NewStringUTF(second_app_class_loader.c_str()));
586
587 // The created namespace is for the second apk
588 EXPECT_STREQ(second_app_dex_path.c_str(),
589 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
590 }
591 }
592
593 INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
594
595 const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
__anona7cbf4c60a02(const struct ConfigEntry&) 596 [](const struct ConfigEntry&) -> Result<bool> { return true; };
597
TEST(NativeLoaderConfigParser,NamesAndComments)598 TEST(NativeLoaderConfigParser, NamesAndComments) {
599 const char file_content[] = R"(
600 ######
601
602 libA.so
603 #libB.so
604
605
606 libC.so
607 libD.so
608 #### libE.so
609 )";
610 const std::vector<std::string> expected_result = {"libA.so", "libC.so", "libD.so"};
611 Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
612 ASSERT_RESULT_OK(result);
613 ASSERT_EQ(expected_result, *result);
614 }
615
TEST(NativeLoaderConfigParser,WithBitness)616 TEST(NativeLoaderConfigParser, WithBitness) {
617 const char file_content[] = R"(
618 libA.so 32
619 libB.so 64
620 libC.so
621 )";
622 #if defined(__LP64__)
623 const std::vector<std::string> expected_result = {"libB.so", "libC.so"};
624 #else
625 const std::vector<std::string> expected_result = {"libA.so", "libC.so"};
626 #endif
627 Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
628 ASSERT_RESULT_OK(result);
629 ASSERT_EQ(expected_result, *result);
630 }
631
TEST(NativeLoaderConfigParser,WithNoPreload)632 TEST(NativeLoaderConfigParser, WithNoPreload) {
633 const char file_content[] = R"(
634 libA.so nopreload
635 libB.so nopreload
636 libC.so
637 )";
638
639 const std::vector<std::string> expected_result = {"libC.so"};
640 Result<std::vector<std::string>> result =
641 ParseConfig(file_content,
642 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
643 ASSERT_RESULT_OK(result);
644 ASSERT_EQ(expected_result, *result);
645 }
646
TEST(NativeLoaderConfigParser,WithNoPreloadAndBitness)647 TEST(NativeLoaderConfigParser, WithNoPreloadAndBitness) {
648 const char file_content[] = R"(
649 libA.so nopreload 32
650 libB.so 64 nopreload
651 libC.so 32
652 libD.so 64
653 libE.so nopreload
654 )";
655
656 #if defined(__LP64__)
657 const std::vector<std::string> expected_result = {"libD.so"};
658 #else
659 const std::vector<std::string> expected_result = {"libC.so"};
660 #endif
661 Result<std::vector<std::string>> result =
662 ParseConfig(file_content,
663 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
664 ASSERT_RESULT_OK(result);
665 ASSERT_EQ(expected_result, *result);
666 }
667
TEST(NativeLoaderConfigParser,RejectMalformed)668 TEST(NativeLoaderConfigParser, RejectMalformed) {
669 ASSERT_FALSE(ParseConfig("libA.so 32 64", always_true).ok());
670 ASSERT_FALSE(ParseConfig("libA.so 32 32", always_true).ok());
671 ASSERT_FALSE(ParseConfig("libA.so 32 nopreload 64", always_true).ok());
672 ASSERT_FALSE(ParseConfig("32 libA.so nopreload", always_true).ok());
673 ASSERT_FALSE(ParseConfig("nopreload libA.so 32", always_true).ok());
674 ASSERT_FALSE(ParseConfig("libA.so nopreload # comment", always_true).ok());
675 }
676
677 } // namespace nativeloader
678 } // namespace android
679