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