blob: 11f330c89632cede73680404d349c162ba793db7 [file] [log] [blame]
Calin Juravle961ae122014-08-11 16:11:59 +01001/*
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
jgu21ab0da5a2014-09-10 06:58:32 -040019#include <cstring>
Andreas Gampe049249c2014-08-19 22:31:31 -070020#include <cutils/log.h>
Calin Juravle961ae122014-08-11 16:11:59 +010021#include <dlfcn.h>
jgu21ab0da5a2014-09-10 06:58:32 -040022#include <errno.h>
23#include <fcntl.h>
Calin Juravle961ae122014-08-11 16:11:59 +010024#include <stdio.h>
jgu21ab0da5a2014-09-10 06:58:32 -040025#include <sys/mount.h>
26#include <sys/stat.h>
Calin Juravle961ae122014-08-11 16:11:59 +010027
28
29namespace android {
30
jgu21ab0da5a2014-09-10 06:58:32 -040031// Environment values required by the apps running with native bridge.
32struct 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
Calin Juravle961ae122014-08-11 16:11:59 +010040// The symbol name exposed by native-bridge with the type of NativeBridgeCallbacks.
41static constexpr const char* kNativeBridgeInterfaceSymbol = "NativeBridgeItf";
42
Andreas Gampe035bd752014-09-02 21:17:03 -070043enum class NativeBridgeState {
44 kNotSetup, // Initial state.
45 kOpened, // After successful dlopen.
46 kInitialized, // After successful initialization.
47 kClosed // Closed or errors.
48};
Calin Juravle961ae122014-08-11 16:11:59 +010049
Andreas Gampe035bd752014-09-02 21:17:03 -070050static const char* kNotSetupString = "kNotSetup";
51static const char* kOpenedString = "kOpened";
52static const char* kInitializedString = "kInitialized";
53static const char* kClosedString = "kClosed";
54
55static const char* GetNativeBridgeStateString(NativeBridgeState state) {
56 switch (state) {
57 case NativeBridgeState::kNotSetup:
58 return kNotSetupString;
59
60 case NativeBridgeState::kOpened:
61 return kOpenedString;
62
63 case NativeBridgeState::kInitialized:
64 return kInitializedString;
65
66 case NativeBridgeState::kClosed:
67 return kClosedString;
68 }
69}
70
71// Current state of the native bridge.
72static NativeBridgeState state = NativeBridgeState::kNotSetup;
73
Andreas Gampe049249c2014-08-19 22:31:31 -070074// Whether we had an error at some point.
75static bool had_error = false;
Calin Juravle961ae122014-08-11 16:11:59 +010076
Andreas Gampe035bd752014-09-02 21:17:03 -070077// Handle of the loaded library.
78static void* native_bridge_handle = nullptr;
79// Pointer to the callbacks. Available as soon as LoadNativeBridge succeeds, but only initialized
80// later.
Calin Juravle961ae122014-08-11 16:11:59 +010081static NativeBridgeCallbacks* callbacks = nullptr;
Andreas Gampe035bd752014-09-02 21:17:03 -070082// Callbacks provided by the environment to the bridge. Passed to LoadNativeBridge.
Calin Juravle961ae122014-08-11 16:11:59 +010083static const NativeBridgeRuntimeCallbacks* runtime_callbacks = nullptr;
84
jgu21ab0da5a2014-09-10 06:58:32 -040085// The app's data directory.
86static char* app_data_dir = nullptr;
87
88static constexpr uint32_t kNativeBridgeCallbackVersion = 1;
89
Andreas Gampe049249c2014-08-19 22:31:31 -070090// Characters allowed in a native bridge filename. The first character must
91// be in [a-zA-Z] (expected 'l' for "libx"). The rest must be in [a-zA-Z0-9._-].
92static bool CharacterAllowed(char c, bool first) {
93 if (first) {
94 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
95 } else {
96 return ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z') || ('0' <= c && c <= '9') ||
97 (c == '.') || (c == '_') || (c == '-');
98 }
99}
100
101// We only allow simple names for the library. It is supposed to be a file in
102// /system/lib or /vendor/lib. Only allow a small range of characters, that is
103// names consisting of [a-zA-Z0-9._-] and starting with [a-zA-Z].
104bool NativeBridgeNameAcceptable(const char* nb_library_filename) {
105 const char* ptr = nb_library_filename;
106 if (*ptr == 0) {
107 // Emptry string. Allowed, means no native bridge.
108 return true;
109 } else {
110 // First character must be [a-zA-Z].
111 if (!CharacterAllowed(*ptr, true)) {
112 // Found an invalid fist character, don't accept.
113 ALOGE("Native bridge library %s has been rejected for first character %c", nb_library_filename, *ptr);
114 return false;
115 } else {
116 // For the rest, be more liberal.
117 ptr++;
118 while (*ptr != 0) {
119 if (!CharacterAllowed(*ptr, false)) {
120 // Found an invalid character, don't accept.
121 ALOGE("Native bridge library %s has been rejected for %c", nb_library_filename, *ptr);
122 return false;
123 }
124 ptr++;
125 }
126 }
127 return true;
128 }
129}
130
jgu21ab0da5a2014-09-10 06:58:32 -0400131static bool VersionCheck(NativeBridgeCallbacks* cb) {
132 return cb != nullptr && cb->version == kNativeBridgeCallbackVersion;
133}
134
Andreas Gampe035bd752014-09-02 21:17:03 -0700135bool LoadNativeBridge(const char* nb_library_filename,
136 const NativeBridgeRuntimeCallbacks* runtime_cbs) {
137 // We expect only one place that calls LoadNativeBridge: Runtime::Init. At that point we are not
138 // multi-threaded, so we do not need locking here.
Calin Juravle961ae122014-08-11 16:11:59 +0100139
Andreas Gampe035bd752014-09-02 21:17:03 -0700140 if (state != NativeBridgeState::kNotSetup) {
Andreas Gampe049249c2014-08-19 22:31:31 -0700141 // Setup has been called before. Ignore this call.
jgu21ab0da5a2014-09-10 06:58:32 -0400142 if (nb_library_filename != nullptr) { // Avoids some log-spam for dalvikvm.
143 ALOGW("Called LoadNativeBridge for an already set up native bridge. State is %s.",
144 GetNativeBridgeStateString(state));
145 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700146 // Note: counts as an error, even though the bridge may be functional.
147 had_error = true;
Andreas Gampe049249c2014-08-19 22:31:31 -0700148 return false;
149 }
150
Andreas Gampe035bd752014-09-02 21:17:03 -0700151 if (nb_library_filename == nullptr || *nb_library_filename == 0) {
152 state = NativeBridgeState::kClosed;
153 return true;
154 } else {
155 if (!NativeBridgeNameAcceptable(nb_library_filename)) {
156 state = NativeBridgeState::kClosed;
Andreas Gampe049249c2014-08-19 22:31:31 -0700157 had_error = true;
Andreas Gampe035bd752014-09-02 21:17:03 -0700158 } else {
159 // Try to open the library.
160 void* handle = dlopen(nb_library_filename, RTLD_LAZY);
161 if (handle != nullptr) {
162 callbacks = reinterpret_cast<NativeBridgeCallbacks*>(dlsym(handle,
163 kNativeBridgeInterfaceSymbol));
164 if (callbacks != nullptr) {
jgu21ab0da5a2014-09-10 06:58:32 -0400165 if (VersionCheck(callbacks)) {
166 // Store the handle for later.
167 native_bridge_handle = handle;
168 } else {
169 callbacks = nullptr;
170 dlclose(handle);
171 ALOGW("Unsupported native bridge interface.");
172 }
Andreas Gampe035bd752014-09-02 21:17:03 -0700173 } else {
174 dlclose(handle);
175 }
176 }
177
178 // Two failure conditions: could not find library (dlopen failed), or could not find native
179 // bridge interface (dlsym failed). Both are an error and close the native bridge.
180 if (callbacks == nullptr) {
181 had_error = true;
182 state = NativeBridgeState::kClosed;
183 } else {
184 runtime_callbacks = runtime_cbs;
185 state = NativeBridgeState::kOpened;
186 }
187 }
188 return state == NativeBridgeState::kOpened;
189 }
190}
191
jgu21ab0da5a2014-09-10 06:58:32 -0400192#if defined(__arm__)
193static const char* kRuntimeISA = "arm";
194#elif defined(__aarch64__)
195static const char* kRuntimeISA = "arm64";
196#elif defined(__mips__)
197static const char* kRuntimeISA = "mips";
198#elif defined(__i386__)
199static const char* kRuntimeISA = "x86";
200#elif defined(__x86_64__)
201static const char* kRuntimeISA = "x86_64";
202#else
203static const char* kRuntimeISA = "unknown";
204#endif
205
206
207bool NeedsNativeBridge(const char* instruction_set) {
208 return strncmp(instruction_set, kRuntimeISA, strlen(kRuntimeISA)) != 0;
209}
210
211void PreInitializeNativeBridge(const char* app_data_dir_in, const char* instruction_set) {
212 if (app_data_dir_in == nullptr) {
213 return;
214 }
215
216 const size_t len = strlen(app_data_dir_in);
217 // Make a copy for us.
218 app_data_dir = new char[len];
219 strncpy(app_data_dir, app_data_dir_in, len);
220
Andreas Gampe962eb402014-09-24 16:36:17 -0700221#ifndef __APPLE__
jgu21ab0da5a2014-09-10 06:58:32 -0400222 if (instruction_set == nullptr) {
223 return;
224 }
225 size_t isa_len = strlen(instruction_set);
226 if (isa_len > 10) {
227 // 10 is a loose upper bound on the currently known instruction sets (a tight bound is 7 for
228 // x86_64 [including the trailing \0]). This is so we don't have to change here if there will
229 // be another instruction set in the future.
230 ALOGW("Instruction set %s is malformed, must be less than 10 characters.", instruction_set);
231 return;
232 }
233
234 // Bind-mount /system/lib{,64}/<isa>/cpuinfo to /proc/cpuinfo. If the file does not exist, the
235 // mount command will fail, so we safe the extra file existence check...
236 char cpuinfo_path[1024];
237
238 snprintf(cpuinfo_path, 1024, "/system/lib"
239#ifdef __LP64__
240 "64"
241#endif
242 "/%s/cpuinfo", instruction_set);
243
244 // Bind-mount.
245 if (TEMP_FAILURE_RETRY(mount("/proc/cpuinfo", cpuinfo_path, nullptr, MS_BIND, nullptr)) == -1) {
246 ALOGW("Failed to bind-mount %s as /proc/cpuinfo: %d", cpuinfo_path, errno);
247 }
Andreas Gampe962eb402014-09-24 16:36:17 -0700248#else
249 ALOGW("Mac OS does not support bind-mounting. Host simulation of native bridge impossible.");
250#endif
jgu21ab0da5a2014-09-10 06:58:32 -0400251}
252
253static void SetCpuAbi(JNIEnv* env, jclass build_class, const char* field, const char* value) {
254 if (value != nullptr) {
255 jfieldID field_id = env->GetStaticFieldID(build_class, field, "Ljava/lang/String;");
256 if (field_id == nullptr) {
257 env->ExceptionClear();
258 ALOGW("Could not find %s field.", field);
259 return;
260 }
261
262 jstring str = env->NewStringUTF(value);
263 if (str == nullptr) {
264 env->ExceptionClear();
265 ALOGW("Could not create string %s.", value);
266 return;
267 }
268
269 env->SetStaticObjectField(build_class, field_id, str);
270 }
271}
272
273static void SetSupportedAbis(JNIEnv* env, jclass build_class, const char* field,
274 const char* *values, int32_t value_count) {
275 if (value_count < 0) {
276 return;
277 }
278 if (values == nullptr && value_count > 0) {
279 ALOGW("More than zero values expected: %d.", value_count);
280 return;
281 }
282
283 jfieldID field_id = env->GetStaticFieldID(build_class, field, "[Ljava/lang/String;");
284 if (field_id != nullptr) {
285 // Create the array.
286 jobjectArray array = env->NewObjectArray(value_count, env->FindClass("java/lang/String"),
287 nullptr);
288 if (array == nullptr) {
289 env->ExceptionClear();
290 ALOGW("Could not create array.");
291 return;
292 }
293
294 // Fill the array.
295 for (int32_t i = 0; i < value_count; i++) {
296 jstring str = env->NewStringUTF(values[i]);
297 if (str == nullptr) {
298 env->ExceptionClear();
299 ALOGW("Could not create string %s.", values[i]);
300 return;
301 }
302
303 env->SetObjectArrayElement(array, i, str);
304 }
305
306 env->SetStaticObjectField(build_class, field_id, array);
307 } else {
308 env->ExceptionClear();
309 ALOGW("Could not find %s field.", field);
310 }
311}
312
313// Set up the environment for the bridged app.
314static void SetupEnvironment(NativeBridgeCallbacks* callbacks, JNIEnv* env, const char* isa) {
315 // Need a JNIEnv* to do anything.
316 if (env == nullptr) {
317 ALOGW("No JNIEnv* to set up app environment.");
318 return;
319 }
320
321 // Query the bridge for environment values.
322 const struct NativeBridgeRuntimeValues* env_values = callbacks->getAppEnv(isa);
323 if (env_values == nullptr) {
324 return;
325 }
326
327 // Keep the JNIEnv clean.
328 jint success = env->PushLocalFrame(16); // That should be small and large enough.
329 if (success < 0) {
330 // Out of memory, really borked.
331 ALOGW("Out of memory while setting up app environment.");
332 env->ExceptionClear();
333 return;
334 }
335
336 // Reset CPU_ABI & CPU_ABI2 to values required by the apps running with native bridge.
337 if (env_values->cpu_abi != nullptr || env_values->cpu_abi2 != nullptr ||
338 env_values->abi_count >= 0) {
339 jclass bclass_id = env->FindClass("android/os/Build");
340 if (bclass_id != nullptr) {
341 SetCpuAbi(env, bclass_id, "CPU_ABI", env_values->cpu_abi);
342 SetCpuAbi(env, bclass_id, "CPU_ABI2", env_values->cpu_abi2);
343
344 SetSupportedAbis(env, bclass_id, "SUPPORTED_ABIS", env_values->supported_abis,
345 env_values->abi_count);
346 } else {
347 // For example in a host test environment.
348 env->ExceptionClear();
349 ALOGW("Could not find Build class.");
350 }
351 }
352
353 if (env_values->os_arch != nullptr) {
354 jclass sclass_id = env->FindClass("java/lang/System");
355 if (sclass_id != nullptr) {
356 jmethodID set_prop_id = env->GetStaticMethodID(sclass_id, "setProperty",
357 "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;");
358 if (set_prop_id != nullptr) {
359 // Reset os.arch to the value reqired by the apps running with native bridge.
360 env->CallStaticObjectMethod(sclass_id, set_prop_id, env->NewStringUTF("os.arch"),
361 env->NewStringUTF(env_values->os_arch));
362 } else {
363 env->ExceptionClear();
364 ALOGW("Could not find setProperty method.");
365 }
366 } else {
367 env->ExceptionClear();
368 ALOGW("Could not find System class.");
369 }
370 }
371
372 // Make it pristine again.
373 env->PopLocalFrame(nullptr);
374}
375
376bool InitializeNativeBridge(JNIEnv* env, const char* instruction_set) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700377 // We expect only one place that calls InitializeNativeBridge: Runtime::DidForkFromZygote. At that
378 // point we are not multi-threaded, so we do not need locking here.
379
380 if (state == NativeBridgeState::kOpened) {
381 // Try to initialize.
jgu21ab0da5a2014-09-10 06:58:32 -0400382 if (callbacks->initialize(runtime_callbacks, app_data_dir, instruction_set)) {
383 SetupEnvironment(callbacks, env, instruction_set);
Andreas Gampe035bd752014-09-02 21:17:03 -0700384 state = NativeBridgeState::kInitialized;
385 } else {
386 // Unload the library.
387 dlclose(native_bridge_handle);
388 had_error = true;
389 state = NativeBridgeState::kClosed;
Calin Juravle961ae122014-08-11 16:11:59 +0100390 }
Andreas Gampe049249c2014-08-19 22:31:31 -0700391 } else {
Andreas Gampe049249c2014-08-19 22:31:31 -0700392 had_error = true;
Andreas Gampe035bd752014-09-02 21:17:03 -0700393 state = NativeBridgeState::kClosed;
Calin Juravle961ae122014-08-11 16:11:59 +0100394 }
395
Andreas Gampe035bd752014-09-02 21:17:03 -0700396 return state == NativeBridgeState::kInitialized;
397}
Calin Juravle961ae122014-08-11 16:11:59 +0100398
Andreas Gampe035bd752014-09-02 21:17:03 -0700399void UnloadNativeBridge() {
400 // We expect only one place that calls UnloadNativeBridge: Runtime::DidForkFromZygote. At that
401 // point we are not multi-threaded, so we do not need locking here.
402
403 switch(state) {
404 case NativeBridgeState::kOpened:
405 case NativeBridgeState::kInitialized:
406 // Unload.
407 dlclose(native_bridge_handle);
408 break;
409
410 case NativeBridgeState::kNotSetup:
411 // Not even set up. Error.
412 had_error = true;
413 break;
414
415 case NativeBridgeState::kClosed:
416 // Ignore.
417 break;
418 }
419
420 state = NativeBridgeState::kClosed;
Calin Juravle961ae122014-08-11 16:11:59 +0100421}
422
Andreas Gampe049249c2014-08-19 22:31:31 -0700423bool NativeBridgeError() {
424 return had_error;
425}
426
427bool NativeBridgeAvailable() {
Andreas Gampe035bd752014-09-02 21:17:03 -0700428 return state == NativeBridgeState::kOpened || state == NativeBridgeState::kInitialized;
429}
430
431bool NativeBridgeInitialized() {
432 // Calls of this are supposed to happen in a state where the native bridge is stable, i.e., after
433 // Runtime::DidForkFromZygote. In that case we do not need a lock.
434 return state == NativeBridgeState::kInitialized;
Andreas Gampe049249c2014-08-19 22:31:31 -0700435}
436
Calin Juravle961ae122014-08-11 16:11:59 +0100437void* NativeBridgeLoadLibrary(const char* libpath, int flag) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700438 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100439 return callbacks->loadLibrary(libpath, flag);
440 }
441 return nullptr;
442}
443
444void* NativeBridgeGetTrampoline(void* handle, const char* name, const char* shorty,
445 uint32_t len) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700446 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100447 return callbacks->getTrampoline(handle, name, shorty, len);
448 }
449 return nullptr;
450}
451
452bool NativeBridgeIsSupported(const char* libpath) {
Andreas Gampe035bd752014-09-02 21:17:03 -0700453 if (NativeBridgeInitialized()) {
Calin Juravle961ae122014-08-11 16:11:59 +0100454 return callbacks->isSupported(libpath);
455 }
456 return false;
457}
458
459}; // namespace android