1 // Copyright 2013 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 content linker, a tiny shared library
6 // implementing a custom dynamic linker that can be used to load the
7 // real content-based 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 "content_android_linker"
30 #define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
31 #define LOG_ERROR(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
33 #define LOG_INFO(...) ((void)0)
34 #define LOG_ERROR(...) ((void)0)
37 #define UNUSED __attribute__((unused))
41 // A simply scoped UTF String class that can be initialized from
42 // a Java jstring handle. Modeled like std::string, which cannot
46 String(JNIEnv* env, jstring str);
53 const char* c_str() const { return ptr_ ? ptr_ : ""; }
54 size_t size() const { return size_; }
61 String::String(JNIEnv* env, jstring str) {
62 size_ = env->GetStringUTFLength(str);
63 ptr_ = static_cast<char*>(::malloc(size_ + 1));
65 // Note: the result contains Java "modified UTF-8" bytes.
66 // Good enough for the linker though.
67 const char* bytes = env->GetStringUTFChars(str, NULL);
68 ::memcpy(ptr_, bytes, size_);
71 env->ReleaseStringUTFChars(str, bytes);
74 // A scoped crazy_library_t that automatically closes the handle
75 // on scope exit, unless Release() has been called.
78 ScopedLibrary() : lib_(NULL) {}
82 crazy_library_close(lib_);
85 crazy_library_t* Get() { return lib_; }
87 crazy_library_t** GetPtr() { return &lib_; }
89 crazy_library_t* Release() {
90 crazy_library_t* ret = lib_;
96 crazy_library_t* lib_;
99 // Return a pointer to the base name from an input |path| string.
100 const char* GetBaseNamePtr(const char* path) {
101 const char* p = strrchr(path, '/');
107 // Return true iff |address| is a valid address for the target CPU.
108 bool IsValidAddress(jlong address) {
109 return static_cast<jlong>(static_cast<size_t>(address)) == address;
112 // Find the jclass JNI reference corresponding to a given |class_name|.
113 // |env| is the current JNI environment handle.
114 // On success, return true and set |*clazz|.
115 bool InitClassReference(JNIEnv* env, const char* class_name, jclass* clazz) {
116 *clazz = env->FindClass(class_name);
118 LOG_ERROR("Could not find class for %s", class_name);
124 // Initialize a jfieldID corresponding to the field of a given |clazz|,
125 // with name |field_name| and signature |field_sig|.
126 // |env| is the current JNI environment handle.
127 // On success, return true and set |*field_id|.
128 bool InitFieldId(JNIEnv* env,
130 const char* field_name,
131 const char* field_sig,
132 jfieldID* field_id) {
133 *field_id = env->GetFieldID(clazz, field_name, field_sig);
135 LOG_ERROR("Could not find ID for field '%s'", field_name);
139 "%s: Found ID %p for field '%s'", __FUNCTION__, *field_id, field_name);
143 // A class used to model the field IDs of the org.chromium.base.Linker
144 // LibInfo inner class, used to communicate data with the Java side
146 struct LibInfo_class {
147 jfieldID load_address_id;
148 jfieldID load_size_id;
149 jfieldID relro_start_id;
150 jfieldID relro_size_id;
151 jfieldID relro_fd_id;
153 // Initialize an instance.
154 bool Init(JNIEnv* env) {
156 if (!InitClassReference(
157 env, "org/chromium/content/app/Linker$LibInfo", &clazz)) {
161 return InitFieldId(env, clazz, "mLoadAddress", "J", &load_address_id) &&
162 InitFieldId(env, clazz, "mLoadSize", "J", &load_size_id) &&
163 InitFieldId(env, clazz, "mRelroStart", "J", &relro_start_id) &&
164 InitFieldId(env, clazz, "mRelroSize", "J", &relro_size_id) &&
165 InitFieldId(env, clazz, "mRelroFd", "I", &relro_fd_id);
168 void SetLoadInfo(JNIEnv* env,
169 jobject library_info_obj,
172 env->SetLongField(library_info_obj, load_address_id, load_address);
173 env->SetLongField(library_info_obj, load_size_id, load_size);
176 // Use this instance to convert a RelroInfo reference into
177 // a crazy_library_info_t.
178 void GetRelroInfo(JNIEnv* env,
179 jobject library_info_obj,
183 *relro_start = static_cast<size_t>(
184 env->GetLongField(library_info_obj, relro_start_id));
187 static_cast<size_t>(env->GetLongField(library_info_obj, relro_size_id));
189 *relro_fd = env->GetIntField(library_info_obj, relro_fd_id);
192 void SetRelroInfo(JNIEnv* env,
193 jobject library_info_obj,
197 env->SetLongField(library_info_obj, relro_start_id, relro_start);
198 env->SetLongField(library_info_obj, relro_size_id, relro_size);
199 env->SetIntField(library_info_obj, relro_fd_id, relro_fd);
203 static LibInfo_class s_lib_info_fields;
205 // The linker uses a single crazy_context_t object created on demand.
206 // There is no need to protect this against concurrent access, locking
207 // is already handled on the Java side.
208 static crazy_context_t* s_crazy_context;
210 crazy_context_t* GetCrazyContext() {
211 if (!s_crazy_context) {
212 // Create new context.
213 s_crazy_context = crazy_context_create();
215 // Ensure libraries located in the same directory as the linker
216 // can be loaded before system ones.
217 crazy_context_add_search_path_for_address(
218 s_crazy_context, reinterpret_cast<void*>(&s_crazy_context));
221 return s_crazy_context;
224 // Load a library with the content linker. This will also call its
225 // JNI_OnLoad() method, which shall register its methods. Note that
226 // lazy native method resolution will _not_ work after this, because
227 // Dalvik uses the system's dlsym() which won't see the new library,
228 // so explicit registration is mandatory.
229 // |env| is the current JNI environment handle.
230 // |clazz| is the static class handle for org.chromium.base.Linker,
231 // and is ignored here.
232 // |library_name| is the library name (e.g. libfoo.so).
233 // |load_address| is an explicit load address.
234 // |library_info| is a LibInfo handle used to communicate information
235 // with the Java side.
236 // Return true on success.
237 jboolean LoadLibrary(JNIEnv* env,
239 jstring library_name,
241 jobject lib_info_obj) {
242 String lib_name(env, library_name);
243 const char* UNUSED lib_basename = GetBaseNamePtr(lib_name.c_str());
245 crazy_context_t* context = GetCrazyContext();
247 if (!IsValidAddress(load_address)) {
248 LOG_ERROR("%s: Invalid address 0x%llx", __FUNCTION__, load_address);
252 // Set the desired load address (0 means randomize it).
253 crazy_context_set_load_address(context, static_cast<size_t>(load_address));
255 // Open the library now.
256 LOG_INFO("%s: Opening shared library: %s", __FUNCTION__, lib_name.c_str());
258 ScopedLibrary library;
259 if (!crazy_library_open(library.GetPtr(), lib_name.c_str(), context)) {
260 LOG_ERROR("%s: Could not open %s: %s",
263 crazy_context_get_error(context));
267 crazy_library_info_t info;
268 if (!crazy_library_get_info(library.Get(), context, &info)) {
269 LOG_ERROR("%s: Could not get library information for %s: %s",
272 crazy_context_get_error(context));
276 // Release library object to keep it alive after the function returns.
279 s_lib_info_fields.SetLoadInfo(
280 env, lib_info_obj, info.load_address, info.load_size);
281 LOG_INFO("%s: Success loading library %s", __FUNCTION__, lib_basename);
285 jboolean CreateSharedRelro(JNIEnv* env,
287 jstring library_name,
289 jobject lib_info_obj) {
290 String lib_name(env, library_name);
292 LOG_INFO("%s: Called for %s", __FUNCTION__, lib_name.c_str());
294 if (!IsValidAddress(load_address)) {
295 LOG_ERROR("%s: Invalid address 0x%llx", __FUNCTION__, load_address);
299 ScopedLibrary library;
300 if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {
301 LOG_ERROR("%s: Could not find %s", __FUNCTION__, lib_name.c_str());
305 crazy_context_t* context = GetCrazyContext();
306 size_t relro_start = 0;
307 size_t relro_size = 0;
310 if (!crazy_library_create_shared_relro(library.Get(),
312 static_cast<size_t>(load_address),
316 LOG_ERROR("%s: Could not create shared RELRO sharing for %s: %s\n",
319 crazy_context_get_error(context));
323 s_lib_info_fields.SetRelroInfo(
324 env, lib_info_obj, relro_start, relro_size, relro_fd);
328 jboolean UseSharedRelro(JNIEnv* env,
330 jstring library_name,
331 jobject lib_info_obj) {
332 String lib_name(env, library_name);
334 LOG_INFO("%s: called for %s, lib_info_ref=%p",
339 ScopedLibrary library;
340 if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {
341 LOG_ERROR("%s: Could not find %s", __FUNCTION__, lib_name.c_str());
345 crazy_context_t* context = GetCrazyContext();
346 size_t relro_start = 0;
347 size_t relro_size = 0;
349 s_lib_info_fields.GetRelroInfo(
350 env, lib_info_obj, &relro_start, &relro_size, &relro_fd);
352 LOG_INFO("%s: library=%s relro start=%p size=%p fd=%d",
359 if (!crazy_library_use_shared_relro(
360 library.Get(), context, relro_start, relro_size, relro_fd)) {
361 LOG_ERROR("%s: Could not use shared RELRO for %s: %s",
364 crazy_context_get_error(context));
368 LOG_INFO("%s: Library %s using shared RELRO section!",
375 jboolean CanUseSharedRelro(JNIEnv* env, jclass clazz) {
376 return crazy_system_can_share_relro();
379 jlong GetPageSize(JNIEnv* env, jclass clazz) {
380 jlong result = static_cast<jlong>(sysconf(_SC_PAGESIZE));
381 LOG_INFO("%s: System page size is %lld bytes\n", __FUNCTION__, result);
385 const JNINativeMethod kNativeMethods[] = {
386 {"nativeLoadLibrary",
390 "Lorg/chromium/content/app/Linker$LibInfo;"
393 reinterpret_cast<void*>(&LoadLibrary)},
394 {"nativeCreateSharedRelro",
398 "Lorg/chromium/content/app/Linker$LibInfo;"
401 reinterpret_cast<void*>(&CreateSharedRelro)},
402 {"nativeUseSharedRelro",
405 "Lorg/chromium/content/app/Linker$LibInfo;"
408 reinterpret_cast<void*>(&UseSharedRelro)},
409 {"nativeCanUseSharedRelro",
413 reinterpret_cast<void*>(&CanUseSharedRelro)},
414 {"nativeGetPageSize",
418 reinterpret_cast<void*>(&GetPageSize)}, };
422 // JNI_OnLoad() hook called when the linker library is loaded through
423 // the regular System.LoadLibrary) API. This shall save the Java VM
424 // handle and initialize LibInfo fields.
425 jint JNI_OnLoad(JavaVM* vm, void* reserved) {
426 LOG_INFO("%s: Entering", __FUNCTION__);
429 if (JNI_OK != vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_4)) {
430 LOG_ERROR("Could not create JNIEnv");
434 // Register native methods.
436 if (!InitClassReference(
437 env, "org/chromium/content/app/Linker", &linker_class))
440 LOG_INFO("%s: Registering native methods", __FUNCTION__);
441 env->RegisterNatives(linker_class,
443 sizeof(kNativeMethods) / sizeof(kNativeMethods[0]));
445 // Find LibInfo field ids.
446 LOG_INFO("%s: Caching field IDs", __FUNCTION__);
447 if (!s_lib_info_fields.Init(env)) {
451 // Save JavaVM* handle into context.
452 crazy_context_t* context = GetCrazyContext();
453 crazy_context_set_java_vm(context, vm, JNI_VERSION_1_4);
455 LOG_INFO("%s: Done", __FUNCTION__);
456 return JNI_VERSION_1_4;