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

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

Powered by Google App Engine
This is Rietveld 408576698