blob: 43c3c151c925bbd91b00261eefb3b8cf47475a55 [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 Hancd616d02020-09-01 14:53:23 +090044using internal::ParseApexLibrariesConfig;
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"),
Martin Stjernholmb3092402020-09-04 00:49:44 +0100102 NAMESPACE_ENTRY("com_android_art"),
103 NAMESPACE_ENTRY("default"),
104 NAMESPACE_ENTRY("sphal"),
105 NAMESPACE_ENTRY("system"),
106 NAMESPACE_ENTRY("vndk"),
107 NAMESPACE_ENTRY("vndk_product"),
108#undef NAMESPACE_ENTRY
Orion Hodson9b16e342019-10-09 13:29:16 +0100109};
110
111// The actual gmock object
112class MockPlatform : public Platform {
113 public:
114 explicit MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
115 ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
116 ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
117 ON_CALL(*this, mock_get_exported_namespace(_, _))
Martin Stjernholm48297332019-11-12 21:21:32 +0000118 .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
Orion Hodson9b16e342019-10-09 13:29:16 +0100119 if (namespaces.find(name) != namespaces.end()) {
120 return namespaces[name];
121 }
Martin Stjernholmb3092402020-09-04 00:49:44 +0100122 std::string msg = android::base::StringPrintf("(namespace %s not found)", name);
123 // The strdup'ed string will leak, but the test is already failing if we get here.
124 return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(strdup(msg.c_str())));
Orion Hodson9b16e342019-10-09 13:29:16 +0100125 }));
126 }
127
128 // Mocking libdl APIs
129 MOCK_METHOD2(dlopen, void*(const char*, int));
130 MOCK_METHOD1(dlclose, int(void*));
131 MOCK_METHOD0(dlerror, char*());
132
133 // Mocking the common APIs
134 MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
135 MOCK_METHOD7(mock_create_namespace,
136 mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
137 const char*, mock_namespace_handle));
138 MOCK_METHOD4(mock_link_namespaces,
139 bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
140 MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
141 MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
142
143 // Mocking libnativebridge APIs
144 MOCK_METHOD0(NativeBridgeInitialized, bool());
145 MOCK_METHOD0(NativeBridgeGetError, const char*());
146 MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
147 MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
148
149 // Mocking "ClassLoader Object.getParent()"
150 MOCK_METHOD1(JniObject_getParent, const char*(const char*));
151
152 private:
153 bool is_bridged_;
154};
155
156static std::unique_ptr<MockPlatform> mock;
157
158// Provide C wrappers for the mock object.
159extern "C" {
160void* dlopen(const char* file, int flag) {
161 return mock->dlopen(file, flag);
162}
163
164int dlclose(void* handle) {
165 return mock->dlclose(handle);
166}
167
168char* dlerror(void) {
169 return mock->dlerror();
170}
171
172bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
173 return mock->mock_init_anonymous_namespace(false, sonames, search_path);
174}
175
176struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
177 const char* default_library_path,
178 uint64_t type,
179 const char* permitted_when_isolated_path,
180 struct android_namespace_t* parent) {
181 return TO_ANDROID_NAMESPACE(
182 mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
183 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
184}
185
186bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
187 const char* sonames) {
188 return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
189}
190
191struct android_namespace_t* android_get_exported_namespace(const char* name) {
192 return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
193}
194
195void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
196 return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
197}
198
199// libnativebridge APIs
200bool NativeBridgeIsSupported(const char* libpath) {
201 return mock->NativeBridgeIsSupported(libpath);
202}
203
204struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
205 return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
206}
207
208struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
209 const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
210 const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
211 return TO_BRIDGED_NAMESPACE(
212 mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
213 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
214}
215
216bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
217 struct native_bridge_namespace_t* to, const char* sonames) {
218 return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
219}
220
221void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
222 struct native_bridge_namespace_t* ns) {
223 return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
224}
225
226bool NativeBridgeInitialized() {
227 return mock->NativeBridgeInitialized();
228}
229
230bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
231 const char* anon_ns_library_path) {
232 return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
233}
234
235const char* NativeBridgeGetError() {
236 return mock->NativeBridgeGetError();
237}
238
239bool NativeBridgeIsPathSupported(const char* path) {
240 return mock->NativeBridgeIsPathSupported(path);
241}
242
243} // extern "C"
244
245// A very simple JNI mock.
246// jstring is a pointer to utf8 char array. We don't need utf16 char here.
247// jobject, jclass, and jmethodID are also a pointer to utf8 char array
248// Only a few JNI methods that are actually used in libnativeloader are mocked.
249JNINativeInterface* CreateJNINativeInterface() {
250 JNINativeInterface* inf = new JNINativeInterface();
251 memset(inf, 0, sizeof(JNINativeInterface));
252
253 inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
254 return reinterpret_cast<const char*>(s);
255 };
256
257 inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
258
259 inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
260 return reinterpret_cast<jstring>(const_cast<char*>(bytes));
261 };
262
263 inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
264 return reinterpret_cast<jclass>(const_cast<char*>(name));
265 };
266
267 inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
268 if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
269 // JniObject_getParent can be a valid jobject or nullptr if there is
270 // no parent classloader.
271 const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
272 return reinterpret_cast<jobject>(const_cast<char*>(ret));
273 }
274 return nullptr;
275 };
276
277 inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
278 return reinterpret_cast<jmethodID>(const_cast<char*>(name));
279 };
280
281 inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
282
283 inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
284 return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
285 };
286
287 return inf;
288}
289
290static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
291
292// Custom matcher for comparing namespace handles
293MATCHER_P(NsEq, other, "") {
294 *result_listener << "comparing " << reinterpret_cast<const char*>(arg) << " and " << other;
295 return strcmp(reinterpret_cast<const char*>(arg), reinterpret_cast<const char*>(other)) == 0;
296}
297
298/////////////////////////////////////////////////////////////////
299
300// Test fixture
301class NativeLoaderTest : public ::testing::TestWithParam<bool> {
302 protected:
303 bool IsBridged() { return GetParam(); }
304
305 void SetUp() override {
Martin Stjernholm48297332019-11-12 21:21:32 +0000306 mock = std::make_unique<testing::NiceMock<MockPlatform>>(IsBridged());
Orion Hodson9b16e342019-10-09 13:29:16 +0100307
308 env = std::make_unique<JNIEnv>();
309 env->functions = CreateJNINativeInterface();
310 }
311
312 void SetExpectations() {
313 std::vector<std::string> default_public_libs =
314 android::base::Split(preloadable_public_libraries(), ":");
315 for (auto l : default_public_libs) {
316 EXPECT_CALL(*mock, dlopen(StrEq(l.c_str()), RTLD_NOW | RTLD_NODELETE))
317 .WillOnce(Return(any_nonnull));
318 }
319 }
320
321 void RunTest() { InitializeNativeLoader(); }
322
323 void TearDown() override {
324 ResetNativeLoader();
325 delete env->functions;
326 mock.reset();
327 }
328
329 std::unique_ptr<JNIEnv> env;
330};
331
332/////////////////////////////////////////////////////////////////
333
334TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
335 SetExpectations();
336 RunTest();
337}
338
339INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
340
341/////////////////////////////////////////////////////////////////
342
343class NativeLoaderTest_Create : public NativeLoaderTest {
344 protected:
345 // Test inputs (initialized to the default values). Overriding these
346 // must be done before calling SetExpectations() and RunTest().
347 uint32_t target_sdk_version = 29;
348 std::string class_loader = "my_classloader";
349 bool is_shared = false;
350 std::string dex_path = "/data/app/foo/classes.dex";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000351 std::string library_path = "/data/app/foo/" LIB_DIR "/arm";
352 std::string permitted_path = "/data/app/foo/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100353
354 // expected output (.. for the default test inputs)
355 std::string expected_namespace_name = "classloader-namespace";
356 uint64_t expected_namespace_flags =
357 ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS;
358 std::string expected_library_path = library_path;
359 std::string expected_permitted_path = std::string("/data:/mnt/expand:") + permitted_path;
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900360 std::string expected_parent_namespace = "system";
Orion Hodson9b16e342019-10-09 13:29:16 +0100361 bool expected_link_with_platform_ns = true;
362 bool expected_link_with_art_ns = true;
Victor Changd20e51d2020-05-05 16:01:19 +0100363 bool expected_link_with_i18n_ns = true;
Orion Hodson9b16e342019-10-09 13:29:16 +0100364 bool expected_link_with_sphal_ns = !vendor_public_libraries().empty();
365 bool expected_link_with_vndk_ns = false;
Justin Yuneb4f08c2020-02-18 11:29:07 +0900366 bool expected_link_with_vndk_product_ns = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100367 bool expected_link_with_default_ns = false;
368 bool expected_link_with_neuralnetworks_ns = true;
369 std::string expected_shared_libs_to_platform_ns = default_public_libraries();
Jooyung Hancd616d02020-09-01 14:53:23 +0900370 std::string expected_shared_libs_to_art_ns = apex_public_libraries().at("com_android_art");
371 std::string expected_shared_libs_to_i18n_ns = apex_public_libraries().at("com_android_i18n");
Orion Hodson9b16e342019-10-09 13:29:16 +0100372 std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900373 std::string expected_shared_libs_to_vndk_ns = vndksp_libraries_vendor();
374 std::string expected_shared_libs_to_vndk_product_ns = vndksp_libraries_product();
Orion Hodson9b16e342019-10-09 13:29:16 +0100375 std::string expected_shared_libs_to_default_ns = default_public_libraries();
Jooyung Hancd616d02020-09-01 14:53:23 +0900376 std::string expected_shared_libs_to_neuralnetworks_ns = apex_public_libraries().at("com_android_neuralnetworks");
Orion Hodson9b16e342019-10-09 13:29:16 +0100377
378 void SetExpectations() {
379 NativeLoaderTest::SetExpectations();
380
381 ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
382
Martin Stjernholm48297332019-11-12 21:21:32 +0000383 EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(testing::AnyNumber());
384 EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(testing::AnyNumber());
Orion Hodson9b16e342019-10-09 13:29:16 +0100385
386 EXPECT_CALL(*mock, mock_create_namespace(
387 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
388 StrEq(expected_library_path), expected_namespace_flags,
389 StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
390 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
391 if (expected_link_with_platform_ns) {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900392 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("system"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100393 StrEq(expected_shared_libs_to_platform_ns)))
394 .WillOnce(Return(true));
395 }
396 if (expected_link_with_art_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900397 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_art"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100398 StrEq(expected_shared_libs_to_art_ns)))
399 .WillOnce(Return(true));
400 }
Victor Changd20e51d2020-05-05 16:01:19 +0100401 if (expected_link_with_i18n_ns) {
402 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_i18n"),
403 StrEq(expected_shared_libs_to_i18n_ns)))
404 .WillOnce(Return(true));
405 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100406 if (expected_link_with_sphal_ns) {
407 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
408 StrEq(expected_shared_libs_to_sphal_ns)))
409 .WillOnce(Return(true));
410 }
411 if (expected_link_with_vndk_ns) {
412 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
413 StrEq(expected_shared_libs_to_vndk_ns)))
414 .WillOnce(Return(true));
415 }
Justin Yuneb4f08c2020-02-18 11:29:07 +0900416 if (expected_link_with_vndk_product_ns) {
417 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk_product"),
418 StrEq(expected_shared_libs_to_vndk_product_ns)))
419 .WillOnce(Return(true));
420 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100421 if (expected_link_with_default_ns) {
422 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
423 StrEq(expected_shared_libs_to_default_ns)))
424 .WillOnce(Return(true));
425 }
426 if (expected_link_with_neuralnetworks_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900427 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_neuralnetworks"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100428 StrEq(expected_shared_libs_to_neuralnetworks_ns)))
429 .WillOnce(Return(true));
430 }
431 }
432
433 void RunTest() {
434 NativeLoaderTest::RunTest();
435
436 jstring err = CreateClassLoaderNamespace(
437 env(), target_sdk_version, env()->NewStringUTF(class_loader.c_str()), is_shared,
438 env()->NewStringUTF(dex_path.c_str()), env()->NewStringUTF(library_path.c_str()),
Martin Stjernholmb3092402020-09-04 00:49:44 +0100439 env()->NewStringUTF(permitted_path.c_str()), /*uses_library_list=*/ nullptr);
Orion Hodson9b16e342019-10-09 13:29:16 +0100440
441 // no error
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100442 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100443
444 if (!IsBridged()) {
445 struct android_namespace_t* ns =
446 FindNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
447
448 // The created namespace is for this apk
449 EXPECT_EQ(dex_path.c_str(), reinterpret_cast<const char*>(ns));
450 } else {
451 struct NativeLoaderNamespace* ns =
452 FindNativeLoaderNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
453
454 // The created namespace is for the this apk
455 EXPECT_STREQ(dex_path.c_str(),
456 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
457 }
458 }
459
460 JNIEnv* env() { return NativeLoaderTest::env.get(); }
461};
462
463TEST_P(NativeLoaderTest_Create, DownloadedApp) {
464 SetExpectations();
465 RunTest();
466}
467
468TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
469 dex_path = "/system/app/foo/foo.apk";
470 is_shared = true;
471
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100472 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100473 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
474 SetExpectations();
475 RunTest();
476}
477
478TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
479 dex_path = "/vendor/app/foo/foo.apk";
480 is_shared = true;
481
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100482 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100483 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
484 SetExpectations();
485 RunTest();
486}
487
488TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
489 dex_path = "/vendor/app/foo/foo.apk";
490 is_shared = false;
491
492 expected_namespace_name = "vendor-classloader-namespace";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000493 expected_library_path = expected_library_path + ":/vendor/" LIB_DIR;
494 expected_permitted_path = expected_permitted_path + ":/vendor/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100495 expected_shared_libs_to_platform_ns =
Justin Yun089c1352020-02-06 16:53:08 +0900496 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_vendor();
Orion Hodson9b16e342019-10-09 13:29:16 +0100497 expected_link_with_vndk_ns = true;
498 SetExpectations();
499 RunTest();
500}
501
Justin Yun3db26d52019-12-16 14:09:39 +0900502TEST_P(NativeLoaderTest_Create, BundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100503 dex_path = "/product/app/foo/foo.apk";
504 is_shared = true;
505
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100506 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100507 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
508 SetExpectations();
509 RunTest();
510}
511
Justin Yun3db26d52019-12-16 14:09:39 +0900512TEST_P(NativeLoaderTest_Create, UnbundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100513 dex_path = "/product/app/foo/foo.apk";
514 is_shared = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100515
Justin Yun3db26d52019-12-16 14:09:39 +0900516 if (is_product_vndk_version_defined()) {
517 expected_namespace_name = "vendor-classloader-namespace";
518 expected_library_path = expected_library_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
519 expected_permitted_path =
520 expected_permitted_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
521 expected_shared_libs_to_platform_ns =
Justin Yun089c1352020-02-06 16:53:08 +0900522 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_product();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900523 expected_link_with_vndk_product_ns = true;
Justin Yun3db26d52019-12-16 14:09:39 +0900524 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100525 SetExpectations();
526 RunTest();
527}
528
529TEST_P(NativeLoaderTest_Create, NamespaceForSharedLibIsNotUsedAsAnonymousNamespace) {
530 if (IsBridged()) {
531 // There is no shared lib in translated arch
532 // TODO(jiyong): revisit this
533 return;
534 }
535 // compared to apks, for java shared libs, library_path is empty; java shared
536 // libs don't have their own native libs. They use platform's.
537 library_path = "";
538 expected_library_path = library_path;
539 // no ALSO_USED_AS_ANONYMOUS
540 expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
541 SetExpectations();
542 RunTest();
543}
544
545TEST_P(NativeLoaderTest_Create, TwoApks) {
546 SetExpectations();
547 const uint32_t second_app_target_sdk_version = 29;
548 const std::string second_app_class_loader = "second_app_classloader";
549 const bool second_app_is_shared = false;
550 const std::string second_app_dex_path = "/data/app/bar/classes.dex";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000551 const std::string second_app_library_path = "/data/app/bar/" LIB_DIR "/arm";
552 const std::string second_app_permitted_path = "/data/app/bar/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100553 const std::string expected_second_app_permitted_path =
554 std::string("/data:/mnt/expand:") + second_app_permitted_path;
555 const std::string expected_second_app_parent_namespace = "classloader-namespace";
556 // no ALSO_USED_AS_ANONYMOUS
557 const uint64_t expected_second_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
558
559 // The scenario is that second app is loaded by the first app.
560 // So the first app's classloader (`classloader`) is parent of the second
561 // app's classloader.
562 ON_CALL(*mock, JniObject_getParent(StrEq(second_app_class_loader)))
563 .WillByDefault(Return(class_loader.c_str()));
564
565 // namespace for the second app is created. Its parent is set to the namespace
566 // of the first app.
567 EXPECT_CALL(*mock, mock_create_namespace(
568 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
569 StrEq(second_app_library_path), expected_second_namespace_flags,
570 StrEq(expected_second_app_permitted_path), NsEq(dex_path.c_str())))
571 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(second_app_dex_path.c_str()))));
572 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), NsEq(second_app_dex_path.c_str()), _, _))
573 .WillRepeatedly(Return(true));
574
575 RunTest();
576 jstring err = CreateClassLoaderNamespace(
577 env(), second_app_target_sdk_version, env()->NewStringUTF(second_app_class_loader.c_str()),
578 second_app_is_shared, env()->NewStringUTF(second_app_dex_path.c_str()),
579 env()->NewStringUTF(second_app_library_path.c_str()),
Martin Stjernholmb3092402020-09-04 00:49:44 +0100580 env()->NewStringUTF(second_app_permitted_path.c_str()), /*uses_library_list=*/ nullptr);
Orion Hodson9b16e342019-10-09 13:29:16 +0100581
582 // success
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100583 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100584
585 if (!IsBridged()) {
586 struct android_namespace_t* ns =
587 FindNamespaceByClassLoader(env(), env()->NewStringUTF(second_app_class_loader.c_str()));
588
589 // The created namespace is for the second apk
590 EXPECT_EQ(second_app_dex_path.c_str(), reinterpret_cast<const char*>(ns));
591 } else {
592 struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
593 env(), env()->NewStringUTF(second_app_class_loader.c_str()));
594
595 // The created namespace is for the second apk
596 EXPECT_STREQ(second_app_dex_path.c_str(),
597 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
598 }
599}
600
601INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
602
603const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
604 [](const struct ConfigEntry&) -> Result<bool> { return true; };
605
606TEST(NativeLoaderConfigParser, NamesAndComments) {
607 const char file_content[] = R"(
608######
609
610libA.so
611#libB.so
612
613
614 libC.so
615libD.so
616 #### libE.so
617)";
618 const std::vector<std::string> expected_result = {"libA.so", "libC.so", "libD.so"};
619 Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900620 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100621 ASSERT_EQ(expected_result, *result);
622}
623
624TEST(NativeLoaderConfigParser, WithBitness) {
625 const char file_content[] = R"(
626libA.so 32
627libB.so 64
628libC.so
629)";
630#if defined(__LP64__)
631 const std::vector<std::string> expected_result = {"libB.so", "libC.so"};
632#else
633 const std::vector<std::string> expected_result = {"libA.so", "libC.so"};
634#endif
635 Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900636 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100637 ASSERT_EQ(expected_result, *result);
638}
639
640TEST(NativeLoaderConfigParser, WithNoPreload) {
641 const char file_content[] = R"(
642libA.so nopreload
643libB.so nopreload
644libC.so
645)";
646
647 const std::vector<std::string> expected_result = {"libC.so"};
648 Result<std::vector<std::string>> result =
649 ParseConfig(file_content,
650 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900651 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100652 ASSERT_EQ(expected_result, *result);
653}
654
655TEST(NativeLoaderConfigParser, WithNoPreloadAndBitness) {
656 const char file_content[] = R"(
657libA.so nopreload 32
658libB.so 64 nopreload
659libC.so 32
660libD.so 64
661libE.so nopreload
662)";
663
664#if defined(__LP64__)
665 const std::vector<std::string> expected_result = {"libD.so"};
666#else
667 const std::vector<std::string> expected_result = {"libC.so"};
668#endif
669 Result<std::vector<std::string>> result =
670 ParseConfig(file_content,
671 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900672 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100673 ASSERT_EQ(expected_result, *result);
674}
675
676TEST(NativeLoaderConfigParser, RejectMalformed) {
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900677 ASSERT_FALSE(ParseConfig("libA.so 32 64", always_true).ok());
678 ASSERT_FALSE(ParseConfig("libA.so 32 32", always_true).ok());
679 ASSERT_FALSE(ParseConfig("libA.so 32 nopreload 64", always_true).ok());
680 ASSERT_FALSE(ParseConfig("32 libA.so nopreload", always_true).ok());
681 ASSERT_FALSE(ParseConfig("nopreload libA.so 32", always_true).ok());
682 ASSERT_FALSE(ParseConfig("libA.so nopreload # comment", always_true).ok());
Orion Hodson9b16e342019-10-09 13:29:16 +0100683}
684
Jooyung Hancd616d02020-09-01 14:53:23 +0900685TEST(NativeLoaderApexLibrariesConfigParser, BasicLoading) {
Jooyung Han538f99a2020-03-03 00:46:50 +0900686 const char file_content[] = R"(
687# comment
Jooyung Hancd616d02020-09-01 14:53:23 +0900688jni com_android_foo libfoo.so
Jooyung Han538f99a2020-03-03 00:46:50 +0900689# Empty line is ignored
690
Jooyung Hancd616d02020-09-01 14:53:23 +0900691jni com_android_bar libbar.so:libbar2.so
692
693 public com_android_bar libpublic.so
Jooyung Han538f99a2020-03-03 00:46:50 +0900694)";
695
Jooyung Hancd616d02020-09-01 14:53:23 +0900696 auto jni_libs = ParseApexLibrariesConfig(file_content, "jni");
697 ASSERT_RESULT_OK(jni_libs);
698 std::map<std::string, std::string> expected_jni_libs {
Jooyung Han538f99a2020-03-03 00:46:50 +0900699 {"com_android_foo", "libfoo.so"},
700 {"com_android_bar", "libbar.so:libbar2.so"},
701 };
Jooyung Hancd616d02020-09-01 14:53:23 +0900702 ASSERT_EQ(expected_jni_libs, *jni_libs);
Jooyung Han538f99a2020-03-03 00:46:50 +0900703
Jooyung Hancd616d02020-09-01 14:53:23 +0900704 auto public_libs = ParseApexLibrariesConfig(file_content, "public");
705 ASSERT_RESULT_OK(public_libs);
706 std::map<std::string, std::string> expected_public_libs {
707 {"com_android_bar", "libpublic.so"},
708 };
709 ASSERT_EQ(expected_public_libs, *public_libs);
Jooyung Han538f99a2020-03-03 00:46:50 +0900710}
711
Jooyung Hancd616d02020-09-01 14:53:23 +0900712TEST(NativeLoaderApexLibrariesConfigParser, RejectMalformedLine) {
713 const char file_content[] = R"(
714jni com_android_foo libfoo
715# missing <library list>
716jni com_android_bar
717)";
718 auto result = ParseApexLibrariesConfig(file_content, "jni");
719 ASSERT_FALSE(result.ok());
720 ASSERT_EQ("Malformed line \"jni com_android_bar\"", result.error().message());
Jooyung Han538f99a2020-03-03 00:46:50 +0900721}
722
Jooyung Hancd616d02020-09-01 14:53:23 +0900723TEST(NativeLoaderApexLibrariesConfigParser, RejectInvalidTag) {
724 const char file_content[] = R"(
725jni apex1 lib
726public apex2 lib
727# unknown tag
728unknown com_android_foo libfoo
729)";
730 auto result = ParseApexLibrariesConfig(file_content, "jni");
731 ASSERT_FALSE(result.ok());
732 ASSERT_EQ("Invalid tag \"unknown com_android_foo libfoo\"", result.error().message());
733}
734
735TEST(NativeLoaderApexLibrariesConfigParser, RejectInvalidApexNamespace) {
736 const char file_content[] = R"(
737# apex linker namespace should be mangled ('.' -> '_')
738jni com.android.foo lib
739)";
740 auto result = ParseApexLibrariesConfig(file_content, "jni");
741 ASSERT_FALSE(result.ok());
742 ASSERT_EQ("Invalid apex_namespace \"jni com.android.foo lib\"", result.error().message());
743}
744
745TEST(NativeLoaderApexLibrariesConfigParser, RejectInvalidLibraryList) {
746 const char file_content[] = R"(
747# library list is ":" separated list of filenames
748jni com_android_foo lib64/libfoo.so
749)";
750 auto result = ParseApexLibrariesConfig(file_content, "jni");
751 ASSERT_FALSE(result.ok());
752 ASSERT_EQ("Invalid library_list \"jni com_android_foo lib64/libfoo.so\"", result.error().message());
753}
754
755
Orion Hodson9b16e342019-10-09 13:29:16 +0100756} // namespace nativeloader
757} // namespace android
Nicolas Geoffray7ca8b672020-04-24 15:43:48 +0100758
759#endif // defined(ART_TARGET_ANDROID)