1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 // This is the Android-specific Chromium linker, a tiny shared library
6 // implementing a custom dynamic linker that can be used to load the
7 // real Chromium libraries (e.g. libcontentshell.so).
9 // The main point of this linker is to be able to share the RELRO
10 // section of libcontentshell.so (or equivalent) between the browser and
13 // This source code *cannot* depend on anything from base/ or the C++
14 // STL, to keep the final library small, and avoid ugly dependency issues.
16 #include <android/log.h>
17 #include <crazy_linker.h>
22 // Set this to 1 to enable debug traces to the Android log.
23 // Note that LOG() from "base/logging.h" cannot be used, since it is
24 // in base/ which hasn't been loaded yet.
27 #define TAG "chromium_android_linker"
30 #define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
32 #define LOG_INFO(...) ((void)0)
34 #define LOG_ERROR(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
36 #define UNUSED __attribute__((unused))
40 // A simply scoped UTF String class that can be initialized from
41 // a Java jstring handle. Modeled like std::string, which cannot
45 String(JNIEnv* env, jstring str);
52 const char* c_str() const { return ptr_ ? ptr_ : ""; }
53 size_t size() const { return size_; }
60 String::String(JNIEnv* env, jstring str) {
61 size_ = env->GetStringUTFLength(str);
62 ptr_ = static_cast<char*>(::malloc(size_ + 1));
64 // Note: the result contains Java "modified UTF-8" bytes.
65 // Good enough for the linker though.
66 const char* bytes = env->GetStringUTFChars(str, NULL);
67 ::memcpy(ptr_, bytes, size_);
70 env->ReleaseStringUTFChars(str, bytes);
73 // Return true iff |address| is a valid address for the target CPU.
74 bool IsValidAddress(jlong address) {
75 return static_cast<jlong>(static_cast<size_t>(address)) == address;
78 // Find the jclass JNI reference corresponding to a given |class_name|.
79 // |env| is the current JNI environment handle.
80 // On success, return true and set |*clazz|.
81 bool InitClassReference(JNIEnv* env, const char* class_name, jclass* clazz) {
82 *clazz = env->FindClass(class_name);
84 LOG_ERROR("Could not find class for %s", class_name);
90 // Initialize a jfieldID corresponding to the field of a given |clazz|,
91 // with name |field_name| and signature |field_sig|.
92 // |env| is the current JNI environment handle.
93 // On success, return true and set |*field_id|.
94 bool InitFieldId(JNIEnv* env,
96 const char* field_name,
97 const char* field_sig,
99 *field_id = env->GetFieldID(clazz, field_name, field_sig);
101 LOG_ERROR("Could not find ID for field '%s'", field_name);
105 "%s: Found ID %p for field '%s'", __FUNCTION__, *field_id, field_name);
109 // Initialize a jmethodID corresponding to the static method of a given
110 // |clazz|, with name |method_name| and signature |method_sig|.
111 // |env| is the current JNI environment handle.
112 // On success, return true and set |*method_id|.
113 bool InitStaticMethodId(JNIEnv* env,
115 const char* method_name,
116 const char* method_sig,
117 jmethodID* method_id) {
118 *method_id = env->GetStaticMethodID(clazz, method_name, method_sig);
120 LOG_ERROR("Could not find ID for static method '%s'", method_name);
123 LOG_INFO("%s: Found ID %p for static method '%s'",
124 __FUNCTION__, *method_id, method_name);
128 // A class used to model the field IDs of the org.chromium.base.Linker
129 // LibInfo inner class, used to communicate data with the Java side
131 struct LibInfo_class {
132 jfieldID load_address_id;
133 jfieldID load_size_id;
134 jfieldID relro_start_id;
135 jfieldID relro_size_id;
136 jfieldID relro_fd_id;
138 // Initialize an instance.
139 bool Init(JNIEnv* env) {
141 if (!InitClassReference(
142 env, "org/chromium/base/library_loader/Linker$LibInfo", &clazz)) {
146 return InitFieldId(env, clazz, "mLoadAddress", "J", &load_address_id) &&
147 InitFieldId(env, clazz, "mLoadSize", "J", &load_size_id) &&
148 InitFieldId(env, clazz, "mRelroStart", "J", &relro_start_id) &&
149 InitFieldId(env, clazz, "mRelroSize", "J", &relro_size_id) &&
150 InitFieldId(env, clazz, "mRelroFd", "I", &relro_fd_id);
153 void SetLoadInfo(JNIEnv* env,
154 jobject library_info_obj,
157 env->SetLongField(library_info_obj, load_address_id, load_address);
158 env->SetLongField(library_info_obj, load_size_id, load_size);
161 // Use this instance to convert a RelroInfo reference into
162 // a crazy_library_info_t.
163 void GetRelroInfo(JNIEnv* env,
164 jobject library_info_obj,
168 *relro_start = static_cast<size_t>(
169 env->GetLongField(library_info_obj, relro_start_id));
172 static_cast<size_t>(env->GetLongField(library_info_obj, relro_size_id));
174 *relro_fd = env->GetIntField(library_info_obj, relro_fd_id);
177 void SetRelroInfo(JNIEnv* env,
178 jobject library_info_obj,
182 env->SetLongField(library_info_obj, relro_start_id, relro_start);
183 env->SetLongField(library_info_obj, relro_size_id, relro_size);
184 env->SetIntField(library_info_obj, relro_fd_id, relro_fd);
188 static LibInfo_class s_lib_info_fields;
190 // The linker uses a single crazy_context_t object created on demand.
191 // There is no need to protect this against concurrent access, locking
192 // is already handled on the Java side.
193 static crazy_context_t* s_crazy_context;
195 crazy_context_t* GetCrazyContext() {
196 if (!s_crazy_context) {
197 // Create new context.
198 s_crazy_context = crazy_context_create();
200 // Ensure libraries located in the same directory as the linker
201 // can be loaded before system ones.
202 crazy_context_add_search_path_for_address(
203 s_crazy_context, reinterpret_cast<void*>(&s_crazy_context));
206 return s_crazy_context;
209 // A scoped crazy_library_t that automatically closes the handle
210 // on scope exit, unless Release() has been called.
211 class ScopedLibrary {
213 ScopedLibrary() : lib_(NULL) {}
217 crazy_library_close_with_context(lib_, GetCrazyContext());
220 crazy_library_t* Get() { return lib_; }
222 crazy_library_t** GetPtr() { return &lib_; }
224 crazy_library_t* Release() {
225 crazy_library_t* ret = lib_;
231 crazy_library_t* lib_;
236 template <class LibraryOpener>
237 bool GenericLoadLibrary(
239 const char* library_name, jlong load_address, jobject lib_info_obj,
240 const LibraryOpener& opener) {
241 crazy_context_t* context = GetCrazyContext();
243 if (!IsValidAddress(load_address)) {
244 LOG_ERROR("%s: Invalid address 0x%llx", __FUNCTION__, load_address);
248 // Set the desired load address (0 means randomize it).
249 crazy_context_set_load_address(context, static_cast<size_t>(load_address));
251 ScopedLibrary library;
252 if (!opener.Open(library.GetPtr(), library_name, context)) {
256 crazy_library_info_t info;
257 if (!crazy_library_get_info(library.Get(), context, &info)) {
258 LOG_ERROR("%s: Could not get library information for %s: %s",
261 crazy_context_get_error(context));
265 // Release library object to keep it alive after the function returns.
268 s_lib_info_fields.SetLoadInfo(
269 env, lib_info_obj, info.load_address, info.load_size);
270 LOG_INFO("%s: Success loading library %s", __FUNCTION__, library_name);
274 // Used for opening the library in a regular file.
275 class FileLibraryOpener {
278 crazy_library_t** library,
279 const char* library_name,
280 crazy_context_t* context) const;
283 bool FileLibraryOpener::Open(
284 crazy_library_t** library,
285 const char* library_name,
286 crazy_context_t* context) const {
287 if (!crazy_library_open(library, library_name, context)) {
288 LOG_ERROR("%s: Could not open %s: %s",
291 crazy_context_get_error(context));
297 // Used for opening the library in a zip file.
298 class ZipLibraryOpener {
300 explicit ZipLibraryOpener(const char* zip_file) : zip_file_(zip_file) {}
302 crazy_library_t** library,
303 const char* library_name,
304 crazy_context_t* context) const;
306 const char* zip_file_;
309 bool ZipLibraryOpener::Open(
310 crazy_library_t** library,
311 const char* library_name,
312 crazy_context_t* context) const {
313 if (!crazy_library_open_in_zip_file(
314 library, zip_file_, library_name, context)) {
315 LOG_ERROR("%s: Could not open %s in zip file %s: %s",
316 __FUNCTION__, library_name, zip_file_,
317 crazy_context_get_error(context));
323 } // unnamed namespace
325 // Load a library with the chromium linker. This will also call its
326 // JNI_OnLoad() method, which shall register its methods. Note that
327 // lazy native method resolution will _not_ work after this, because
328 // Dalvik uses the system's dlsym() which won't see the new library,
329 // so explicit registration is mandatory.
330 // |env| is the current JNI environment handle.
331 // |clazz| is the static class handle for org.chromium.base.Linker,
332 // and is ignored here.
333 // |library_name| is the library name (e.g. libfoo.so).
334 // |load_address| is an explicit load address.
335 // |library_info| is a LibInfo handle used to communicate information
336 // with the Java side.
337 // Return true on success.
338 jboolean LoadLibrary(JNIEnv* env,
340 jstring library_name,
342 jobject lib_info_obj) {
343 String lib_name(env, library_name);
344 FileLibraryOpener opener;
345 return GenericLoadLibrary(
346 env, lib_name.c_str(),
347 static_cast<size_t>(load_address), lib_info_obj, opener);
350 // Load a library from a zipfile with the chromium linker. The
351 // library in the zipfile must be uncompressed and page aligned.
352 // The basename of the library is given. The library is expected
353 // to be lib/<abi_tag>/crazy.<basename>. The <abi_tag> used will be the
354 // same as the abi for this linker. The "crazy." prefix is included
355 // so that the Android Package Manager doesn't extract the library into
358 // Loading the library will also call its JNI_OnLoad() method, which
359 // shall register its methods. Note that lazy native method resolution
360 // will _not_ work after this, because Dalvik uses the system's dlsym()
361 // which won't see the new library, so explicit registration is mandatory.
363 // |env| is the current JNI environment handle.
364 // |clazz| is the static class handle for org.chromium.base.Linker,
365 // and is ignored here.
366 // |zipfile_name| is the filename of the zipfile containing the library.
367 // |library_name| is the library base name (e.g. libfoo.so).
368 // |load_address| is an explicit load address.
369 // |library_info| is a LibInfo handle used to communicate information
370 // with the Java side.
371 // Returns true on success.
372 jboolean LoadLibraryInZipFile(JNIEnv* env,
374 jstring zipfile_name,
375 jstring library_name,
377 jobject lib_info_obj) {
378 String zipfile_name_str(env, zipfile_name);
379 String lib_name(env, library_name);
380 ZipLibraryOpener opener(zipfile_name_str.c_str());
381 return GenericLoadLibrary(
382 env, lib_name.c_str(),
383 static_cast<size_t>(load_address), lib_info_obj, opener);
386 // Class holding the Java class and method ID for the Java side Linker
387 // postCallbackOnMainThread method.
388 struct JavaCallbackBindings_class {
392 // Initialize an instance.
393 bool Init(JNIEnv* env, jclass linker_class) {
394 clazz = reinterpret_cast<jclass>(env->NewGlobalRef(linker_class));
395 return InitStaticMethodId(env,
397 "postCallbackOnMainThread",
403 static JavaCallbackBindings_class s_java_callback_bindings;
405 // Designated receiver function for callbacks from Java. Its name is known
407 // |env| is the current JNI environment handle and is ignored here.
408 // |clazz| is the static class handle for org.chromium.base.Linker,
409 // and is ignored here.
410 // |arg| is a pointer to an allocated crazy_callback_t, deleted after use.
411 void RunCallbackOnUiThread(JNIEnv* env, jclass clazz, jlong arg) {
412 crazy_callback_t* callback = reinterpret_cast<crazy_callback_t*>(arg);
414 LOG_INFO("%s: Called back from java with handler %p, opaque %p",
415 __FUNCTION__, callback->handler, callback->opaque);
417 crazy_callback_run(callback);
421 // Request a callback from Java. The supplied crazy_callback_t is valid only
422 // for the duration of this call, so we copy it to a newly allocated
423 // crazy_callback_t and then call the Java side's postCallbackOnMainThread.
424 // This will call back to to our RunCallbackOnUiThread some time
425 // later on the UI thread.
426 // |callback_request| is a crazy_callback_t.
427 // |poster_opaque| is unused.
428 // Returns true if the callback request succeeds.
429 static bool PostForLaterExecution(crazy_callback_t* callback_request,
430 void* poster_opaque UNUSED) {
431 crazy_context_t* context = GetCrazyContext();
434 int minimum_jni_version;
435 crazy_context_get_java_vm(context,
436 reinterpret_cast<void**>(&vm),
437 &minimum_jni_version);
439 // Do not reuse JNIEnv from JNI_OnLoad, but retrieve our own.
441 if (JNI_OK != vm->GetEnv(
442 reinterpret_cast<void**>(&env), minimum_jni_version)) {
443 LOG_ERROR("Could not create JNIEnv");
447 // Copy the callback; the one passed as an argument may be temporary.
448 crazy_callback_t* callback = new crazy_callback_t();
449 *callback = *callback_request;
451 LOG_INFO("%s: Calling back to java with handler %p, opaque %p",
452 __FUNCTION__, callback->handler, callback->opaque);
454 jlong arg = static_cast<jlong>(reinterpret_cast<intptr_t>(callback));
455 env->CallStaticVoidMethod(
456 s_java_callback_bindings.clazz, s_java_callback_bindings.method_id, arg);
458 // Back out and return false if we encounter a JNI exception.
459 if (env->ExceptionCheck() == JNI_TRUE) {
460 env->ExceptionDescribe();
461 env->ExceptionClear();
469 jboolean CreateSharedRelro(JNIEnv* env,
471 jstring library_name,
473 jobject lib_info_obj) {
474 String lib_name(env, library_name);
476 LOG_INFO("%s: Called for %s", __FUNCTION__, lib_name.c_str());
478 if (!IsValidAddress(load_address)) {
479 LOG_ERROR("%s: Invalid address 0x%llx", __FUNCTION__, load_address);
483 ScopedLibrary library;
484 if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {
485 LOG_ERROR("%s: Could not find %s", __FUNCTION__, lib_name.c_str());
489 crazy_context_t* context = GetCrazyContext();
490 size_t relro_start = 0;
491 size_t relro_size = 0;
494 if (!crazy_library_create_shared_relro(library.Get(),
496 static_cast<size_t>(load_address),
500 LOG_ERROR("%s: Could not create shared RELRO sharing for %s: %s\n",
503 crazy_context_get_error(context));
507 s_lib_info_fields.SetRelroInfo(
508 env, lib_info_obj, relro_start, relro_size, relro_fd);
512 jboolean UseSharedRelro(JNIEnv* env,
514 jstring library_name,
515 jobject lib_info_obj) {
516 String lib_name(env, library_name);
518 LOG_INFO("%s: called for %s, lib_info_ref=%p",
523 ScopedLibrary library;
524 if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {
525 LOG_ERROR("%s: Could not find %s", __FUNCTION__, lib_name.c_str());
529 crazy_context_t* context = GetCrazyContext();
530 size_t relro_start = 0;
531 size_t relro_size = 0;
533 s_lib_info_fields.GetRelroInfo(
534 env, lib_info_obj, &relro_start, &relro_size, &relro_fd);
536 LOG_INFO("%s: library=%s relro start=%p size=%p fd=%d",
543 if (!crazy_library_use_shared_relro(
544 library.Get(), context, relro_start, relro_size, relro_fd)) {
545 LOG_ERROR("%s: Could not use shared RELRO for %s: %s",
548 crazy_context_get_error(context));
552 LOG_INFO("%s: Library %s using shared RELRO section!",
559 jboolean CanUseSharedRelro(JNIEnv* env, jclass clazz) {
560 return crazy_system_can_share_relro();
563 jlong GetPageSize(JNIEnv* env, jclass clazz) {
564 jlong result = static_cast<jlong>(sysconf(_SC_PAGESIZE));
565 LOG_INFO("%s: System page size is %lld bytes\n", __FUNCTION__, result);
569 const JNINativeMethod kNativeMethods[] = {
570 {"nativeLoadLibrary",
574 "Lorg/chromium/base/library_loader/Linker$LibInfo;"
577 reinterpret_cast<void*>(&LoadLibrary)},
578 {"nativeLoadLibraryInZipFile",
583 "Lorg/chromium/base/library_loader/Linker$LibInfo;"
586 reinterpret_cast<void*>(&LoadLibraryInZipFile)},
587 {"nativeRunCallbackOnUiThread",
592 reinterpret_cast<void*>(&RunCallbackOnUiThread)},
593 {"nativeCreateSharedRelro",
597 "Lorg/chromium/base/library_loader/Linker$LibInfo;"
600 reinterpret_cast<void*>(&CreateSharedRelro)},
601 {"nativeUseSharedRelro",
604 "Lorg/chromium/base/library_loader/Linker$LibInfo;"
607 reinterpret_cast<void*>(&UseSharedRelro)},
608 {"nativeCanUseSharedRelro",
612 reinterpret_cast<void*>(&CanUseSharedRelro)},
613 {"nativeGetPageSize",
617 reinterpret_cast<void*>(&GetPageSize)}, };
621 // JNI_OnLoad() hook called when the linker library is loaded through
622 // the regular System.LoadLibrary) API. This shall save the Java VM
623 // handle and initialize LibInfo fields.
624 jint JNI_OnLoad(JavaVM* vm, void* reserved) {
625 LOG_INFO("%s: Entering", __FUNCTION__);
628 if (JNI_OK != vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_4)) {
629 LOG_ERROR("Could not create JNIEnv");
633 // Register native methods.
635 if (!InitClassReference(env,
636 "org/chromium/base/library_loader/Linker",
640 LOG_INFO("%s: Registering native methods", __FUNCTION__);
641 env->RegisterNatives(linker_class,
643 sizeof(kNativeMethods) / sizeof(kNativeMethods[0]));
645 // Find LibInfo field ids.
646 LOG_INFO("%s: Caching field IDs", __FUNCTION__);
647 if (!s_lib_info_fields.Init(env)) {
651 // Resolve and save the Java side Linker callback class and method.
652 LOG_INFO("%s: Resolving callback bindings", __FUNCTION__);
653 if (!s_java_callback_bindings.Init(env, linker_class)) {
657 // Save JavaVM* handle into context.
658 crazy_context_t* context = GetCrazyContext();
659 crazy_context_set_java_vm(context, vm, JNI_VERSION_1_4);
661 // Register the function that the crazy linker can call to post code
662 // for later execution.
663 crazy_context_set_callback_poster(context, &PostForLaterExecution, NULL);
665 LOG_INFO("%s: Done", __FUNCTION__);
666 return JNI_VERSION_1_4;