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