Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(74)

Side by Side Diff: content/common/android/linker/linker_jni.cc

Issue 23717023: Android: Add chrome-specific dynamic linker. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Trivial rebase. Created 7 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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.
4
5 // This is the Android-specific Chrome linker, a tiny shared library
6 // implementing a custom dynamic linker that can be used to load the
7 // real Chrome libraries (e.g. libchromeview.so).
8
9 // The main point of this linker is to be able to share the RELRO
10 // section of libchromeview.so between the browser and renderer
11 // process. This saves about 1.3 MB of private RAM per renderer process.
12
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.
15
16 #include <android/log.h>
17 #include <crazy_linker.h>
18 #include <jni.h>
19 #include <stdlib.h>
20 #include <unistd.h>
21
22 // A special header that contains only constant definitions to avoid dragging
23 // any dependency from base/ into this file.
24 #include "base/android/sys_utils_constants.h"
25
26 // Set this to 1 to enable debug traces to the Android log.
27 // Note that LOG() from "base/logging.h" cannot be used, since it is
28 // in base/ which hasn't been loaded yet.
29 #define DEBUG 0
30
31 #define TAG "content_android_linker"
32
33 #if DEBUG
34 #define LOG_INFO(...) __android_log_print(ANDROID_LOG_INFO, TAG, __VA_ARGS__)
35 #define LOG_ERROR(...) __android_log_print(ANDROID_LOG_ERROR, TAG, __VA_ARGS__)
36 #else
37 #define LOG_INFO(...) ((void)0)
38 #define LOG_ERROR(...) ((void)0)
39 #endif
40
41 #define UNUSED __attribute__((unused))
42
43 namespace {
44
45 // A simply scoped UTF String class that can be initialized from
46 // a Java jstring handle. Modeled like std::string, which cannot
47 // be used here.
48 class String {
49 public:
50 String(JNIEnv* env, jstring str);
51
52 ~String() {
53 if (ptr_)
54 ::free(ptr_);
55 }
56
57 const char* c_str() const { return ptr_ ? ptr_ : ""; }
58 size_t size() const { return size_; }
59
60 private:
61 char* ptr_;
62 size_t size_;
63 };
64
65 String::String(JNIEnv* env, jstring str) {
66 size_ = env->GetStringUTFLength(str);
67 ptr_ = static_cast<char*>(::malloc(size_ + 1));
68
69 // Note: the result contains Java "modified UTF-8" bytes.
70 // Good enough for the linker though.
71 const char* bytes = env->GetStringUTFChars(str, NULL);
72 ::memcpy(ptr_, bytes, size_);
73 ptr_[size_] = '\0';
74
75 env->ReleaseStringUTFChars(str, bytes);
76 }
77
78 // A scoped crazy_library_t that automatically closes the handle
79 // on scope exit, unless Release() has been called.
80 class ScopedLibrary {
81 public:
82 ScopedLibrary() : lib_(NULL) {}
83
84 ~ScopedLibrary() {
85 if (lib_)
86 crazy_library_close(lib_);
87 }
88
89 crazy_library_t* Get() { return lib_; }
90
91 crazy_library_t** GetPtr() { return &lib_; }
92
93 crazy_library_t* Release() {
94 crazy_library_t* ret = lib_;
95 lib_ = NULL;
96 return ret;
97 }
98
99 private:
100 crazy_library_t* lib_;
101 };
102
103 // Return a pointer to the base name from an input |path| string.
104 const char* GetBaseNamePtr(const char* path) {
105 const char* p = strrchr(path, '/');
106 if (p)
107 return p + 1;
108 return path;
109 }
110
111 // Return true iff |address| is a valid address for the target CPU.
112 bool IsValidAddress(jlong address) {
113 return static_cast<jlong>(static_cast<size_t>(address)) == address;
114 }
115
116 // Find the jclass JNI reference corresponding to a given |class_name|.
117 // |env| is the current JNI environment handle.
118 // On success, return true and set |*clazz|.
119 bool InitClassReference(JNIEnv* env, const char* class_name, jclass* clazz) {
120 *clazz = env->FindClass(class_name);
121 if (!*clazz) {
122 LOG_ERROR("Could not find class for %s", class_name);
123 return false;
124 }
125 return true;
126 }
127
128 // Initialize a jfieldID corresponding to the field of a given |clazz|,
129 // with name |field_name| and signature |field_sig|.
130 // |env| is the current JNI environment handle.
131 // On success, return true and set |*field_id|.
132 bool InitFieldId(JNIEnv* env,
133 jclass clazz,
134 const char* field_name,
135 const char* field_sig,
136 jfieldID* field_id) {
137 *field_id = env->GetFieldID(clazz, field_name, field_sig);
138 if (!*field_id) {
139 LOG_ERROR("Could not find ID for field '%s'", field_name);
140 return false;
141 }
142 LOG_INFO(
143 "%s: Found ID %p for field '%s'", __FUNCTION__, *field_id, field_name);
144 return true;
145 }
146
147 // A class used to model the field IDs of the org.chromium.base.Linker
148 // LibInfo inner class, used to communicate data with the Java side
149 // of the linker.
150 struct LibInfo_class {
151 jfieldID load_address_id;
152 jfieldID load_size_id;
153 jfieldID relro_start_id;
154 jfieldID relro_size_id;
155 jfieldID relro_fd_id;
156
157 // Initialize an instance.
158 bool Init(JNIEnv* env) {
159 jclass clazz;
160 if (!InitClassReference(
161 env, "org/chromium/content/app/Linker$LibInfo", &clazz)) {
162 return false;
163 }
164
165 return InitFieldId(env, clazz, "mLoadAddress", "J", &load_address_id) &&
166 InitFieldId(env, clazz, "mLoadSize", "J", &load_size_id) &&
167 InitFieldId(env, clazz, "mRelroStart", "J", &relro_start_id) &&
168 InitFieldId(env, clazz, "mRelroSize", "J", &relro_size_id) &&
169 InitFieldId(env, clazz, "mRelroFd", "I", &relro_fd_id);
170 }
171
172 void SetLoadInfo(JNIEnv* env,
173 jobject library_info_obj,
174 size_t load_address,
175 size_t load_size) {
176 env->SetLongField(library_info_obj, load_address_id, load_address);
177 env->SetLongField(library_info_obj, load_size_id, load_size);
178 }
179
180 // Use this instance to convert a RelroInfo reference into
181 // a crazy_library_info_t.
182 void GetRelroInfo(JNIEnv* env,
183 jobject library_info_obj,
184 size_t* relro_start,
185 size_t* relro_size,
186 int* relro_fd) {
187 *relro_start = static_cast<size_t>(
188 env->GetLongField(library_info_obj, relro_start_id));
189
190 *relro_size =
191 static_cast<size_t>(env->GetLongField(library_info_obj, relro_size_id));
192
193 *relro_fd = env->GetIntField(library_info_obj, relro_fd_id);
194 }
195
196 void SetRelroInfo(JNIEnv* env,
197 jobject library_info_obj,
198 size_t relro_start,
199 size_t relro_size,
200 int relro_fd) {
201 env->SetLongField(library_info_obj, relro_start_id, relro_start);
202 env->SetLongField(library_info_obj, relro_size_id, relro_size);
203 env->SetIntField(library_info_obj, relro_fd_id, relro_fd);
204 }
205 };
206
207 static LibInfo_class s_lib_info_fields;
208
209 // The linker uses a single crazy_context_t object created on demand.
210 // There is no need to protect this against concurrent access, locking
211 // is already handled on the Java side.
212 static crazy_context_t* s_crazy_context;
213
214 crazy_context_t* GetCrazyContext() {
215 if (!s_crazy_context) {
216 // Create new context.
217 s_crazy_context = crazy_context_create();
218
219 // Ensure libraries located in the same directory as the linker
220 // can be loaded before system ones.
221 crazy_context_add_search_path_for_address(
222 s_crazy_context, reinterpret_cast<void*>(&s_crazy_context));
223 }
224
225 return s_crazy_context;
226 }
227
228 // Load a library with the Chrome linker. This will also call its
229 // JNI_OnLoad() method, which shall register its methods. Note that
230 // lazy native method resolution will _not_ work after this, because
231 // Dalvik uses the system's dlsym() which won't see the new library,
232 // so explicit registration is mandatory.
233 // |env| is the current JNI environment handle.
234 // |clazz| is the static class handle for org.chromium.base.Linker,
235 // and is ignored here.
236 // |library_name| is the library name (e.g. libfoo.so).
237 // |load_address| is an explicit load address.
238 // |library_info| is a LibInfo handle used to communicate information
239 // with the Java side.
240 // Return true on success.
241 jboolean LoadLibrary(JNIEnv* env,
242 jclass clazz,
243 jstring library_name,
244 jlong load_address,
245 jobject lib_info_obj) {
246 String lib_name(env, library_name);
247 const char* UNUSED lib_basename = GetBaseNamePtr(lib_name.c_str());
248
249 crazy_context_t* context = GetCrazyContext();
250
251 if (!IsValidAddress(load_address)) {
252 LOG_ERROR("%s: Invalid address 0x%llx", __FUNCTION__, load_address);
253 return false;
254 }
255
256 // Set the desired load address (0 means randomize it).
257 crazy_context_set_load_address(context, static_cast<size_t>(load_address));
258
259 // Open the library now.
260 LOG_INFO("%s: Opening shared library: %s", __FUNCTION__, lib_name.c_str());
261
262 ScopedLibrary library;
263 if (!crazy_library_open(library.GetPtr(), lib_name.c_str(), context)) {
264 LOG_ERROR("%s: Could not open %s: %s",
265 __FUNCTION__,
266 lib_basename,
267 crazy_context_get_error(context));
268 return false;
269 }
270
271 crazy_library_info_t info;
272 if (!crazy_library_get_info(library.Get(), context, &info)) {
273 LOG_ERROR("%s: Could not get library information for %s: %s",
274 __FUNCTION__,
275 lib_basename,
276 crazy_context_get_error(context));
277 return false;
278 }
279
280 // Release library object to keep it alive after the function returns.
281 library.Release();
282
283 s_lib_info_fields.SetLoadInfo(
284 env, lib_info_obj, info.load_address, info.load_size);
285 LOG_INFO("%s: Success loading library %s", __FUNCTION__, lib_basename);
286 return true;
287 }
288
289 jboolean CreateSharedRelro(JNIEnv* env,
290 jclass clazz,
291 jstring library_name,
292 jlong load_address,
293 jobject lib_info_obj) {
294 String lib_name(env, library_name);
295
296 LOG_INFO("%s: Called for %s", __FUNCTION__, lib_name.c_str());
297
298 if (!IsValidAddress(load_address)) {
299 LOG_ERROR("%s: Invalid address 0x%llx", __FUNCTION__, load_address);
300 return false;
301 }
302
303 ScopedLibrary library;
304 if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {
305 LOG_ERROR("%s: Could not find %s", __FUNCTION__, lib_name.c_str());
306 return false;
307 }
308
309 crazy_context_t* context = GetCrazyContext();
310 size_t relro_start = 0;
311 size_t relro_size = 0;
312 int relro_fd = -1;
313
314 if (!crazy_library_create_shared_relro(library.Get(),
315 context,
316 static_cast<size_t>(load_address),
317 &relro_start,
318 &relro_size,
319 &relro_fd)) {
320 LOG_ERROR("%s: Could not create shared RELRO sharing for %s: %s\n",
321 __FUNCTION__,
322 lib_name.c_str(),
323 crazy_context_get_error(context));
324 return false;
325 }
326
327 s_lib_info_fields.SetRelroInfo(
328 env, lib_info_obj, relro_start, relro_size, relro_fd);
329 return true;
330 }
331
332 jboolean UseSharedRelro(JNIEnv* env,
333 jclass clazz,
334 jstring library_name,
335 jobject lib_info_obj) {
336 String lib_name(env, library_name);
337
338 LOG_INFO("%s: called for %s, lib_info_ref=%p",
339 __FUNCTION__,
340 lib_name.c_str(),
341 lib_info_obj);
342
343 ScopedLibrary library;
344 if (!crazy_library_find_by_name(lib_name.c_str(), library.GetPtr())) {
345 LOG_ERROR("%s: Could not find %s", __FUNCTION__, lib_name.c_str());
346 return false;
347 }
348
349 crazy_context_t* context = GetCrazyContext();
350 size_t relro_start = 0;
351 size_t relro_size = 0;
352 int relro_fd = -1;
353 s_lib_info_fields.GetRelroInfo(
354 env, lib_info_obj, &relro_start, &relro_size, &relro_fd);
355
356 LOG_INFO("%s: library=%s relro start=%p size=%p fd=%d",
357 __FUNCTION__,
358 lib_name.c_str(),
359 (void*)relro_start,
360 (void*)relro_size,
361 relro_fd);
362
363 if (!crazy_library_use_shared_relro(
364 library.Get(), context, relro_start, relro_size, relro_fd)) {
365 LOG_ERROR("%s: Could not use shared RELRO for %s: %s",
366 __FUNCTION__,
367 lib_name.c_str(),
368 crazy_context_get_error(context));
369 return false;
370 }
371
372 LOG_INFO("%s: Library %s using shared RELRO section!",
373 __FUNCTION__,
374 lib_name.c_str());
375
376 return true;
377 }
378
379 jboolean CanUseSharedRelro(JNIEnv* env, jclass clazz) {
380 return crazy_system_can_share_relro();
381 }
382
383 jlong GetPageSize(JNIEnv* env, jclass clazz) {
384 jlong result = static_cast<jlong>(sysconf(_SC_PAGESIZE));
385 LOG_INFO("%s: System page size is %lld bytes\n", __FUNCTION__, result);
386 return result;
387 }
388
389 jboolean IsLowMemoryDevice(JNIEnv* env, jclass clazz) {
390 // This matches the implementation of org.chromium.base.SysUtils.isLowEnd(),
391 // however this Java method relies on native code from base/, which isn't
392 // available since the library hasn't been loaded yet.
393
394 // The threshold value is taken from a special base/ header that only defines
395 // constants as macros to avoid dragging any dependency into this file.
396
397 // Threshold for low-end memory devices.
398 const size_t kMegaBytes = 1024 * 1024;
399 const size_t kLowMemoryDeviceThreshold =
400 BASE_ANDROID_LOW_END_MEMORY_THRESHOLD_MB * kMegaBytes;
401
402 // Compute the amount of physical RAM on the device.
403 size_t pages = static_cast<size_t>(sysconf(_SC_PHYS_PAGES));
404 size_t page_size = static_cast<size_t>(sysconf(_SC_PAGESIZE));
405 size_t physical_size = pages * page_size;
406
407 LOG_INFO("%s: System physical size is %zu MB\n",
408 __FUNCTION__,
409 physical_size / kMegaBytes);
410
411 return physical_size <= kLowMemoryDeviceThreshold;
412 }
413
414 const JNINativeMethod kNativeMethods[] = {
415 {"nativeLoadLibrary",
416 "("
417 "Ljava/lang/String;"
418 "J"
419 "Lorg/chromium/content/app/Linker$LibInfo;"
420 ")"
421 "Z",
422 reinterpret_cast<void*>(&LoadLibrary)},
423 {"nativeCreateSharedRelro",
424 "("
425 "Ljava/lang/String;"
426 "J"
427 "Lorg/chromium/content/app/Linker$LibInfo;"
428 ")"
429 "Z",
430 reinterpret_cast<void*>(&CreateSharedRelro)},
431 {"nativeUseSharedRelro",
432 "("
433 "Ljava/lang/String;"
434 "Lorg/chromium/content/app/Linker$LibInfo;"
435 ")"
436 "Z",
437 reinterpret_cast<void*>(&UseSharedRelro)},
438 {"nativeCanUseSharedRelro",
439 "("
440 ")"
441 "Z",
442 reinterpret_cast<void*>(&CanUseSharedRelro)},
443 {"nativeGetPageSize",
444 "("
445 ")"
446 "J",
447 reinterpret_cast<void*>(&GetPageSize)},
448 {"nativeIsLowMemoryDevice",
449 "("
450 ")"
451 "Z",
452 reinterpret_cast<void*>(&IsLowMemoryDevice)}, };
453
454 } // namespace
455
456 // JNI_OnLoad() hook called when the linker library is loaded through
457 // the regular System.LoadLibrary) API. This shall save the Java VM
458 // handle and initialize LibInfo fields.
459 jint JNI_OnLoad(JavaVM* vm, void* reserved) {
460 LOG_INFO("%s: Entering", __FUNCTION__);
461 // Get new JNIEnv
462 JNIEnv* env;
463 if (JNI_OK != vm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_4)) {
464 LOG_ERROR("Could not create JNIEnv");
465 return -1;
466 }
467
468 // Register native methods.
469 jclass linker_class;
470 if (!InitClassReference(
471 env, "org/chromium/content/app/Linker", &linker_class))
472 return -1;
473
474 LOG_INFO("%s: Registering native methods", __FUNCTION__);
475 env->RegisterNatives(linker_class,
476 kNativeMethods,
477 sizeof(kNativeMethods) / sizeof(kNativeMethods[0]));
478
479 // Find LibInfo field ids.
480 LOG_INFO("%s: Caching field IDs", __FUNCTION__);
481 if (!s_lib_info_fields.Init(env)) {
482 return -1;
483 }
484
485 // Save JavaVM* handle into context.
486 crazy_context_t* context = GetCrazyContext();
487 crazy_context_set_java_vm(context, vm, JNI_VERSION_1_4);
488
489 LOG_INFO("%s: Done", __FUNCTION__);
490 return JNI_VERSION_1_4;
491 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698