blob: 81109b6008330ef8bdcd35b35881a26c7281813f [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
Martin Stjernholmb3092402020-09-04 00:49:44 +010023#include <android-base/stringprintf.h>
Orion Hodson9b16e342019-10-09 13:29:16 +010024#include <android-base/strings.h>
25#include <gmock/gmock.h>
26#include <gtest/gtest.h>
27#include <jni.h>
28
29#include "native_loader_namespace.h"
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +010030#include "nativehelper/scoped_utf_chars.h"
Orion Hodson9b16e342019-10-09 13:29:16 +010031#include "nativeloader/dlext_namespaces.h"
32#include "nativeloader/native_loader.h"
33#include "public_libraries.h"
34
Orion Hodson9b16e342019-10-09 13:29:16 +010035namespace android {
36namespace nativeloader {
37
Martin Stjernholm48297332019-11-12 21:21:32 +000038using ::testing::Eq;
39using ::testing::Return;
40using ::testing::StrEq;
41using ::testing::_;
42using internal::ConfigEntry;
43using internal::ParseConfig;
Jooyung Han538f99a2020-03-03 00:46:50 +090044using internal::ParseJniConfig;
Martin Stjernholm48297332019-11-12 21:21:32 +000045
Martin Stjernholmbe08b202019-11-12 20:11:00 +000046#if defined(__LP64__)
47#define LIB_DIR "lib64"
48#else
49#define LIB_DIR "lib"
50#endif
51
Orion Hodson9b16e342019-10-09 13:29:16 +010052// gmock interface that represents interested platform APIs on libdl and libnativebridge
53class Platform {
54 public:
55 virtual ~Platform() {}
56
57 // libdl APIs
58 virtual void* dlopen(const char* filename, int flags) = 0;
59 virtual int dlclose(void* handle) = 0;
60 virtual char* dlerror(void) = 0;
61
62 // These mock_* are the APIs semantically the same across libdl and libnativebridge.
63 // Instead of having two set of mock APIs for the two, define only one set with an additional
64 // argument 'bool bridged' to identify the context (i.e., called for libdl or libnativebridge).
65 typedef char* mock_namespace_handle;
66 virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
67 const char* search_paths) = 0;
68 virtual mock_namespace_handle mock_create_namespace(
69 bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
70 uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
71 virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
72 mock_namespace_handle to, const char* sonames) = 0;
73 virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
74 virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
75 mock_namespace_handle ns) = 0;
76
77 // libnativebridge APIs for which libdl has no corresponding APIs
78 virtual bool NativeBridgeInitialized() = 0;
79 virtual const char* NativeBridgeGetError() = 0;
80 virtual bool NativeBridgeIsPathSupported(const char*) = 0;
81 virtual bool NativeBridgeIsSupported(const char*) = 0;
82
83 // To mock "ClassLoader Object.getParent()"
84 virtual const char* JniObject_getParent(const char*) = 0;
85};
86
87// The mock does not actually create a namespace object. But simply casts the pointer to the
88// string for the namespace name as the handle to the namespace object.
89#define TO_ANDROID_NAMESPACE(str) \
90 reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
91
92#define TO_BRIDGED_NAMESPACE(str) \
93 reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
94
95#define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
96
97// These represents built-in namespaces created by the linker according to ld.config.txt
98static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
Martin Stjernholmb3092402020-09-04 00:49:44 +010099#define NAMESPACE_ENTRY(ns) {ns, TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(ns))}
100 NAMESPACE_ENTRY("com_android_i18n"),
101 NAMESPACE_ENTRY("com_android_neuralnetworks"),
102 NAMESPACE_ENTRY("com_android_os_statsd"),
103 NAMESPACE_ENTRY("com_android_art"),
104 NAMESPACE_ENTRY("default"),
105 NAMESPACE_ENTRY("sphal"),
106 NAMESPACE_ENTRY("system"),
107 NAMESPACE_ENTRY("vndk"),
108 NAMESPACE_ENTRY("vndk_product"),
109#undef NAMESPACE_ENTRY
Orion Hodson9b16e342019-10-09 13:29:16 +0100110};
111
112// The actual gmock object
113class MockPlatform : public Platform {
114 public:
115 explicit MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
116 ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
117 ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
118 ON_CALL(*this, mock_get_exported_namespace(_, _))
Martin Stjernholm48297332019-11-12 21:21:32 +0000119 .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
Orion Hodson9b16e342019-10-09 13:29:16 +0100120 if (namespaces.find(name) != namespaces.end()) {
121 return namespaces[name];
122 }
Martin Stjernholmb3092402020-09-04 00:49:44 +0100123 std::string msg = android::base::StringPrintf("(namespace %s not found)", name);
124 // The strdup'ed string will leak, but the test is already failing if we get here.
125 return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(strdup(msg.c_str())));
Orion Hodson9b16e342019-10-09 13:29:16 +0100126 }));
127 }
128
129 // Mocking libdl APIs
130 MOCK_METHOD2(dlopen, void*(const char*, int));
131 MOCK_METHOD1(dlclose, int(void*));
132 MOCK_METHOD0(dlerror, char*());
133
134 // Mocking the common APIs
135 MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
136 MOCK_METHOD7(mock_create_namespace,
137 mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
138 const char*, mock_namespace_handle));
139 MOCK_METHOD4(mock_link_namespaces,
140 bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
141 MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
142 MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
143
144 // Mocking libnativebridge APIs
145 MOCK_METHOD0(NativeBridgeInitialized, bool());
146 MOCK_METHOD0(NativeBridgeGetError, const char*());
147 MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
148 MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
149
150 // Mocking "ClassLoader Object.getParent()"
151 MOCK_METHOD1(JniObject_getParent, const char*(const char*));
152
153 private:
154 bool is_bridged_;
155};
156
157static std::unique_ptr<MockPlatform> mock;
158
159// Provide C wrappers for the mock object.
160extern "C" {
161void* dlopen(const char* file, int flag) {
162 return mock->dlopen(file, flag);
163}
164
165int dlclose(void* handle) {
166 return mock->dlclose(handle);
167}
168
169char* dlerror(void) {
170 return mock->dlerror();
171}
172
173bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
174 return mock->mock_init_anonymous_namespace(false, sonames, search_path);
175}
176
177struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
178 const char* default_library_path,
179 uint64_t type,
180 const char* permitted_when_isolated_path,
181 struct android_namespace_t* parent) {
182 return TO_ANDROID_NAMESPACE(
183 mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
184 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
185}
186
187bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
188 const char* sonames) {
189 return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
190}
191
192struct android_namespace_t* android_get_exported_namespace(const char* name) {
193 return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
194}
195
196void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
197 return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
198}
199
200// libnativebridge APIs
201bool NativeBridgeIsSupported(const char* libpath) {
202 return mock->NativeBridgeIsSupported(libpath);
203}
204
205struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
206 return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
207}
208
209struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
210 const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
211 const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
212 return TO_BRIDGED_NAMESPACE(
213 mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
214 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
215}
216
217bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
218 struct native_bridge_namespace_t* to, const char* sonames) {
219 return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
220}
221
222void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
223 struct native_bridge_namespace_t* ns) {
224 return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
225}
226
227bool NativeBridgeInitialized() {
228 return mock->NativeBridgeInitialized();
229}
230
231bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
232 const char* anon_ns_library_path) {
233 return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
234}
235
236const char* NativeBridgeGetError() {
237 return mock->NativeBridgeGetError();
238}
239
240bool NativeBridgeIsPathSupported(const char* path) {
241 return mock->NativeBridgeIsPathSupported(path);
242}
243
244} // extern "C"
245
246// A very simple JNI mock.
247// jstring is a pointer to utf8 char array. We don't need utf16 char here.
248// jobject, jclass, and jmethodID are also a pointer to utf8 char array
249// Only a few JNI methods that are actually used in libnativeloader are mocked.
250JNINativeInterface* CreateJNINativeInterface() {
251 JNINativeInterface* inf = new JNINativeInterface();
252 memset(inf, 0, sizeof(JNINativeInterface));
253
254 inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
255 return reinterpret_cast<const char*>(s);
256 };
257
258 inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
259
260 inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
261 return reinterpret_cast<jstring>(const_cast<char*>(bytes));
262 };
263
264 inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
265 return reinterpret_cast<jclass>(const_cast<char*>(name));
266 };
267
268 inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
269 if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
270 // JniObject_getParent can be a valid jobject or nullptr if there is
271 // no parent classloader.
272 const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
273 return reinterpret_cast<jobject>(const_cast<char*>(ret));
274 }
275 return nullptr;
276 };
277
278 inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
279 return reinterpret_cast<jmethodID>(const_cast<char*>(name));
280 };
281
282 inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
283
284 inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
285 return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
286 };
287
288 return inf;
289}
290
291static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
292
293// Custom matcher for comparing namespace handles
294MATCHER_P(NsEq, other, "") {
295 *result_listener << "comparing " << reinterpret_cast<const char*>(arg) << " and " << other;
296 return strcmp(reinterpret_cast<const char*>(arg), reinterpret_cast<const char*>(other)) == 0;
297}
298
299/////////////////////////////////////////////////////////////////
300
301// Test fixture
302class NativeLoaderTest : public ::testing::TestWithParam<bool> {
303 protected:
304 bool IsBridged() { return GetParam(); }
305
306 void SetUp() override {
Martin Stjernholm48297332019-11-12 21:21:32 +0000307 mock = std::make_unique<testing::NiceMock<MockPlatform>>(IsBridged());
Orion Hodson9b16e342019-10-09 13:29:16 +0100308
309 env = std::make_unique<JNIEnv>();
310 env->functions = CreateJNINativeInterface();
311 }
312
313 void SetExpectations() {
314 std::vector<std::string> default_public_libs =
315 android::base::Split(preloadable_public_libraries(), ":");
316 for (auto l : default_public_libs) {
317 EXPECT_CALL(*mock, dlopen(StrEq(l.c_str()), RTLD_NOW | RTLD_NODELETE))
318 .WillOnce(Return(any_nonnull));
319 }
320 }
321
322 void RunTest() { InitializeNativeLoader(); }
323
324 void TearDown() override {
325 ResetNativeLoader();
326 delete env->functions;
327 mock.reset();
328 }
329
330 std::unique_ptr<JNIEnv> env;
331};
332
333/////////////////////////////////////////////////////////////////
334
335TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
336 SetExpectations();
337 RunTest();
338}
339
340INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
341
342/////////////////////////////////////////////////////////////////
343
344class NativeLoaderTest_Create : public NativeLoaderTest {
345 protected:
346 // Test inputs (initialized to the default values). Overriding these
347 // must be done before calling SetExpectations() and RunTest().
348 uint32_t target_sdk_version = 29;
349 std::string class_loader = "my_classloader";
350 bool is_shared = false;
351 std::string dex_path = "/data/app/foo/classes.dex";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000352 std::string library_path = "/data/app/foo/" LIB_DIR "/arm";
353 std::string permitted_path = "/data/app/foo/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100354
355 // expected output (.. for the default test inputs)
356 std::string expected_namespace_name = "classloader-namespace";
357 uint64_t expected_namespace_flags =
358 ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS;
359 std::string expected_library_path = library_path;
360 std::string expected_permitted_path = std::string("/data:/mnt/expand:") + permitted_path;
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900361 std::string expected_parent_namespace = "system";
Orion Hodson9b16e342019-10-09 13:29:16 +0100362 bool expected_link_with_platform_ns = true;
363 bool expected_link_with_art_ns = true;
Victor Changd20e51d2020-05-05 16:01:19 +0100364 bool expected_link_with_i18n_ns = true;
Orion Hodson9b16e342019-10-09 13:29:16 +0100365 bool expected_link_with_sphal_ns = !vendor_public_libraries().empty();
366 bool expected_link_with_vndk_ns = false;
Justin Yuneb4f08c2020-02-18 11:29:07 +0900367 bool expected_link_with_vndk_product_ns = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100368 bool expected_link_with_default_ns = false;
369 bool expected_link_with_neuralnetworks_ns = true;
Jeffrey Huang52575032020-02-11 17:33:45 -0800370 bool expected_link_with_statsd_ns = true;
Orion Hodson9b16e342019-10-09 13:29:16 +0100371 std::string expected_shared_libs_to_platform_ns = default_public_libraries();
372 std::string expected_shared_libs_to_art_ns = art_public_libraries();
Victor Changd20e51d2020-05-05 16:01:19 +0100373 std::string expected_shared_libs_to_i18n_ns = i18n_public_libraries();
Orion Hodson9b16e342019-10-09 13:29:16 +0100374 std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900375 std::string expected_shared_libs_to_vndk_ns = vndksp_libraries_vendor();
376 std::string expected_shared_libs_to_vndk_product_ns = vndksp_libraries_product();
Orion Hodson9b16e342019-10-09 13:29:16 +0100377 std::string expected_shared_libs_to_default_ns = default_public_libraries();
378 std::string expected_shared_libs_to_neuralnetworks_ns = neuralnetworks_public_libraries();
Jeffrey Huang52575032020-02-11 17:33:45 -0800379 std::string expected_shared_libs_to_statsd_ns = statsd_public_libraries();
Orion Hodson9b16e342019-10-09 13:29:16 +0100380
381 void SetExpectations() {
382 NativeLoaderTest::SetExpectations();
383
384 ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
385
Martin Stjernholm48297332019-11-12 21:21:32 +0000386 EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(testing::AnyNumber());
387 EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(testing::AnyNumber());
Orion Hodson9b16e342019-10-09 13:29:16 +0100388
389 EXPECT_CALL(*mock, mock_create_namespace(
390 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
391 StrEq(expected_library_path), expected_namespace_flags,
392 StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
393 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
394 if (expected_link_with_platform_ns) {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900395 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("system"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100396 StrEq(expected_shared_libs_to_platform_ns)))
397 .WillOnce(Return(true));
398 }
399 if (expected_link_with_art_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900400 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_art"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100401 StrEq(expected_shared_libs_to_art_ns)))
402 .WillOnce(Return(true));
403 }
Victor Changd20e51d2020-05-05 16:01:19 +0100404 if (expected_link_with_i18n_ns) {
405 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_i18n"),
406 StrEq(expected_shared_libs_to_i18n_ns)))
407 .WillOnce(Return(true));
408 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100409 if (expected_link_with_sphal_ns) {
410 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
411 StrEq(expected_shared_libs_to_sphal_ns)))
412 .WillOnce(Return(true));
413 }
414 if (expected_link_with_vndk_ns) {
415 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
416 StrEq(expected_shared_libs_to_vndk_ns)))
417 .WillOnce(Return(true));
418 }
Justin Yuneb4f08c2020-02-18 11:29:07 +0900419 if (expected_link_with_vndk_product_ns) {
420 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk_product"),
421 StrEq(expected_shared_libs_to_vndk_product_ns)))
422 .WillOnce(Return(true));
423 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100424 if (expected_link_with_default_ns) {
425 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
426 StrEq(expected_shared_libs_to_default_ns)))
427 .WillOnce(Return(true));
428 }
429 if (expected_link_with_neuralnetworks_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900430 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_neuralnetworks"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100431 StrEq(expected_shared_libs_to_neuralnetworks_ns)))
432 .WillOnce(Return(true));
433 }
Jeffrey Huang52575032020-02-11 17:33:45 -0800434 if (expected_link_with_statsd_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900435 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_os_statsd"),
Jeffrey Huang52575032020-02-11 17:33:45 -0800436 StrEq(expected_shared_libs_to_statsd_ns)))
437 .WillOnce(Return(true));
438 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100439 }
440
441 void RunTest() {
442 NativeLoaderTest::RunTest();
443
444 jstring err = CreateClassLoaderNamespace(
445 env(), target_sdk_version, env()->NewStringUTF(class_loader.c_str()), is_shared,
446 env()->NewStringUTF(dex_path.c_str()), env()->NewStringUTF(library_path.c_str()),
Martin Stjernholmb3092402020-09-04 00:49:44 +0100447 env()->NewStringUTF(permitted_path.c_str()), /*uses_library_list=*/ nullptr);
Orion Hodson9b16e342019-10-09 13:29:16 +0100448
449 // no error
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100450 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100451
452 if (!IsBridged()) {
453 struct android_namespace_t* ns =
454 FindNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
455
456 // The created namespace is for this apk
457 EXPECT_EQ(dex_path.c_str(), reinterpret_cast<const char*>(ns));
458 } else {
459 struct NativeLoaderNamespace* ns =
460 FindNativeLoaderNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
461
462 // The created namespace is for the this apk
463 EXPECT_STREQ(dex_path.c_str(),
464 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
465 }
466 }
467
468 JNIEnv* env() { return NativeLoaderTest::env.get(); }
469};
470
471TEST_P(NativeLoaderTest_Create, DownloadedApp) {
472 SetExpectations();
473 RunTest();
474}
475
476TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
477 dex_path = "/system/app/foo/foo.apk";
478 is_shared = true;
479
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100480 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100481 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
482 SetExpectations();
483 RunTest();
484}
485
486TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
487 dex_path = "/vendor/app/foo/foo.apk";
488 is_shared = true;
489
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100490 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100491 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
492 SetExpectations();
493 RunTest();
494}
495
496TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
497 dex_path = "/vendor/app/foo/foo.apk";
498 is_shared = false;
499
500 expected_namespace_name = "vendor-classloader-namespace";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000501 expected_library_path = expected_library_path + ":/vendor/" LIB_DIR;
502 expected_permitted_path = expected_permitted_path + ":/vendor/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100503 expected_shared_libs_to_platform_ns =
Justin Yun089c1352020-02-06 16:53:08 +0900504 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_vendor();
Orion Hodson9b16e342019-10-09 13:29:16 +0100505 expected_link_with_vndk_ns = true;
506 SetExpectations();
507 RunTest();
508}
509
Justin Yun3db26d52019-12-16 14:09:39 +0900510TEST_P(NativeLoaderTest_Create, BundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100511 dex_path = "/product/app/foo/foo.apk";
512 is_shared = true;
513
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100514 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100515 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
516 SetExpectations();
517 RunTest();
518}
519
Justin Yun3db26d52019-12-16 14:09:39 +0900520TEST_P(NativeLoaderTest_Create, UnbundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100521 dex_path = "/product/app/foo/foo.apk";
522 is_shared = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100523
Justin Yun3db26d52019-12-16 14:09:39 +0900524 if (is_product_vndk_version_defined()) {
525 expected_namespace_name = "vendor-classloader-namespace";
526 expected_library_path = expected_library_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
527 expected_permitted_path =
528 expected_permitted_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
529 expected_shared_libs_to_platform_ns =
Justin Yun089c1352020-02-06 16:53:08 +0900530 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_product();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900531 expected_link_with_vndk_product_ns = true;
Justin Yun3db26d52019-12-16 14:09:39 +0900532 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100533 SetExpectations();
534 RunTest();
535}
536
537TEST_P(NativeLoaderTest_Create, NamespaceForSharedLibIsNotUsedAsAnonymousNamespace) {
538 if (IsBridged()) {
539 // There is no shared lib in translated arch
540 // TODO(jiyong): revisit this
541 return;
542 }
543 // compared to apks, for java shared libs, library_path is empty; java shared
544 // libs don't have their own native libs. They use platform's.
545 library_path = "";
546 expected_library_path = library_path;
547 // no ALSO_USED_AS_ANONYMOUS
548 expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
549 SetExpectations();
550 RunTest();
551}
552
553TEST_P(NativeLoaderTest_Create, TwoApks) {
554 SetExpectations();
555 const uint32_t second_app_target_sdk_version = 29;
556 const std::string second_app_class_loader = "second_app_classloader";
557 const bool second_app_is_shared = false;
558 const std::string second_app_dex_path = "/data/app/bar/classes.dex";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000559 const std::string second_app_library_path = "/data/app/bar/" LIB_DIR "/arm";
560 const std::string second_app_permitted_path = "/data/app/bar/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100561 const std::string expected_second_app_permitted_path =
562 std::string("/data:/mnt/expand:") + second_app_permitted_path;
563 const std::string expected_second_app_parent_namespace = "classloader-namespace";
564 // no ALSO_USED_AS_ANONYMOUS
565 const uint64_t expected_second_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
566
567 // The scenario is that second app is loaded by the first app.
568 // So the first app's classloader (`classloader`) is parent of the second
569 // app's classloader.
570 ON_CALL(*mock, JniObject_getParent(StrEq(second_app_class_loader)))
571 .WillByDefault(Return(class_loader.c_str()));
572
573 // namespace for the second app is created. Its parent is set to the namespace
574 // of the first app.
575 EXPECT_CALL(*mock, mock_create_namespace(
576 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
577 StrEq(second_app_library_path), expected_second_namespace_flags,
578 StrEq(expected_second_app_permitted_path), NsEq(dex_path.c_str())))
579 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(second_app_dex_path.c_str()))));
580 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), NsEq(second_app_dex_path.c_str()), _, _))
581 .WillRepeatedly(Return(true));
582
583 RunTest();
584 jstring err = CreateClassLoaderNamespace(
585 env(), second_app_target_sdk_version, env()->NewStringUTF(second_app_class_loader.c_str()),
586 second_app_is_shared, env()->NewStringUTF(second_app_dex_path.c_str()),
587 env()->NewStringUTF(second_app_library_path.c_str()),
Martin Stjernholmb3092402020-09-04 00:49:44 +0100588 env()->NewStringUTF(second_app_permitted_path.c_str()), /*uses_library_list=*/ nullptr);
Orion Hodson9b16e342019-10-09 13:29:16 +0100589
590 // success
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100591 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100592
593 if (!IsBridged()) {
594 struct android_namespace_t* ns =
595 FindNamespaceByClassLoader(env(), env()->NewStringUTF(second_app_class_loader.c_str()));
596
597 // The created namespace is for the second apk
598 EXPECT_EQ(second_app_dex_path.c_str(), reinterpret_cast<const char*>(ns));
599 } else {
600 struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
601 env(), env()->NewStringUTF(second_app_class_loader.c_str()));
602
603 // The created namespace is for the second apk
604 EXPECT_STREQ(second_app_dex_path.c_str(),
605 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
606 }
607}
608
609INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
610
611const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
612 [](const struct ConfigEntry&) -> Result<bool> { return true; };
613
614TEST(NativeLoaderConfigParser, NamesAndComments) {
615 const char file_content[] = R"(
616######
617
618libA.so
619#libB.so
620
621
622 libC.so
623libD.so
624 #### libE.so
625)";
626 const std::vector<std::string> expected_result = {"libA.so", "libC.so", "libD.so"};
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, WithBitness) {
633 const char file_content[] = R"(
634libA.so 32
635libB.so 64
636libC.so
637)";
638#if defined(__LP64__)
639 const std::vector<std::string> expected_result = {"libB.so", "libC.so"};
640#else
641 const std::vector<std::string> expected_result = {"libA.so", "libC.so"};
642#endif
643 Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900644 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100645 ASSERT_EQ(expected_result, *result);
646}
647
648TEST(NativeLoaderConfigParser, WithNoPreload) {
649 const char file_content[] = R"(
650libA.so nopreload
651libB.so nopreload
652libC.so
653)";
654
655 const std::vector<std::string> expected_result = {"libC.so"};
656 Result<std::vector<std::string>> result =
657 ParseConfig(file_content,
658 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900659 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100660 ASSERT_EQ(expected_result, *result);
661}
662
663TEST(NativeLoaderConfigParser, WithNoPreloadAndBitness) {
664 const char file_content[] = R"(
665libA.so nopreload 32
666libB.so 64 nopreload
667libC.so 32
668libD.so 64
669libE.so nopreload
670)";
671
672#if defined(__LP64__)
673 const std::vector<std::string> expected_result = {"libD.so"};
674#else
675 const std::vector<std::string> expected_result = {"libC.so"};
676#endif
677 Result<std::vector<std::string>> result =
678 ParseConfig(file_content,
679 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900680 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100681 ASSERT_EQ(expected_result, *result);
682}
683
684TEST(NativeLoaderConfigParser, RejectMalformed) {
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900685 ASSERT_FALSE(ParseConfig("libA.so 32 64", always_true).ok());
686 ASSERT_FALSE(ParseConfig("libA.so 32 32", always_true).ok());
687 ASSERT_FALSE(ParseConfig("libA.so 32 nopreload 64", always_true).ok());
688 ASSERT_FALSE(ParseConfig("32 libA.so nopreload", always_true).ok());
689 ASSERT_FALSE(ParseConfig("nopreload libA.so 32", always_true).ok());
690 ASSERT_FALSE(ParseConfig("libA.so nopreload # comment", always_true).ok());
Orion Hodson9b16e342019-10-09 13:29:16 +0100691}
692
Jooyung Han538f99a2020-03-03 00:46:50 +0900693TEST(NativeLoaderJniConfigParser, BasicLoading) {
694 const char file_content[] = R"(
695# comment
696com_android_foo libfoo.so
697# Empty line is ignored
698
699com_android_bar libbar.so:libbar2.so
700)";
701
702 std::map<std::string, std::string> expected_result{
703 {"com_android_foo", "libfoo.so"},
704 {"com_android_bar", "libbar.so:libbar2.so"},
705 };
706
707 Result<std::map<std::string, std::string>> result = ParseJniConfig(file_content);
708 ASSERT_RESULT_OK(result);
709 ASSERT_EQ(expected_result, *result);
710}
711
712TEST(NativeLoaderJniConfigParser, RejectMalformed) {
713 ASSERT_FALSE(ParseJniConfig("com_android_foo").ok());
714}
715
Orion Hodson9b16e342019-10-09 13:29:16 +0100716} // namespace nativeloader
717} // namespace android
Nicolas Geoffray7ca8b672020-04-24 15:43:48 +0100718
719#endif // defined(ART_TARGET_ANDROID)