blob: 3f2505c2de8e78fb427e8169208e1bb6291d725f [file] [log] [blame]
Orion Hodson9b16e342019-10-09 13:29:16 +01001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <dlfcn.h>
18#include <memory>
19#include <unordered_map>
20
21#include <android-base/strings.h>
22#include <gmock/gmock.h>
23#include <gtest/gtest.h>
24#include <jni.h>
25
26#include "native_loader_namespace.h"
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +010027#include "nativehelper/scoped_utf_chars.h"
Orion Hodson9b16e342019-10-09 13:29:16 +010028#include "nativeloader/dlext_namespaces.h"
29#include "nativeloader/native_loader.h"
30#include "public_libraries.h"
31
Orion Hodson9b16e342019-10-09 13:29:16 +010032namespace android {
33namespace nativeloader {
34
Martin Stjernholm48297332019-11-12 21:21:32 +000035using ::testing::Eq;
36using ::testing::Return;
37using ::testing::StrEq;
38using ::testing::_;
39using internal::ConfigEntry;
40using internal::ParseConfig;
Jooyung Han538f99a2020-03-03 00:46:50 +090041using internal::ParseJniConfig;
Martin Stjernholm48297332019-11-12 21:21:32 +000042
Martin Stjernholmbe08b202019-11-12 20:11:00 +000043#if defined(__LP64__)
44#define LIB_DIR "lib64"
45#else
46#define LIB_DIR "lib"
47#endif
48
Orion Hodson9b16e342019-10-09 13:29:16 +010049// gmock interface that represents interested platform APIs on libdl and libnativebridge
50class Platform {
51 public:
52 virtual ~Platform() {}
53
54 // libdl APIs
55 virtual void* dlopen(const char* filename, int flags) = 0;
56 virtual int dlclose(void* handle) = 0;
57 virtual char* dlerror(void) = 0;
58
59 // These mock_* are the APIs semantically the same across libdl and libnativebridge.
60 // Instead of having two set of mock APIs for the two, define only one set with an additional
61 // argument 'bool bridged' to identify the context (i.e., called for libdl or libnativebridge).
62 typedef char* mock_namespace_handle;
63 virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
64 const char* search_paths) = 0;
65 virtual mock_namespace_handle mock_create_namespace(
66 bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
67 uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
68 virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
69 mock_namespace_handle to, const char* sonames) = 0;
70 virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
71 virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
72 mock_namespace_handle ns) = 0;
73
74 // libnativebridge APIs for which libdl has no corresponding APIs
75 virtual bool NativeBridgeInitialized() = 0;
76 virtual const char* NativeBridgeGetError() = 0;
77 virtual bool NativeBridgeIsPathSupported(const char*) = 0;
78 virtual bool NativeBridgeIsSupported(const char*) = 0;
79
80 // To mock "ClassLoader Object.getParent()"
81 virtual const char* JniObject_getParent(const char*) = 0;
82};
83
84// The mock does not actually create a namespace object. But simply casts the pointer to the
85// string for the namespace name as the handle to the namespace object.
86#define TO_ANDROID_NAMESPACE(str) \
87 reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
88
89#define TO_BRIDGED_NAMESPACE(str) \
90 reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
91
92#define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
93
94// These represents built-in namespaces created by the linker according to ld.config.txt
95static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +090096 {"system", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("system"))},
Orion Hodson9b16e342019-10-09 13:29:16 +010097 {"default", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("default"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +090098 {"com_android_art", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_art"))},
Orion Hodson9b16e342019-10-09 13:29:16 +010099 {"sphal", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("sphal"))},
100 {"vndk", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk"))},
Justin Yuneb4f08c2020-02-18 11:29:07 +0900101 {"vndk_product", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk_product"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900102 {"com_android_neuralnetworks", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_neuralnetworks"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900103 {"com_android_os_statsd", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_os_statsd"))},
Orion Hodson9b16e342019-10-09 13:29:16 +0100104};
105
106// The actual gmock object
107class MockPlatform : public Platform {
108 public:
109 explicit MockPlatform(bool is_bridged) : is_bridged_(is_bridged) {
110 ON_CALL(*this, NativeBridgeIsSupported(_)).WillByDefault(Return(is_bridged_));
111 ON_CALL(*this, NativeBridgeIsPathSupported(_)).WillByDefault(Return(is_bridged_));
112 ON_CALL(*this, mock_get_exported_namespace(_, _))
Martin Stjernholm48297332019-11-12 21:21:32 +0000113 .WillByDefault(testing::Invoke([](bool, const char* name) -> mock_namespace_handle {
Orion Hodson9b16e342019-10-09 13:29:16 +0100114 if (namespaces.find(name) != namespaces.end()) {
115 return namespaces[name];
116 }
117 return TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("(namespace not found"));
118 }));
119 }
120
121 // Mocking libdl APIs
122 MOCK_METHOD2(dlopen, void*(const char*, int));
123 MOCK_METHOD1(dlclose, int(void*));
124 MOCK_METHOD0(dlerror, char*());
125
126 // Mocking the common APIs
127 MOCK_METHOD3(mock_init_anonymous_namespace, bool(bool, const char*, const char*));
128 MOCK_METHOD7(mock_create_namespace,
129 mock_namespace_handle(bool, const char*, const char*, const char*, uint64_t,
130 const char*, mock_namespace_handle));
131 MOCK_METHOD4(mock_link_namespaces,
132 bool(bool, mock_namespace_handle, mock_namespace_handle, const char*));
133 MOCK_METHOD2(mock_get_exported_namespace, mock_namespace_handle(bool, const char*));
134 MOCK_METHOD4(mock_dlopen_ext, void*(bool, const char*, int, mock_namespace_handle));
135
136 // Mocking libnativebridge APIs
137 MOCK_METHOD0(NativeBridgeInitialized, bool());
138 MOCK_METHOD0(NativeBridgeGetError, const char*());
139 MOCK_METHOD1(NativeBridgeIsPathSupported, bool(const char*));
140 MOCK_METHOD1(NativeBridgeIsSupported, bool(const char*));
141
142 // Mocking "ClassLoader Object.getParent()"
143 MOCK_METHOD1(JniObject_getParent, const char*(const char*));
144
145 private:
146 bool is_bridged_;
147};
148
149static std::unique_ptr<MockPlatform> mock;
150
151// Provide C wrappers for the mock object.
152extern "C" {
153void* dlopen(const char* file, int flag) {
154 return mock->dlopen(file, flag);
155}
156
157int dlclose(void* handle) {
158 return mock->dlclose(handle);
159}
160
161char* dlerror(void) {
162 return mock->dlerror();
163}
164
165bool android_init_anonymous_namespace(const char* sonames, const char* search_path) {
166 return mock->mock_init_anonymous_namespace(false, sonames, search_path);
167}
168
169struct android_namespace_t* android_create_namespace(const char* name, const char* ld_library_path,
170 const char* default_library_path,
171 uint64_t type,
172 const char* permitted_when_isolated_path,
173 struct android_namespace_t* parent) {
174 return TO_ANDROID_NAMESPACE(
175 mock->mock_create_namespace(false, name, ld_library_path, default_library_path, type,
176 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
177}
178
179bool android_link_namespaces(struct android_namespace_t* from, struct android_namespace_t* to,
180 const char* sonames) {
181 return mock->mock_link_namespaces(false, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
182}
183
184struct android_namespace_t* android_get_exported_namespace(const char* name) {
185 return TO_ANDROID_NAMESPACE(mock->mock_get_exported_namespace(false, name));
186}
187
188void* android_dlopen_ext(const char* filename, int flags, const android_dlextinfo* info) {
189 return mock->mock_dlopen_ext(false, filename, flags, TO_MOCK_NAMESPACE(info->library_namespace));
190}
191
192// libnativebridge APIs
193bool NativeBridgeIsSupported(const char* libpath) {
194 return mock->NativeBridgeIsSupported(libpath);
195}
196
197struct native_bridge_namespace_t* NativeBridgeGetExportedNamespace(const char* name) {
198 return TO_BRIDGED_NAMESPACE(mock->mock_get_exported_namespace(true, name));
199}
200
201struct native_bridge_namespace_t* NativeBridgeCreateNamespace(
202 const char* name, const char* ld_library_path, const char* default_library_path, uint64_t type,
203 const char* permitted_when_isolated_path, struct native_bridge_namespace_t* parent) {
204 return TO_BRIDGED_NAMESPACE(
205 mock->mock_create_namespace(true, name, ld_library_path, default_library_path, type,
206 permitted_when_isolated_path, TO_MOCK_NAMESPACE(parent)));
207}
208
209bool NativeBridgeLinkNamespaces(struct native_bridge_namespace_t* from,
210 struct native_bridge_namespace_t* to, const char* sonames) {
211 return mock->mock_link_namespaces(true, TO_MOCK_NAMESPACE(from), TO_MOCK_NAMESPACE(to), sonames);
212}
213
214void* NativeBridgeLoadLibraryExt(const char* libpath, int flag,
215 struct native_bridge_namespace_t* ns) {
216 return mock->mock_dlopen_ext(true, libpath, flag, TO_MOCK_NAMESPACE(ns));
217}
218
219bool NativeBridgeInitialized() {
220 return mock->NativeBridgeInitialized();
221}
222
223bool NativeBridgeInitAnonymousNamespace(const char* public_ns_sonames,
224 const char* anon_ns_library_path) {
225 return mock->mock_init_anonymous_namespace(true, public_ns_sonames, anon_ns_library_path);
226}
227
228const char* NativeBridgeGetError() {
229 return mock->NativeBridgeGetError();
230}
231
232bool NativeBridgeIsPathSupported(const char* path) {
233 return mock->NativeBridgeIsPathSupported(path);
234}
235
236} // extern "C"
237
238// A very simple JNI mock.
239// jstring is a pointer to utf8 char array. We don't need utf16 char here.
240// jobject, jclass, and jmethodID are also a pointer to utf8 char array
241// Only a few JNI methods that are actually used in libnativeloader are mocked.
242JNINativeInterface* CreateJNINativeInterface() {
243 JNINativeInterface* inf = new JNINativeInterface();
244 memset(inf, 0, sizeof(JNINativeInterface));
245
246 inf->GetStringUTFChars = [](JNIEnv*, jstring s, jboolean*) -> const char* {
247 return reinterpret_cast<const char*>(s);
248 };
249
250 inf->ReleaseStringUTFChars = [](JNIEnv*, jstring, const char*) -> void { return; };
251
252 inf->NewStringUTF = [](JNIEnv*, const char* bytes) -> jstring {
253 return reinterpret_cast<jstring>(const_cast<char*>(bytes));
254 };
255
256 inf->FindClass = [](JNIEnv*, const char* name) -> jclass {
257 return reinterpret_cast<jclass>(const_cast<char*>(name));
258 };
259
260 inf->CallObjectMethodV = [](JNIEnv*, jobject obj, jmethodID mid, va_list) -> jobject {
261 if (strcmp("getParent", reinterpret_cast<const char*>(mid)) == 0) {
262 // JniObject_getParent can be a valid jobject or nullptr if there is
263 // no parent classloader.
264 const char* ret = mock->JniObject_getParent(reinterpret_cast<const char*>(obj));
265 return reinterpret_cast<jobject>(const_cast<char*>(ret));
266 }
267 return nullptr;
268 };
269
270 inf->GetMethodID = [](JNIEnv*, jclass, const char* name, const char*) -> jmethodID {
271 return reinterpret_cast<jmethodID>(const_cast<char*>(name));
272 };
273
274 inf->NewWeakGlobalRef = [](JNIEnv*, jobject obj) -> jobject { return obj; };
275
276 inf->IsSameObject = [](JNIEnv*, jobject a, jobject b) -> jboolean {
277 return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)) == 0;
278 };
279
280 return inf;
281}
282
283static void* const any_nonnull = reinterpret_cast<void*>(0x12345678);
284
285// Custom matcher for comparing namespace handles
286MATCHER_P(NsEq, other, "") {
287 *result_listener << "comparing " << reinterpret_cast<const char*>(arg) << " and " << other;
288 return strcmp(reinterpret_cast<const char*>(arg), reinterpret_cast<const char*>(other)) == 0;
289}
290
291/////////////////////////////////////////////////////////////////
292
293// Test fixture
294class NativeLoaderTest : public ::testing::TestWithParam<bool> {
295 protected:
296 bool IsBridged() { return GetParam(); }
297
298 void SetUp() override {
Martin Stjernholm48297332019-11-12 21:21:32 +0000299 mock = std::make_unique<testing::NiceMock<MockPlatform>>(IsBridged());
Orion Hodson9b16e342019-10-09 13:29:16 +0100300
301 env = std::make_unique<JNIEnv>();
302 env->functions = CreateJNINativeInterface();
303 }
304
305 void SetExpectations() {
306 std::vector<std::string> default_public_libs =
307 android::base::Split(preloadable_public_libraries(), ":");
308 for (auto l : default_public_libs) {
309 EXPECT_CALL(*mock, dlopen(StrEq(l.c_str()), RTLD_NOW | RTLD_NODELETE))
310 .WillOnce(Return(any_nonnull));
311 }
312 }
313
314 void RunTest() { InitializeNativeLoader(); }
315
316 void TearDown() override {
317 ResetNativeLoader();
318 delete env->functions;
319 mock.reset();
320 }
321
322 std::unique_ptr<JNIEnv> env;
323};
324
325/////////////////////////////////////////////////////////////////
326
327TEST_P(NativeLoaderTest, InitializeLoadsDefaultPublicLibraries) {
328 SetExpectations();
329 RunTest();
330}
331
332INSTANTIATE_TEST_SUITE_P(NativeLoaderTests, NativeLoaderTest, testing::Bool());
333
334/////////////////////////////////////////////////////////////////
335
336class NativeLoaderTest_Create : public NativeLoaderTest {
337 protected:
338 // Test inputs (initialized to the default values). Overriding these
339 // must be done before calling SetExpectations() and RunTest().
340 uint32_t target_sdk_version = 29;
341 std::string class_loader = "my_classloader";
342 bool is_shared = false;
343 std::string dex_path = "/data/app/foo/classes.dex";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000344 std::string library_path = "/data/app/foo/" LIB_DIR "/arm";
345 std::string permitted_path = "/data/app/foo/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100346
347 // expected output (.. for the default test inputs)
348 std::string expected_namespace_name = "classloader-namespace";
349 uint64_t expected_namespace_flags =
350 ANDROID_NAMESPACE_TYPE_ISOLATED | ANDROID_NAMESPACE_TYPE_ALSO_USED_AS_ANONYMOUS;
351 std::string expected_library_path = library_path;
352 std::string expected_permitted_path = std::string("/data:/mnt/expand:") + permitted_path;
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900353 std::string expected_parent_namespace = "system";
Orion Hodson9b16e342019-10-09 13:29:16 +0100354 bool expected_link_with_platform_ns = true;
355 bool expected_link_with_art_ns = true;
356 bool expected_link_with_sphal_ns = !vendor_public_libraries().empty();
357 bool expected_link_with_vndk_ns = false;
Justin Yuneb4f08c2020-02-18 11:29:07 +0900358 bool expected_link_with_vndk_product_ns = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100359 bool expected_link_with_default_ns = false;
360 bool expected_link_with_neuralnetworks_ns = true;
Jeffrey Huang52575032020-02-11 17:33:45 -0800361 bool expected_link_with_statsd_ns = true;
Orion Hodson9b16e342019-10-09 13:29:16 +0100362 std::string expected_shared_libs_to_platform_ns = default_public_libraries();
363 std::string expected_shared_libs_to_art_ns = art_public_libraries();
364 std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900365 std::string expected_shared_libs_to_vndk_ns = vndksp_libraries_vendor();
366 std::string expected_shared_libs_to_vndk_product_ns = vndksp_libraries_product();
Orion Hodson9b16e342019-10-09 13:29:16 +0100367 std::string expected_shared_libs_to_default_ns = default_public_libraries();
368 std::string expected_shared_libs_to_neuralnetworks_ns = neuralnetworks_public_libraries();
Jeffrey Huang52575032020-02-11 17:33:45 -0800369 std::string expected_shared_libs_to_statsd_ns = statsd_public_libraries();
Orion Hodson9b16e342019-10-09 13:29:16 +0100370
371 void SetExpectations() {
372 NativeLoaderTest::SetExpectations();
373
374 ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
375
Martin Stjernholm48297332019-11-12 21:21:32 +0000376 EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(testing::AnyNumber());
377 EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(testing::AnyNumber());
Orion Hodson9b16e342019-10-09 13:29:16 +0100378
379 EXPECT_CALL(*mock, mock_create_namespace(
380 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
381 StrEq(expected_library_path), expected_namespace_flags,
382 StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
383 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
384 if (expected_link_with_platform_ns) {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900385 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("system"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100386 StrEq(expected_shared_libs_to_platform_ns)))
387 .WillOnce(Return(true));
388 }
389 if (expected_link_with_art_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900390 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_art"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100391 StrEq(expected_shared_libs_to_art_ns)))
392 .WillOnce(Return(true));
393 }
394 if (expected_link_with_sphal_ns) {
395 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
396 StrEq(expected_shared_libs_to_sphal_ns)))
397 .WillOnce(Return(true));
398 }
399 if (expected_link_with_vndk_ns) {
400 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
401 StrEq(expected_shared_libs_to_vndk_ns)))
402 .WillOnce(Return(true));
403 }
Justin Yuneb4f08c2020-02-18 11:29:07 +0900404 if (expected_link_with_vndk_product_ns) {
405 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk_product"),
406 StrEq(expected_shared_libs_to_vndk_product_ns)))
407 .WillOnce(Return(true));
408 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100409 if (expected_link_with_default_ns) {
410 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
411 StrEq(expected_shared_libs_to_default_ns)))
412 .WillOnce(Return(true));
413 }
414 if (expected_link_with_neuralnetworks_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900415 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_neuralnetworks"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100416 StrEq(expected_shared_libs_to_neuralnetworks_ns)))
417 .WillOnce(Return(true));
418 }
Jeffrey Huang52575032020-02-11 17:33:45 -0800419 if (expected_link_with_statsd_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900420 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_os_statsd"),
Jeffrey Huang52575032020-02-11 17:33:45 -0800421 StrEq(expected_shared_libs_to_statsd_ns)))
422 .WillOnce(Return(true));
423 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100424 }
425
426 void RunTest() {
427 NativeLoaderTest::RunTest();
428
429 jstring err = CreateClassLoaderNamespace(
430 env(), target_sdk_version, env()->NewStringUTF(class_loader.c_str()), is_shared,
431 env()->NewStringUTF(dex_path.c_str()), env()->NewStringUTF(library_path.c_str()),
432 env()->NewStringUTF(permitted_path.c_str()));
433
434 // no error
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100435 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100436
437 if (!IsBridged()) {
438 struct android_namespace_t* ns =
439 FindNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
440
441 // The created namespace is for this apk
442 EXPECT_EQ(dex_path.c_str(), reinterpret_cast<const char*>(ns));
443 } else {
444 struct NativeLoaderNamespace* ns =
445 FindNativeLoaderNamespaceByClassLoader(env(), env()->NewStringUTF(class_loader.c_str()));
446
447 // The created namespace is for the this apk
448 EXPECT_STREQ(dex_path.c_str(),
449 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
450 }
451 }
452
453 JNIEnv* env() { return NativeLoaderTest::env.get(); }
454};
455
456TEST_P(NativeLoaderTest_Create, DownloadedApp) {
457 SetExpectations();
458 RunTest();
459}
460
461TEST_P(NativeLoaderTest_Create, BundledSystemApp) {
462 dex_path = "/system/app/foo/foo.apk";
463 is_shared = true;
464
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100465 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100466 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
467 SetExpectations();
468 RunTest();
469}
470
471TEST_P(NativeLoaderTest_Create, BundledVendorApp) {
472 dex_path = "/vendor/app/foo/foo.apk";
473 is_shared = true;
474
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100475 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100476 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
477 SetExpectations();
478 RunTest();
479}
480
481TEST_P(NativeLoaderTest_Create, UnbundledVendorApp) {
482 dex_path = "/vendor/app/foo/foo.apk";
483 is_shared = false;
484
485 expected_namespace_name = "vendor-classloader-namespace";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000486 expected_library_path = expected_library_path + ":/vendor/" LIB_DIR;
487 expected_permitted_path = expected_permitted_path + ":/vendor/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100488 expected_shared_libs_to_platform_ns =
Justin Yun089c1352020-02-06 16:53:08 +0900489 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_vendor();
Orion Hodson9b16e342019-10-09 13:29:16 +0100490 expected_link_with_vndk_ns = true;
491 SetExpectations();
492 RunTest();
493}
494
Justin Yun3db26d52019-12-16 14:09:39 +0900495TEST_P(NativeLoaderTest_Create, BundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100496 dex_path = "/product/app/foo/foo.apk";
497 is_shared = true;
498
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100499 expected_namespace_name = "classloader-namespace-shared";
Orion Hodson9b16e342019-10-09 13:29:16 +0100500 expected_namespace_flags |= ANDROID_NAMESPACE_TYPE_SHARED;
501 SetExpectations();
502 RunTest();
503}
504
Justin Yun3db26d52019-12-16 14:09:39 +0900505TEST_P(NativeLoaderTest_Create, UnbundledProductApp) {
Orion Hodson9b16e342019-10-09 13:29:16 +0100506 dex_path = "/product/app/foo/foo.apk";
507 is_shared = false;
Orion Hodson9b16e342019-10-09 13:29:16 +0100508
Justin Yun3db26d52019-12-16 14:09:39 +0900509 if (is_product_vndk_version_defined()) {
510 expected_namespace_name = "vendor-classloader-namespace";
511 expected_library_path = expected_library_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
512 expected_permitted_path =
513 expected_permitted_path + ":/product/" LIB_DIR ":/system/product/" LIB_DIR;
514 expected_shared_libs_to_platform_ns =
Justin Yun089c1352020-02-06 16:53:08 +0900515 expected_shared_libs_to_platform_ns + ":" + llndk_libraries_product();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900516 expected_link_with_vndk_product_ns = true;
Justin Yun3db26d52019-12-16 14:09:39 +0900517 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100518 SetExpectations();
519 RunTest();
520}
521
522TEST_P(NativeLoaderTest_Create, NamespaceForSharedLibIsNotUsedAsAnonymousNamespace) {
523 if (IsBridged()) {
524 // There is no shared lib in translated arch
525 // TODO(jiyong): revisit this
526 return;
527 }
528 // compared to apks, for java shared libs, library_path is empty; java shared
529 // libs don't have their own native libs. They use platform's.
530 library_path = "";
531 expected_library_path = library_path;
532 // no ALSO_USED_AS_ANONYMOUS
533 expected_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
534 SetExpectations();
535 RunTest();
536}
537
538TEST_P(NativeLoaderTest_Create, TwoApks) {
539 SetExpectations();
540 const uint32_t second_app_target_sdk_version = 29;
541 const std::string second_app_class_loader = "second_app_classloader";
542 const bool second_app_is_shared = false;
543 const std::string second_app_dex_path = "/data/app/bar/classes.dex";
Martin Stjernholmbe08b202019-11-12 20:11:00 +0000544 const std::string second_app_library_path = "/data/app/bar/" LIB_DIR "/arm";
545 const std::string second_app_permitted_path = "/data/app/bar/" LIB_DIR;
Orion Hodson9b16e342019-10-09 13:29:16 +0100546 const std::string expected_second_app_permitted_path =
547 std::string("/data:/mnt/expand:") + second_app_permitted_path;
548 const std::string expected_second_app_parent_namespace = "classloader-namespace";
549 // no ALSO_USED_AS_ANONYMOUS
550 const uint64_t expected_second_namespace_flags = ANDROID_NAMESPACE_TYPE_ISOLATED;
551
552 // The scenario is that second app is loaded by the first app.
553 // So the first app's classloader (`classloader`) is parent of the second
554 // app's classloader.
555 ON_CALL(*mock, JniObject_getParent(StrEq(second_app_class_loader)))
556 .WillByDefault(Return(class_loader.c_str()));
557
558 // namespace for the second app is created. Its parent is set to the namespace
559 // of the first app.
560 EXPECT_CALL(*mock, mock_create_namespace(
561 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
562 StrEq(second_app_library_path), expected_second_namespace_flags,
563 StrEq(expected_second_app_permitted_path), NsEq(dex_path.c_str())))
564 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(second_app_dex_path.c_str()))));
565 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), NsEq(second_app_dex_path.c_str()), _, _))
566 .WillRepeatedly(Return(true));
567
568 RunTest();
569 jstring err = CreateClassLoaderNamespace(
570 env(), second_app_target_sdk_version, env()->NewStringUTF(second_app_class_loader.c_str()),
571 second_app_is_shared, env()->NewStringUTF(second_app_dex_path.c_str()),
572 env()->NewStringUTF(second_app_library_path.c_str()),
573 env()->NewStringUTF(second_app_permitted_path.c_str()));
574
575 // success
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +0100576 EXPECT_EQ(err, nullptr) << "Error is: " << std::string(ScopedUtfChars(env(), err).c_str());
Orion Hodson9b16e342019-10-09 13:29:16 +0100577
578 if (!IsBridged()) {
579 struct android_namespace_t* ns =
580 FindNamespaceByClassLoader(env(), env()->NewStringUTF(second_app_class_loader.c_str()));
581
582 // The created namespace is for the second apk
583 EXPECT_EQ(second_app_dex_path.c_str(), reinterpret_cast<const char*>(ns));
584 } else {
585 struct NativeLoaderNamespace* ns = FindNativeLoaderNamespaceByClassLoader(
586 env(), env()->NewStringUTF(second_app_class_loader.c_str()));
587
588 // The created namespace is for the second apk
589 EXPECT_STREQ(second_app_dex_path.c_str(),
590 reinterpret_cast<const char*>(ns->ToRawNativeBridgeNamespace()));
591 }
592}
593
594INSTANTIATE_TEST_SUITE_P(NativeLoaderTests_Create, NativeLoaderTest_Create, testing::Bool());
595
596const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
597 [](const struct ConfigEntry&) -> Result<bool> { return true; };
598
599TEST(NativeLoaderConfigParser, NamesAndComments) {
600 const char file_content[] = R"(
601######
602
603libA.so
604#libB.so
605
606
607 libC.so
608libD.so
609 #### libE.so
610)";
611 const std::vector<std::string> expected_result = {"libA.so", "libC.so", "libD.so"};
612 Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900613 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100614 ASSERT_EQ(expected_result, *result);
615}
616
617TEST(NativeLoaderConfigParser, WithBitness) {
618 const char file_content[] = R"(
619libA.so 32
620libB.so 64
621libC.so
622)";
623#if defined(__LP64__)
624 const std::vector<std::string> expected_result = {"libB.so", "libC.so"};
625#else
626 const std::vector<std::string> expected_result = {"libA.so", "libC.so"};
627#endif
628 Result<std::vector<std::string>> result = ParseConfig(file_content, always_true);
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900629 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100630 ASSERT_EQ(expected_result, *result);
631}
632
633TEST(NativeLoaderConfigParser, WithNoPreload) {
634 const char file_content[] = R"(
635libA.so nopreload
636libB.so nopreload
637libC.so
638)";
639
640 const std::vector<std::string> expected_result = {"libC.so"};
641 Result<std::vector<std::string>> result =
642 ParseConfig(file_content,
643 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
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, WithNoPreloadAndBitness) {
649 const char file_content[] = R"(
650libA.so nopreload 32
651libB.so 64 nopreload
652libC.so 32
653libD.so 64
654libE.so nopreload
655)";
656
657#if defined(__LP64__)
658 const std::vector<std::string> expected_result = {"libD.so"};
659#else
660 const std::vector<std::string> expected_result = {"libC.so"};
661#endif
662 Result<std::vector<std::string>> result =
663 ParseConfig(file_content,
664 [](const struct ConfigEntry& entry) -> Result<bool> { return !entry.nopreload; });
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900665 ASSERT_RESULT_OK(result);
Orion Hodson9b16e342019-10-09 13:29:16 +0100666 ASSERT_EQ(expected_result, *result);
667}
668
669TEST(NativeLoaderConfigParser, RejectMalformed) {
Bernie Innocentiac5ae3c2020-02-12 10:43:42 +0900670 ASSERT_FALSE(ParseConfig("libA.so 32 64", always_true).ok());
671 ASSERT_FALSE(ParseConfig("libA.so 32 32", always_true).ok());
672 ASSERT_FALSE(ParseConfig("libA.so 32 nopreload 64", always_true).ok());
673 ASSERT_FALSE(ParseConfig("32 libA.so nopreload", always_true).ok());
674 ASSERT_FALSE(ParseConfig("nopreload libA.so 32", always_true).ok());
675 ASSERT_FALSE(ParseConfig("libA.so nopreload # comment", always_true).ok());
Orion Hodson9b16e342019-10-09 13:29:16 +0100676}
677
Jooyung Han538f99a2020-03-03 00:46:50 +0900678TEST(NativeLoaderJniConfigParser, BasicLoading) {
679 const char file_content[] = R"(
680# comment
681com_android_foo libfoo.so
682# Empty line is ignored
683
684com_android_bar libbar.so:libbar2.so
685)";
686
687 std::map<std::string, std::string> expected_result{
688 {"com_android_foo", "libfoo.so"},
689 {"com_android_bar", "libbar.so:libbar2.so"},
690 };
691
692 Result<std::map<std::string, std::string>> result = ParseJniConfig(file_content);
693 ASSERT_RESULT_OK(result);
694 ASSERT_EQ(expected_result, *result);
695}
696
697TEST(NativeLoaderJniConfigParser, RejectMalformed) {
698 ASSERT_FALSE(ParseJniConfig("com_android_foo").ok());
699}
700
Orion Hodson9b16e342019-10-09 13:29:16 +0100701} // namespace nativeloader
702} // namespace android