blob: f0446f0db160d604aecf470260c9e44c72bb737e [file] [log] [blame]
Orion Hodson9b16e342019-10-09 13:29:16 +01001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <dlfcn.h>
18#include <memory>
19#include <unordered_map>
20
21#include <android-base/strings.h>
22#include <gmock/gmock.h>
23#include <gtest/gtest.h>
24#include <jni.h>
25
26#include "native_loader_namespace.h"
Martin Stjernholm94fd9ea2019-10-24 16:57:34 +010027#include "nativehelper/scoped_utf_chars.h"
Orion Hodson9b16e342019-10-09 13:29:16 +010028#include "nativeloader/dlext_namespaces.h"
29#include "nativeloader/native_loader.h"
30#include "public_libraries.h"
31
Orion Hodson9b16e342019-10-09 13:29:16 +010032namespace android {
33namespace nativeloader {
34
Martin Stjernholm48297332019-11-12 21:21:32 +000035using ::testing::Eq;
36using ::testing::Return;
37using ::testing::StrEq;
38using ::testing::_;
39using internal::ConfigEntry;
40using internal::ParseConfig;
41
Martin Stjernholmbe08b202019-11-12 20:11:00 +000042#if defined(__LP64__)
43#define LIB_DIR "lib64"
44#else
45#define LIB_DIR "lib"
46#endif
47
Orion Hodson9b16e342019-10-09 13:29:16 +010048// gmock interface that represents interested platform APIs on libdl and libnativebridge
49class Platform {
50 public:
51 virtual ~Platform() {}
52
53 // libdl APIs
54 virtual void* dlopen(const char* filename, int flags) = 0;
55 virtual int dlclose(void* handle) = 0;
56 virtual char* dlerror(void) = 0;
57
58 // These mock_* are the APIs semantically the same across libdl and libnativebridge.
59 // Instead of having two set of mock APIs for the two, define only one set with an additional
60 // argument 'bool bridged' to identify the context (i.e., called for libdl or libnativebridge).
61 typedef char* mock_namespace_handle;
62 virtual bool mock_init_anonymous_namespace(bool bridged, const char* sonames,
63 const char* search_paths) = 0;
64 virtual mock_namespace_handle mock_create_namespace(
65 bool bridged, const char* name, const char* ld_library_path, const char* default_library_path,
66 uint64_t type, const char* permitted_when_isolated_path, mock_namespace_handle parent) = 0;
67 virtual bool mock_link_namespaces(bool bridged, mock_namespace_handle from,
68 mock_namespace_handle to, const char* sonames) = 0;
69 virtual mock_namespace_handle mock_get_exported_namespace(bool bridged, const char* name) = 0;
70 virtual void* mock_dlopen_ext(bool bridged, const char* filename, int flags,
71 mock_namespace_handle ns) = 0;
72
73 // libnativebridge APIs for which libdl has no corresponding APIs
74 virtual bool NativeBridgeInitialized() = 0;
75 virtual const char* NativeBridgeGetError() = 0;
76 virtual bool NativeBridgeIsPathSupported(const char*) = 0;
77 virtual bool NativeBridgeIsSupported(const char*) = 0;
78
79 // To mock "ClassLoader Object.getParent()"
80 virtual const char* JniObject_getParent(const char*) = 0;
81};
82
83// The mock does not actually create a namespace object. But simply casts the pointer to the
84// string for the namespace name as the handle to the namespace object.
85#define TO_ANDROID_NAMESPACE(str) \
86 reinterpret_cast<struct android_namespace_t*>(const_cast<char*>(str))
87
88#define TO_BRIDGED_NAMESPACE(str) \
89 reinterpret_cast<struct native_bridge_namespace_t*>(const_cast<char*>(str))
90
91#define TO_MOCK_NAMESPACE(ns) reinterpret_cast<Platform::mock_namespace_handle>(ns)
92
93// These represents built-in namespaces created by the linker according to ld.config.txt
94static std::unordered_map<std::string, Platform::mock_namespace_handle> namespaces = {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +090095 {"system", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("system"))},
Orion Hodson9b16e342019-10-09 13:29:16 +010096 {"default", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("default"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +090097 {"com_android_art", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_art"))},
Orion Hodson9b16e342019-10-09 13:29:16 +010098 {"sphal", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("sphal"))},
99 {"vndk", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk"))},
Justin Yuneb4f08c2020-02-18 11:29:07 +0900100 {"vndk_product", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("vndk_product"))},
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900101 {"com_android_neuralnetworks", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_neuralnetworks"))},
102 {"com_android_cronet", TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE("com_android_cronet"))},
103 {"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;
Luke Huang5c017722019-12-17 10:54:26 +0800361 bool expected_link_with_cronet_ns = true;
Jeffrey Huang52575032020-02-11 17:33:45 -0800362 bool expected_link_with_statsd_ns = true;
Orion Hodson9b16e342019-10-09 13:29:16 +0100363 std::string expected_shared_libs_to_platform_ns = default_public_libraries();
364 std::string expected_shared_libs_to_art_ns = art_public_libraries();
365 std::string expected_shared_libs_to_sphal_ns = vendor_public_libraries();
Justin Yuneb4f08c2020-02-18 11:29:07 +0900366 std::string expected_shared_libs_to_vndk_ns = vndksp_libraries_vendor();
367 std::string expected_shared_libs_to_vndk_product_ns = vndksp_libraries_product();
Orion Hodson9b16e342019-10-09 13:29:16 +0100368 std::string expected_shared_libs_to_default_ns = default_public_libraries();
369 std::string expected_shared_libs_to_neuralnetworks_ns = neuralnetworks_public_libraries();
Luke Huang5c017722019-12-17 10:54:26 +0800370 std::string expected_shared_libs_to_cronet_ns = cronet_public_libraries();
Jeffrey Huang52575032020-02-11 17:33:45 -0800371 std::string expected_shared_libs_to_statsd_ns = statsd_public_libraries();
Orion Hodson9b16e342019-10-09 13:29:16 +0100372
373 void SetExpectations() {
374 NativeLoaderTest::SetExpectations();
375
376 ON_CALL(*mock, JniObject_getParent(StrEq(class_loader))).WillByDefault(Return(nullptr));
377
Martin Stjernholm48297332019-11-12 21:21:32 +0000378 EXPECT_CALL(*mock, NativeBridgeIsPathSupported(_)).Times(testing::AnyNumber());
379 EXPECT_CALL(*mock, NativeBridgeInitialized()).Times(testing::AnyNumber());
Orion Hodson9b16e342019-10-09 13:29:16 +0100380
381 EXPECT_CALL(*mock, mock_create_namespace(
382 Eq(IsBridged()), StrEq(expected_namespace_name), nullptr,
383 StrEq(expected_library_path), expected_namespace_flags,
384 StrEq(expected_permitted_path), NsEq(expected_parent_namespace.c_str())))
385 .WillOnce(Return(TO_MOCK_NAMESPACE(TO_ANDROID_NAMESPACE(dex_path.c_str()))));
386 if (expected_link_with_platform_ns) {
Kiyoung Kim99c19ca2020-01-29 16:09:38 +0900387 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("system"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100388 StrEq(expected_shared_libs_to_platform_ns)))
389 .WillOnce(Return(true));
390 }
391 if (expected_link_with_art_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900392 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_art"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100393 StrEq(expected_shared_libs_to_art_ns)))
394 .WillOnce(Return(true));
395 }
396 if (expected_link_with_sphal_ns) {
397 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("sphal"),
398 StrEq(expected_shared_libs_to_sphal_ns)))
399 .WillOnce(Return(true));
400 }
401 if (expected_link_with_vndk_ns) {
402 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk"),
403 StrEq(expected_shared_libs_to_vndk_ns)))
404 .WillOnce(Return(true));
405 }
Justin Yuneb4f08c2020-02-18 11:29:07 +0900406 if (expected_link_with_vndk_product_ns) {
407 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("vndk_product"),
408 StrEq(expected_shared_libs_to_vndk_product_ns)))
409 .WillOnce(Return(true));
410 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100411 if (expected_link_with_default_ns) {
412 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("default"),
413 StrEq(expected_shared_libs_to_default_ns)))
414 .WillOnce(Return(true));
415 }
416 if (expected_link_with_neuralnetworks_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900417 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_neuralnetworks"),
Orion Hodson9b16e342019-10-09 13:29:16 +0100418 StrEq(expected_shared_libs_to_neuralnetworks_ns)))
419 .WillOnce(Return(true));
420 }
Luke Huang5c017722019-12-17 10:54:26 +0800421 if (expected_link_with_cronet_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900422 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_cronet"),
Luke Huang5c017722019-12-17 10:54:26 +0800423 StrEq(expected_shared_libs_to_cronet_ns)))
424 .WillOnce(Return(true));
425 }
Jeffrey Huang52575032020-02-11 17:33:45 -0800426 if (expected_link_with_statsd_ns) {
Kiyoung Kim272b36d2020-02-19 16:08:47 +0900427 EXPECT_CALL(*mock, mock_link_namespaces(Eq(IsBridged()), _, NsEq("com_android_os_statsd"),
Jeffrey Huang52575032020-02-11 17:33:45 -0800428 StrEq(expected_shared_libs_to_statsd_ns)))
429 .WillOnce(Return(true));
430 }
Orion Hodson9b16e342019-10-09 13:29:16 +0100431 }
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()),
439 env()->NewStringUTF(permitted_path.c_str()));
440
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()),
580 env()->NewStringUTF(second_app_permitted_path.c_str()));
581
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
685} // namespace nativeloader
686} // namespace android