1 /*
2 * Copyright (C) 2014 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 "nativebridge/native_bridge.h"
18
19 #include <cstring>
20 #include <cutils/log.h>
21 #include <dlfcn.h>
22 #include <errno.h>
23 #include <fcntl.h>
24 #include <stdio.h>
25 #include <sys/mount.h>
26 #include <sys/stat.h>
27
28
29 namespace android {
30
31 // Environment values required by the apps running with native bridge.
32 struct NativeBridgeRuntimeValues {
33 const char* os_arch;
34 const char* cpu_abi;
35 const char* cpu_abi2;
36 const char* *supported_abis;
37 int32_t abi_count;
38 };
39
40 // The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
41 static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
42
43 enum class NativeBridgeState {
44 kNotSetup, // Initial state.
45 kOpened, // After successful dlopen.
46 kPreInitialized, // After successful pre-initialization.
47 kInitialized, // After successful initialization.
48 kClosed // Closed or errors.
49 };
50
51 static constexpr const char* kNotSetupString = "kNotSetup";
52 static constexpr const char* kOpenedString = "kOpened";
53 static constexpr const char* kPreInitializedString = "kPreInitialized";
54 static constexpr const char* kInitializedString = "kInitialized";
55 static constexpr const char* kClosedString = "kClosed";
56
GetNativeBridgeStateString(NativeBridgeState state)57 static const char* GetNativeBridgeStateString(NativeBridgeState state) {
58 switch (state) {
59 case NativeBridgeState::kNotSetup:
60 return kNotSetupString;
61
62 case NativeBridgeState::kOpened:
63 return kOpenedString;
64
65 case NativeBridgeState::kPreInitialized:
66 return kPreInitializedString;
67
68 case NativeBridgeState::kInitialized:
69 return kInitializedString;
70
71 case NativeBridgeState::kClosed:
72 return kClosedString;
73 }
74 }
75
76 // Current state of the native bridge.
77 static NativeBridgeState state = NativeBridgeState::kNotSetup;
78
79 // Whether we had an error at some point.
80 static bool had_error = false;
81
82 // Handle of the loaded library.
83 static void* native_bridge_handle = nullptr;
84 // Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
85 // later.
86 static const NativeBridgeCallbacks* callbacks = nullptr;
87 // Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
88 static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
89
90 // The app's code cache directory.
91 static char* app_code_cache_dir = nullptr;
92
93 // Code cache directory (relative to the application private directory)
94 // Ideally we'd like to call into framework to retrieve this name. However that's considered an
95 // implementation detail and will require either hacks or consistent refactorings. We compromise
96 // and hard code the directory name again here.
97 static constexpr const char* kCodeCacheDir = "code_cache";
98
99 static constexpr uint32_t kLibNativeBridgeVersion = 2;
100
101 // Characters allowed in a native bridge filename. The first character must
102 // be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
CharacterAllowed(char c,bool first)103 static bool CharacterAllowed(char c, bool first) {
104 if (first) {
105 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
106 } else {
107 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
108 (c == '.') || (c == '_') || (c == '-');
109 }
110 }
111
112 // We only allow simple names for the library. It is supposed to be a file in
113 // /system/lib or /vendor/lib. Only allow a small range of characters, that is
114 // names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
NativeBridgeNameAcceptable(const char * nb_library_filename)115 bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
116 const char* ptr = nb_library_filename;
117 if (*ptr == 0) {
118 // Emptry string. Allowed, means no native bridge.
119 return true;
120 } else {
121 // First character must be [a-zA-Z].
122 if (!CharacterAllowed(*ptr, true)) {
123 // Found an invalid fist character, don't accept.
124 ALOGE("Native bridge library %s has been rejected for first character %c",
125 nb_library_filename,
126 *ptr);
127 return false;
128 } else {
129 // For the rest, be more liberal.
130 ptr++;
131 while (*ptr != 0) {
132 if (!CharacterAllowed(*ptr, false)) {
133 // Found an invalid character, don't accept.
134 ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
135 return false;
136 }
137 ptr++;
138 }
139 }
140 return true;
141 }
142 }
143
VersionCheck(const NativeBridgeCallbacks * cb)144 static bool VersionCheck(const NativeBridgeCallbacks* cb) {
145 // Libnativebridge is now designed to be forward-compatible. So only "0" is an unsupported
146 // version.
147 if (cb == nullptr || cb->version == 0) {
148 return false;
149 }
150
151 // If this is a v2+ bridge, it may not be forwards- or backwards-compatible. Check.
152 if (cb->version >= 2) {
153 if (!callbacks->isCompatibleWith(kLibNativeBridgeVersion)) {
154 // TODO: Scan which version is supported, and fall back to handle it.
155 return false;
156 }
157 }
158
159 return true;
160 }
161
CloseNativeBridge(bool with_error)162 static void CloseNativeBridge(bool with_error) {
163 state = NativeBridgeState::kClosed;
164 had_error |= with_error;
165 delete[] app_code_cache_dir;
166 app_code_cache_dir = nullptr;
167 }
168
LoadNativeBridge(const char * nb_library_filename,const NativeBridgeRuntimeCallbacks * runtime_cbs)169 bool LoadNativeBridge(const char* nb_library_filename,
170 const NativeBridgeRuntimeCallbacks* runtime_cbs) {
171 // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
172 // multi-threaded, so we do not need locking here.
173
174 if (state != NativeBridgeState::kNotSetup) {
175 // Setup has been called before. Ignore this call.
176 if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
177 ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
178 GetNativeBridgeStateString(state));
179 }
180 // Note: counts as an error, even though the bridge may be functional.
181 had_error = true;
182 return false;
183 }
184
185 if (nb_library_filename == nullptr || *nb_library_filename == 0) {
186 CloseNativeBridge(false);
187 return false;
188 } else {
189 if (!NativeBridgeNameAcceptable(nb_library_filename)) {
190 CloseNativeBridge(true);
191 } else {
192 // Try to open the library.
193 void* handle = dlopen(nb_library_filename, RTLD_LAZY);
194 if (handle != nullptr) {
195 callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
196 kNativeBridgeInterfaceSymbol));
197 if (callbacks != nullptr) {
198 if (VersionCheck(callbacks)) {
199 // Store the handle for later.
200 native_bridge_handle = handle;
201 } else {
202 callbacks = nullptr;
203 dlclose(handle);
204 ALOGW("Unsupported native bridge interface.");
205 }
206 } else {
207 dlclose(handle);
208 }
209 }
210
211 // Two failure conditions: could not find library (dlopen failed), or could not find native
212 // bridge interface (dlsym failed). Both are an error and close the native bridge.
213 if (callbacks == nullptr) {
214 CloseNativeBridge(true);
215 } else {
216 runtime_callbacks = runtime_cbs;
217 state = NativeBridgeState::kOpened;
218 }
219 }
220 return state == NativeBridgeState::kOpened;
221 }
222 }
223
224 #if defined(__arm__)
225 static const char* kRuntimeISA = "arm";
226 #elif defined(__aarch64__)
227 static const char* kRuntimeISA = "arm64";
228 #elif defined(__mips__)
229 static const char* kRuntimeISA = "mips";
230 #elif defined(__i386__)
231 static const char* kRuntimeISA = "x86";
232 #elif defined(__x86_64__)
233 static const char* kRuntimeISA = "x86_64";
234 #else
235 static const char* kRuntimeISA = "unknown";
236 #endif
237
238
NeedsNativeBridge(const char * instruction_set)239 bool NeedsNativeBridge(const char* instruction_set) {
240 if (instruction_set == nullptr) {
241 ALOGE("Null instruction set in NeedsNativeBridge.");
242 return false;
243 }
244 return strncmp(instruction_set, kRuntimeISA, strlen(kRuntimeISA) + 1) != 0;
245 }
246
247 #ifdef __APPLE__
UNUSED(const T &)248 template<typename T> void UNUSED(const T&) {}
249 #endif
250
PreInitializeNativeBridge(const char * app_data_dir_in,const char * instruction_set)251 bool PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
252 if (state != NativeBridgeState::kOpened) {
253 ALOGE("Invalid state: native bridge is expected to be opened.");
254 CloseNativeBridge(true);
255 return false;
256 }
257
258 if (app_data_dir_in == nullptr) {
259 ALOGE("Application private directory cannot be null.");
260 CloseNativeBridge(true);
261 return false;
262 }
263
264 // Create the path to the application code cache directory.
265 // The memory will be release after Initialization or when the native bridge is closed.
266 const size_t len = strlen(app_data_dir_in) + strlen(kCodeCacheDir) + 2; // '\0' + '/'
267 app_code_cache_dir = new char[len];
268 snprintf(app_code_cache_dir, len, "%s/%s", app_data_dir_in, kCodeCacheDir);
269
270 // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo.
271 // Failure is not fatal and will keep the native bridge in kPreInitialized.
272 state = NativeBridgeState::kPreInitialized;
273
274 #ifndef __APPLE__
275 if (instruction_set == nullptr) {
276 return true;
277 }
278 size_t isa_len = strlen(instruction_set);
279 if (isa_len > 10) {
280 // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
281 // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
282 // be another instruction set in the future.
283 ALOGW("Instruction set %s is malformed, must be less than or equal to 10 characters.",
284 instruction_set);
285 return true;
286 }
287
288 // If the file does not exist, the mount command will fail,
289 // so we save the extra file existence check.
290 char cpuinfo_path[1024];
291
292 #ifdef HAVE_ANDROID_OS
293 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "/system/lib"
294 #ifdef __LP64__
295 "64"
296 #endif // __LP64__
297 "/%s/cpuinfo", instruction_set);
298 #else // !HAVE_ANDROID_OS
299 // To be able to test on the host, we hardwire a relative path.
300 snprintf(cpuinfo_path, sizeof(cpuinfo_path), "./cpuinfo");
301 #endif
302
303 // Bind-mount.
304 if (TEMP_FAILURE_RETRY(mount(cpuinfo_path, // Source.
305 "/proc/cpuinfo", // Target.
306 nullptr, // FS type.
307 MS_BIND, // Mount flags: bind mount.
308 nullptr)) == -1) { // "Data."
309 ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %s", cpuinfo_path, strerror(errno));
310 }
311 #else // __APPLE__
312 UNUSED(instruction_set);
313 ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
314 #endif
315
316 return true;
317 }
318
SetCpuAbi(JNIEnv * env,jclass build_class,const char * field,const char * value)319 static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
320 if (value != nullptr) {
321 jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
322 if (field_id == nullptr) {
323 env->ExceptionClear();
324 ALOGW("Could not find %s field.", field);
325 return;
326 }
327
328 jstring str = env->NewStringUTF(value);
329 if (str == nullptr) {
330 env->ExceptionClear();
331 ALOGW("Could not create string %s.", value);
332 return;
333 }
334
335 env->SetStaticObjectField(build_class, field_id, str);
336 }
337 }
338
339 // Set up the environment for the bridged app.
SetupEnvironment(const NativeBridgeCallbacks * callbacks,JNIEnv * env,const char * isa)340 static void SetupEnvironment(const NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
341 // Need a JNIEnv* to do anything.
342 if (env == nullptr) {
343 ALOGW("No JNIEnv* to set up app environment.");
344 return;
345 }
346
347 // Query the bridge for environment values.
348 const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
349 if (env_values == nullptr) {
350 return;
351 }
352
353 // Keep the JNIEnv clean.
354 jint success = env->PushLocalFrame(16); // That should be small and large enough.
355 if (success < 0) {
356 // Out of memory, really borked.
357 ALOGW("Out of memory while setting up app environment.");
358 env->ExceptionClear();
359 return;
360 }
361
362 // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
363 if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
364 env_values->abi_count >= 0) {
365 jclass bclass_id = env->FindClass("android/os/Build");
366 if (bclass_id != nullptr) {
367 SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
368 SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
369 } else {
370 // For example in a host test environment.
371 env->ExceptionClear();
372 ALOGW("Could not find Build class.");
373 }
374 }
375
376 if (env_values->os_arch != nullptr) {
377 jclass sclass_id = env->FindClass("java/lang/System");
378 if (sclass_id != nullptr) {
379 jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setUnchangeableSystemProperty",
380 "(Ljava/lang/String;Ljava/lang/String;)V");
381 if (set_prop_id != nullptr) {
382 // Init os.arch to the value reqired by the apps running with native bridge.
383 env->CallStaticVoidMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
384 env->NewStringUTF(env_values->os_arch));
385 } else {
386 env->ExceptionClear();
387 ALOGW("Could not find System#setUnchangeableSystemProperty.");
388 }
389 } else {
390 env->ExceptionClear();
391 ALOGW("Could not find System class.");
392 }
393 }
394
395 // Make it pristine again.
396 env->PopLocalFrame(nullptr);
397 }
398
InitializeNativeBridge(JNIEnv * env,const char * instruction_set)399 bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
400 // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
401 // point we are not multi-threaded, so we do not need locking here.
402
403 if (state == NativeBridgeState::kPreInitialized) {
404 // Check for code cache: if it doesn't exist try to create it.
405 struct stat st;
406 if (stat(app_code_cache_dir, &st) == -1) {
407 if (errno == ENOENT) {
408 if (mkdir(app_code_cache_dir, S_IRWXU | S_IRWXG | S_IXOTH) == -1) {
409 ALOGE("Cannot create code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
410 CloseNativeBridge(true);
411 }
412 } else {
413 ALOGE("Cannot stat code cache directory %s: %s.", app_code_cache_dir, strerror(errno));
414 CloseNativeBridge(true);
415 }
416 } else if (!S_ISDIR(st.st_mode)) {
417 ALOGE("Code cache is not a directory %s.", app_code_cache_dir);
418 CloseNativeBridge(true);
419 }
420
421 // If we're still PreInitialized (dind't fail the code cache checks) try to initialize.
422 if (state == NativeBridgeState::kPreInitialized) {
423 if (callbacks->initialize(runtime_callbacks, app_code_cache_dir, instruction_set)) {
424 SetupEnvironment(callbacks, env, instruction_set);
425 state = NativeBridgeState::kInitialized;
426 // We no longer need the code cache path, release the memory.
427 delete[] app_code_cache_dir;
428 app_code_cache_dir = nullptr;
429 } else {
430 // Unload the library.
431 dlclose(native_bridge_handle);
432 CloseNativeBridge(true);
433 }
434 }
435 } else {
436 CloseNativeBridge(true);
437 }
438
439 return state == NativeBridgeState::kInitialized;
440 }
441
UnloadNativeBridge()442 void UnloadNativeBridge() {
443 // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
444 // point we are not multi-threaded, so we do not need locking here.
445
446 switch(state) {
447 case NativeBridgeState::kOpened:
448 case NativeBridgeState::kPreInitialized:
449 case NativeBridgeState::kInitialized:
450 // Unload.
451 dlclose(native_bridge_handle);
452 CloseNativeBridge(false);
453 break;
454
455 case NativeBridgeState::kNotSetup:
456 // Not even set up. Error.
457 CloseNativeBridge(true);
458 break;
459
460 case NativeBridgeState::kClosed:
461 // Ignore.
462 break;
463 }
464 }
465
NativeBridgeError()466 bool NativeBridgeError() {
467 return had_error;
468 }
469
NativeBridgeAvailable()470 bool NativeBridgeAvailable() {
471 return state == NativeBridgeState::kOpened
472 || state == NativeBridgeState::kPreInitialized
473 || state == NativeBridgeState::kInitialized;
474 }
475
NativeBridgeInitialized()476 bool NativeBridgeInitialized() {
477 // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
478 // Runtime::DidForkFromZygote. In that case we do not need a lock.
479 return state == NativeBridgeState::kInitialized;
480 }
481
NativeBridgeLoadLibrary(const char * libpath,int flag)482 void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
483 if (NativeBridgeInitialized()) {
484 return callbacks->loadLibrary(libpath, flag);
485 }
486 return nullptr;
487 }
488
NativeBridgeGetTrampoline(void * handle,const char * name,const char * shorty,uint32_t len)489 void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
490 uint32_t len) {
491 if (NativeBridgeInitialized()) {
492 return callbacks->getTrampoline(handle, name, shorty, len);
493 }
494 return nullptr;
495 }
496
NativeBridgeIsSupported(const char * libpath)497 bool NativeBridgeIsSupported(const char* libpath) {
498 if (NativeBridgeInitialized()) {
499 return callbacks->isSupported(libpath);
500 }
501 return false;
502 }
503
NativeBridgeGetVersion()504 uint32_t NativeBridgeGetVersion() {
505 if (NativeBridgeAvailable()) {
506 return callbacks->version;
507 }
508 return 0;
509 }
510
NativeBridgeGetSignalHandler(int signal)511 NativeBridgeSignalHandlerFn NativeBridgeGetSignalHandler(int signal) {
512 if (NativeBridgeInitialized() && callbacks->version >= 2) {
513 return callbacks->getSignalHandler(signal);
514 }
515 return nullptr;
516 }
517
518 }; // namespace android
519