blob: 8c4a8c5f871a0e86ec408b5adccec5f40c273d99 [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"
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +010027#include "nativehelper/scoped_utf_chars.h"
Orion Hodson9b16e342019-10-09 13:29:16 +010028#include "nativeloader/dlext_namespaces.h"
29#include "nativeloader/native_loader.h"
30#include "public_libraries.h"
31
Orion Hodson9b16e342019-10-09 13:29:16 +010032namespace android {
33namespace nativeloader {
34
Martin Stjernholm48297332019-11-12 21:21:32 +000035using ::testing::Eq;
36using ::testing::Return;
37using ::testing::StrEq;
38using ::testing::_;
39using internal::ConfigEntry;
40using internal::ParseConfig;
41
Martin Stjernholmbe08b202019-11-12 20:11:00 +000042#if defined(__LP64__)
43#define LIB_DIR "lib64"
44#else
45#define LIB_DIR "lib"
46#endif
47
Orion Hodson9b16e342019-10-09 13:29:16 +010048// gmock interface that represents interested platform APIs on libdl and libnativebridge
49class Platform {
50 public:
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
94static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +090095 {"system", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("system"))},
Orion Hodson9b16e342019-10-09 13:29:16 +010096 {"default", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("default"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +090097 {"com_android_art", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_art"))},
Orion Hodson9b16e342019-10-09 13:29:16 +010098 {"sphal", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("sphal"))},
99 {"vndk", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk"))},
Justin Yuneb4f08c2020-02-18 11:29:07 +0900100 {"vndk_product", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk_product"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900101 {"com_android_neuralnetworks", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_neuralnetworks"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900102 {"com_android_os_statsd", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_os_statsd"))},
Orion Hodson9b16e342019-10-09 13:29:16 +0100103};
104
105// The actual gmock object
106class MockPlatform : public Platform {
107 public:
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(_, _))
Martin Stjernholm48297332019-11-12 21:21:32 +0000112 .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
Orion Hodson9b16e342019-10-09 13:29:16 +0100113 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
148static std::unique_ptr<MockPlatform> mock;
149
150// Provide C wrappers for the mock object.
151extern "C" {
152void* dlopen(const char* file, int flag) {
153 return mock->dlopen(file, flag);
154}
155
156int dlclose(void* handle) {
157 return mock->dlclose(handle);
158}
159
160char* dlerror(void) {
161 return mock->dlerror();
162}
163
164bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
165 return mock->mock_init_anonymous_namespace(false, sonames, search_path);
166}
167
168struct 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
178bool 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
183struct android_namespace_t* android_get_exported_namespace(const char* name) {
184 return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
185}
186
187void* 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
192bool NativeBridgeIsSupported(const char* libpath) {
193 return mock->NativeBridgeIsSupported(libpath);
194}
195
196struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
197 return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
198}
199
200struct 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
208bool 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
213void* 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
218bool NativeBridgeInitialized() {
219 return mock->NativeBridgeInitialized();
220}
221
222bool 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
227const char* NativeBridgeGetError() {
228 return mock->NativeBridgeGetError();
229}
230
231bool 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.
241JNINativeInterface* 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
282static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
283
284// Custom matcher for comparing namespace handles
285MATCHER_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
293class NativeLoaderTest : public ::testing::TestWithParam<bool> {
294 protected:
295 bool IsBridged() { return GetParam(); }
296
297 void SetUp() override {
Martin Stjernholm48297332019-11-12 21:21:32 +0000298 mock = std::make_unique<testing::NiceMock<MockPlatform>>(IsBridged());
Orion Hodson9b16e342019-10-09 13:29:16 +0100299
300 env = std::make_unique<JNIEnv>();
301 env->functions = CreateJNINativeInterface();
302 }
303
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
313 void RunTest() { InitializeNativeLoader(); }
314
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
326TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
327 SetExpectations();
328 RunTest();
329}
330
331INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
332
333/////////////////////////////////////////////////////////////////
334
335class 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";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000343 std::string library_path = "/data/app/foo/" LIB_DIR "/arm";
344 std::string permitted_path = "/data/app/foo/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100345
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;
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900352 std::string expected_parent_namespace = "system";
Orion Hodson9b16e342019-10-09 13:29:16 +0100353 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;
Justin Yuneb4f08c2020-02-18 11:29:07 +0900357 bool expected_link_with_vndk_product_ns = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100358 bool expected_link_with_default_ns = false;
359 bool expected_link_with_neuralnetworks_ns = true;
Jeffrey Huang52575032020-02-11 17:33:45 -0800360 bool expected_link_with_statsd_ns = true;
Orion Hodson9b16e342019-10-09 13:29:16 +0100361 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();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900364 std::string expected_shared_libs_to_vndk_ns = vndksp_libraries_vendor();
365 std::string expected_shared_libs_to_vndk_product_ns = vndksp_libraries_product();
Orion Hodson9b16e342019-10-09 13:29:16 +0100366 std::string expected_shared_libs_to_default_ns = default_public_libraries();
367 std::string expected_shared_libs_to_neuralnetworks_ns = neuralnetworks_public_libraries();
Jeffrey Huang52575032020-02-11 17:33:45 -0800368 std::string expected_shared_libs_to_statsd_ns = statsd_public_libraries();
Orion Hodson9b16e342019-10-09 13:29:16 +0100369
370 void SetExpectations() {
371 NativeLoaderTest::SetExpectations();
372
373 ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
374
Martin Stjernholm48297332019-11-12 21:21:32 +0000375 EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(testing::AnyNumber());
376 EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(testing::AnyNumber());
Orion Hodson9b16e342019-10-09 13:29:16 +0100377
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) {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900384 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("system"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100385 StrEq(expected_shared_libs_to_platform_ns)))
386 .WillOnce(Return(true));
387 }
388 if (expected_link_with_art_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900389 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_art"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100390 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 }
Justin Yuneb4f08c2020-02-18 11:29:07 +0900403 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 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100408 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) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900414 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_neuralnetworks"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100415 StrEq(expected_shared_libs_to_neuralnetworks_ns)))
416 .WillOnce(Return(true));
417 }
Jeffrey Huang52575032020-02-11 17:33:45 -0800418 if (expected_link_with_statsd_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900419 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_os_statsd"),
Jeffrey Huang52575032020-02-11 17:33:45 -0800420 StrEq(expected_shared_libs_to_statsd_ns)))
421 .WillOnce(Return(true));
422 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100423 }
424
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
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100434 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100435
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
452 JNIEnv* env() { return NativeLoaderTest::env.get(); }
453};
454
455TEST_P(NativeLoaderTest_Create, DownloadedApp) {
456 SetExpectations();
457 RunTest();
458}
459
460TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
461 dex_path = "/system/app/foo/foo.apk";
462 is_shared = true;
463
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100464 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100465 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
466 SetExpectations();
467 RunTest();
468}
469
470TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
471 dex_path = "/vendor/app/foo/foo.apk";
472 is_shared = true;
473
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100474 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100475 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
476 SetExpectations();
477 RunTest();
478}
479
480TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
481 dex_path = "/vendor/app/foo/foo.apk";
482 is_shared = false;
483
484 expected_namespace_name = "vendor-classloader-namespace";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000485 expected_library_path = expected_library_path + ":/vendor/" LIB_DIR;
486 expected_permitted_path = expected_permitted_path + ":/vendor/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100487 expected_shared_libs_to_platform_ns =
Justin Yun089c1352020-02-06 16:53:08 +0900488 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_vendor();
Orion Hodson9b16e342019-10-09 13:29:16 +0100489 expected_link_with_vndk_ns = true;
490 SetExpectations();
491 RunTest();
492}
493
Justin Yun3db26d52019-12-16 14:09:39 +0900494TEST_P(NativeLoaderTest_Create, BundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100495 dex_path = "/product/app/foo/foo.apk";
496 is_shared = true;
497
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100498 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100499 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
500 SetExpectations();
501 RunTest();
502}
503
Justin Yun3db26d52019-12-16 14:09:39 +0900504TEST_P(NativeLoaderTest_Create, UnbundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100505 dex_path = "/product/app/foo/foo.apk";
506 is_shared = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100507
Justin Yun3db26d52019-12-16 14:09:39 +0900508 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 =
Justin Yun089c1352020-02-06 16:53:08 +0900514 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_product();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900515 expected_link_with_vndk_product_ns = true;
Justin Yun3db26d52019-12-16 14:09:39 +0900516 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100517 SetExpectations();
518 RunTest();
519}
520
521TEST_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
537TEST_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";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000543 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;
Orion Hodson9b16e342019-10-09 13:29:16 +0100545 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
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100575 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100576
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
593INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
594
595const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
596 [](const struct ConfigEntry&) -> Result<bool> { return true; };
597
598TEST(NativeLoaderConfigParser, NamesAndComments) {
599 const char file_content[] = R"(
600######
601
602libA.so
603#libB.so
604
605
606 libC.so
607libD.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);
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900612 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100613 ASSERT_EQ(expected_result, *result);
614}
615
616TEST(NativeLoaderConfigParser, WithBitness) {
617 const char file_content[] = R"(
618libA.so 32
619libB.so 64
620libC.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);
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900628 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100629 ASSERT_EQ(expected_result, *result);
630}
631
632TEST(NativeLoaderConfigParser, WithNoPreload) {
633 const char file_content[] = R"(
634libA.so nopreload
635libB.so nopreload
636libC.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; });
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900643 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100644 ASSERT_EQ(expected_result, *result);
645}
646
647TEST(NativeLoaderConfigParser, WithNoPreloadAndBitness) {
648 const char file_content[] = R"(
649libA.so nopreload 32
650libB.so 64 nopreload
651libC.so 32
652libD.so 64
653libE.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; });
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900664 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100665 ASSERT_EQ(expected_result, *result);
666}
667
668TEST(NativeLoaderConfigParser, RejectMalformed) {
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900669 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());
Orion Hodson9b16e342019-10-09 13:29:16 +0100675}
676
677} // namespace nativeloader
678} // namespace android