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 package org.chromium.content.app;
8 import java.io.FileInputStream;
10 import java.util.HashMap;
14 import android.content.Context;
15 import android.os.Bundle;
16 import android.os.Parcel;
17 import android.os.Parcelable;
18 import android.os.ParcelFileDescriptor;
19 import android.util.Log;
24 * The point of this class is to provide an alternative to System.loadLibrary()
25 * to load native shared libraries. One specific feature that it supports is the
26 * ability to save RAM by sharing the ELF RELRO sections between renderer
29 * When two processes load the same native library at the _same_ memory address,
30 * the content of their RELRO section (which includes C++ vtables or any
31 * constants that contain pointers) will be largely identical [1].
33 * By default, the RELRO section is backed by private RAM in each process,
34 * which is still significant on mobile (e.g. 1.28 MB / process on Chrome 30 for
37 * However, it is possible to save RAM by creating a shared memory region,
38 * copy the RELRO content into it, then have each process swap its private,
39 * regular RELRO, with a shared, read-only, mapping of the shared one.
41 * This trick saves 98% of the RELRO section size per extra process, after the
42 * first one. On the other hand, this requires careful communication between
43 * the process where the shared RELRO is created and the one(s) where it is used.
45 * Note that swapping the regular RELRO with the shared one is not an atomic
46 * operation. Care must be taken that no other thread tries to run native code
47 * that accesses it during it. In practice, this means the swap must happen
48 * before library native code is executed.
50 * [1] The exceptions are pointers to external, randomized, symbols, like
51 * those from some system libraries, but these are very few in practice.
55 * Security considerations:
57 * - Whether the browser process loads its native libraries at the same
58 * addresses as the service ones (to save RAM by sharing the RELRO too)
59 * depends on the configuration variable BROWSER_SHARED_RELRO_CONFIG below.
61 * Not using fixed library addresses in the browser process is preferred
62 * for regular devices since it maintains the efficacy of ASLR as an
63 * exploit mitigation across the render <-> browser privilege boundary.
65 * - The shared RELRO memory region is always forced read-only after creation,
66 * which means it is impossible for a compromised service process to map
67 * it read-write (e.g. by calling mmap() or mprotect()) and modify its
68 * content, altering values seen in other service processes.
70 * - Unfortunately, certain Android systems use an old, buggy kernel, that
71 * doesn't check Ashmem region permissions correctly. See CVE-2011-1149
72 * for details. This linker probes the system on startup and will completely
73 * disable shared RELROs if it detects the problem. For the record, this is
74 * common for Android emulator system images (which are still based on 2.6.29)
76 * - Once the RELRO ashmem region is mapped into a service process' address
77 * space, the corresponding file descriptor is immediately closed. The
78 * file descriptor is kept opened in the browser process, because a copy needs
79 * to be sent to each new potential service process.
81 * - The common library load addresses are randomized for each instance of
82 * the program on the device. See computeRandomBaseLoadAddress() for more
83 * details on how this is computed.
85 * - When loading several libraries in service processes, a simple incremental
86 * approach from the original random base load address is used. This is
87 * sufficient to deal correctly with component builds (which can use dozens
88 * of shared libraries), while regular builds always embed a single shared
93 * Here's an explanation of how this class is supposed to be used:
95 * - Native shared libraries should be loaded with Linker.loadLibrary(),
96 * instead of System.loadLibrary(). The two functions take the same parameter
97 * and should behave the same (at a high level).
99 * - Before loading any library, prepareLibraryLoad() should be called.
101 * - After loading all libraries, finishLibraryLoad() should be called, before
102 * running any native code from any of the libraries (except their static
103 * constructors, which can't be avoided).
105 * - A service process shall call either initServiceProcess() or
106 * disableSharedRelros() early (i.e. before any loadLibrary() call).
107 * Otherwise, the linker considers that it is running inside the browser
108 * process. This is because various content-based projects have vastly
109 * different initialization paths.
111 * disableSharedRelros() completely disables shared RELROs, and loadLibrary()
112 * will behave exactly like System.loadLibrary().
114 * initServiceProcess(baseLoadAddress) indicates that shared RELROs are to be
115 * used in this process.
117 * - The browser is in charge of deciding where in memory each library should
118 * be loaded. This address must be passed to each service process (see
119 * LinkerParams.java for a helper class to do so).
121 * - The browser will also generate shared RELROs for each library it loads.
122 * More specifically, by default when in the browser process, the linker
125 * - Load libraries randomly (just like System.loadLibrary()).
126 * - Compute the fixed address to be used to load the same library
127 * in service processes.
128 * - Create a shared memory region populated with the RELRO region
129 * content pre-relocated for the specific fixed address above.
131 * Note that these shared RELRO regions cannot be used inside the browser
132 * process. They are also never mapped into it.
134 * This behaviour is altered by the BROWSER_SHARED_RELRO_CONFIG configuration
135 * variable below, which may force the browser to load the libraries at
136 * fixed addresses to.
138 * - Once all libraries are loaded in the browser process, one can call
139 * getSharedRelros() which returns a Bundle instance containing a map that
140 * links each loaded library to its shared RELRO region.
142 * This Bundle must be passed to each service process, for example through
143 * a Binder call (note that the Bundle includes file descriptors and cannot
144 * be added as an Intent extra).
146 * - In a service process, finishLibraryLoad() will block until the RELRO
147 * section Bundle is received. This is typically done by calling
148 * useSharedRelros() from another thread.
150 * This method also ensures the process uses the shared RELROs.
152 public class Linker {
154 // Log tag for this class. This must match the name of the linker's native library.
155 private static final String TAG = "content_android_linker";
157 // Set to true to enable debug logs.
158 private static final boolean DEBUG = false;
160 // Constants used to control the behaviour of the browser process with
161 // regards to the shared RELRO section.
162 // NEVER -> The browser never uses it itself.
163 // LOW_RAM_ONLY -> It is only used on devices with low RAM.
164 // ALWAYS -> It is always used.
165 // NOTE: These names are known and expected by the Linker test scripts.
166 public static final int BROWSER_SHARED_RELRO_CONFIG_NEVER = 0;
167 public static final int BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY = 1;
168 public static final int BROWSER_SHARED_RELRO_CONFIG_ALWAYS = 2;
170 // Configuration variable used to control how the browser process uses the
171 // shared RELRO. Only change this while debugging linker-related issues.
172 // NOTE: This variable's name is known and expected by the Linker test scripts.
173 public static final int BROWSER_SHARED_RELRO_CONFIG =
174 BROWSER_SHARED_RELRO_CONFIG_ALWAYS;
176 // Constants used to control the value of sMemoryDeviceConfig.
177 // INIT -> Value is undetermined (will check at runtime).
178 // LOW -> This is a low-memory device.
179 // NORMAL -> This is not a low-memory device.
180 public static final int MEMORY_DEVICE_CONFIG_INIT = 0;
181 public static final int MEMORY_DEVICE_CONFIG_LOW = 1;
182 public static final int MEMORY_DEVICE_CONFIG_NORMAL = 2;
184 // Indicates if this is a low-memory device or not. The default is to
185 // determine this by probing the system at runtime, but this can be forced
186 // for testing by calling setMemoryDeviceConfig().
187 private static int sMemoryDeviceConfig = MEMORY_DEVICE_CONFIG_INIT;
189 // Becomes true after linker initialization.
190 private static boolean sInitialized = false;
192 // Set to true to indicate that the system supports safe sharing of RELRO sections.
193 private static boolean sRelroSharingSupported = false;
195 // Set to true if this runs in the browser process. Disabled by initServiceProcess().
196 private static boolean sInBrowserProcess = true;
198 // Becomes true to indicate this process needs to wait for a shared RELRO in
199 // finishLibraryLoad().
200 private static boolean sWaitForSharedRelros = false;
202 // Becomes true when initialization determines that the browser process can use the
204 private static boolean sBrowserUsesSharedRelro = false;
206 // The map of all RELRO sections either created or used in this process.
207 private static Bundle sSharedRelros = null;
209 // Current common random base load address.
210 private static long sBaseLoadAddress = 0;
212 // Current fixed-location load address for the next library called by loadLibrary().
213 private static long sCurrentLoadAddress = 0;
215 // Becomes true if any library fails to load at a given, non-0, fixed address.
216 private static boolean sLoadAtFixedAddressFailed = false;
218 // Becomes true once prepareLibraryLoad() has been called.
219 private static boolean sPrepareLibraryLoadCalled = false;
221 // Used internally to initialize the linker's static data. Assume lock is held.
222 private static void ensureInitializedLocked() {
223 assert Thread.holdsLock(Linker.class);
226 sRelroSharingSupported = false;
227 if (NativeLibraries.USE_LINKER) {
228 if (DEBUG) Log.i(TAG, "Loading lib" + TAG + ".so");
230 System.loadLibrary(TAG);
231 } catch (UnsatisfiedLinkError e) {
232 // In a component build, the ".cr" suffix is added to each library name.
233 System.loadLibrary(TAG + ".cr");
235 sRelroSharingSupported = nativeCanUseSharedRelro();
236 if (!sRelroSharingSupported)
237 Log.w(TAG, "This system cannot safely share RELRO sections");
239 if (DEBUG) Log.i(TAG, "This system supports safe shared RELRO sections");
242 if (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT) {
243 sMemoryDeviceConfig = nativeIsLowMemoryDevice() ?
244 MEMORY_DEVICE_CONFIG_LOW : MEMORY_DEVICE_CONFIG_NORMAL;
247 switch (BROWSER_SHARED_RELRO_CONFIG) {
248 case BROWSER_SHARED_RELRO_CONFIG_NEVER:
249 sBrowserUsesSharedRelro = false;
251 case BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY:
252 sBrowserUsesSharedRelro =
253 (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW);
254 if (sBrowserUsesSharedRelro)
255 Log.w(TAG, "Low-memory device: shared RELROs used in all processes");
257 case BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
258 Log.w(TAG, "Beware: shared RELROs used in all processes!");
259 sBrowserUsesSharedRelro = true;
262 assert false : "Unreached";
266 if (DEBUG) Log.i(TAG, "Linker disabled");
269 if (!sRelroSharingSupported) {
271 sBrowserUsesSharedRelro = false;
272 sWaitForSharedRelros = false;
280 * A public interface used to run runtime linker tests after loading
281 * libraries. Should only be used to implement the linker unit tests,
282 * which is controlled by the value of NativeLibraries.ENABLE_LINKER_TESTS
283 * configured at build time.
285 public interface TestRunner {
287 * Run runtime checks and return true if they all pass.
288 * @param memoryDeviceConfig The current memory device configuration.
289 * @param inBrowserProcess true iff this is the browser process.
291 public boolean runChecks(int memoryDeviceConfig, boolean inBrowserProcess);
294 // The name of a class that implements TestRunner.
295 static String sTestRunnerClassName = null;
298 * Set the TestRunner by its class name. It will be instantiated at
299 * runtime after all libraries are loaded.
300 * @param testRunnerClassName null or a String for the class name of the
303 public static void setTestRunnerClassName(String testRunnerClassName) {
304 if (DEBUG) Log.i(TAG, "setTestRunnerByClassName(" + testRunnerClassName + ") called");
306 if (!NativeLibraries.ENABLE_LINKER_TESTS) {
307 // Ignore this in production code to prevent malvolent runtime injection.
311 synchronized (Linker.class) {
312 assert sTestRunnerClassName == null;
313 sTestRunnerClassName = testRunnerClassName;
318 * Call this to retrieve the name of the current TestRunner class name
319 * if any. This can be useful to pass it from the browser process to
321 * @return null or a String holding the name of the class implementing
322 * the TestRunner set by calling setTestRunnerClassName() previously.
324 public static String getTestRunnerClassName() {
325 synchronized (Linker.class) {
326 return sTestRunnerClassName;
331 * Call this method before any other Linker method to force a specific
332 * memory device configuration. Should only be used for testing.
333 * @param config either MEMORY_DEVICE_CONFIG_LOW or MEMORY_DEVICE_CONFIG_NORMAL.
335 public static void setMemoryDeviceConfig(int memoryDeviceConfig) {
336 if (DEBUG) Log.i(TAG, "setMemoryDeviceConfig(" + memoryDeviceConfig + ") called");
337 // Sanity check. This method should only be called during tests.
338 assert NativeLibraries.ENABLE_LINKER_TESTS;
339 synchronized (Linker.class) {
340 assert sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT;
341 assert memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW ||
342 memoryDeviceConfig == MEMORY_DEVICE_CONFIG_NORMAL;
344 if (memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW)
345 Log.i(TAG, "Simulating a low-memory device");
347 Log.i(TAG, "Simulating a regular-memory device");
349 sMemoryDeviceConfig = memoryDeviceConfig;
354 * Call this method to determine if this content-based project must
355 * use this linker. If not, System.loadLibrary() should be used to load
358 public static boolean isUsed() {
359 // Only GYP targets that are APKs and have the 'use_content_linker' variable
360 // defined as 1 will use this linker. For all others (the default), the
361 // auto-generated NativeLibraries.USE_LINKER variable will be false.
362 if (!NativeLibraries.USE_LINKER)
365 synchronized (Linker.class) {
366 ensureInitializedLocked();
367 // At the moment, there is also no point in using this linker if the
368 // system does not support RELRO sharing safely.
369 return sRelroSharingSupported;
374 * Call this method just before loading any native shared libraries in this process.
376 public static void prepareLibraryLoad() {
377 if (DEBUG) Log.i(TAG, "prepareLibraryLoad() called");
378 synchronized (Linker.class) {
379 sPrepareLibraryLoadCalled = true;
381 if (sInBrowserProcess) {
382 // Force generation of random base load address, as well
383 // as creation of shared RELRO sections in this process.
384 setupBaseLoadAddressLocked();
390 * Call this method just after loading all native shared libraries in this process.
391 * Note that when in a service process, this will block until the RELRO bundle is
392 * received, i.e. when another thread calls useSharedRelros().
394 public static void finishLibraryLoad() {
395 if (DEBUG) Log.i(TAG, "finishLibraryLoad() called");
396 synchronized (Linker.class) {
397 if (DEBUG) Log.i(TAG, String.format(
398 "sInBrowserProcess=%s sBrowserUsesSharedRelro=%s sWaitForSharedRelros=%s",
399 sInBrowserProcess ? "true" : "false",
400 sBrowserUsesSharedRelro ? "true" : "false",
401 sWaitForSharedRelros ? "true" : "false"));
403 if (sLoadedLibraries == null) {
404 if (DEBUG) Log.i(TAG, "No libraries loaded");
406 if (sInBrowserProcess) {
407 // Create new Bundle containing RELRO section information
408 // for all loaded libraries. Make it available to getSharedRelros().
409 sSharedRelros = createBundleFromLibInfoMap(sLoadedLibraries);
411 Log.i(TAG, "Shared RELRO created");
412 dumpBundle(sSharedRelros);
415 if (sBrowserUsesSharedRelro) {
416 useSharedRelrosLocked(sSharedRelros);
420 if (sWaitForSharedRelros) {
421 assert !sInBrowserProcess;
423 // Wait until the shared relro bundle is received from useSharedRelros().
424 while (sSharedRelros == null) {
427 } catch (InterruptedException ie) {
430 useSharedRelrosLocked(sSharedRelros);
431 // Clear the Bundle to ensure its file descriptor references can't be reused.
432 sSharedRelros.clear();
433 sSharedRelros = null;
437 if (NativeLibraries.ENABLE_LINKER_TESTS && sTestRunnerClassName != null) {
438 // The TestRunner implementation must be instantiated _after_
439 // all libraries are loaded to ensure that its native methods
440 // are properly registered.
441 if (DEBUG) Log.i(TAG, "Instantiating " + sTestRunnerClassName);
442 TestRunner testRunner = null;
444 testRunner = (TestRunner)
445 Class.forName(sTestRunnerClassName).newInstance();
446 } catch (Exception e) {
447 Log.e(TAG, "Could not extract test runner class name", e);
450 if (testRunner != null) {
451 if (!testRunner.runChecks(sMemoryDeviceConfig, sInBrowserProcess)) {
452 Log.wtf(TAG, "Linker runtime tests failed in this process!!");
455 Log.i(TAG, "All linker tests passed!");
460 if (DEBUG) Log.i(TAG, "finishLibraryLoad() exiting");
464 * Call this to send a Bundle containing the shared RELRO sections to be
465 * used in this process. If initServiceProcess() was previously called,
466 * finishLibraryLoad() will not exit until this method is called in another
467 * thread with a non-null value.
468 * @param bundle The Bundle instance containing a map of shared RELRO sections
469 * to use in this process.
471 public static void useSharedRelros(Bundle bundle) {
472 // Ensure the bundle uses the application's class loader, not the framework
473 // one which doesn't know anything about LibInfo.
475 bundle.setClassLoader(LibInfo.class.getClassLoader());
477 if (DEBUG) Log.i(TAG, "useSharedRelros() called with " + bundle);
479 synchronized (Linker.class) {
480 // Note that in certain cases, this can be called before
481 // initServiceProcess() in service processes.
482 sSharedRelros = bundle;
483 // Tell any listener blocked in finishLibraryLoad() about it.
484 Linker.class.notifyAll();
489 * Call this to retrieve the shared RELRO sections created in this process,
490 * after loading all libraries.
491 * @return a new Bundle instance, or null if RELRO sharing is disabled on
492 * this system, or if initServiceProcess() was called previously.
494 public static Bundle getSharedRelros() {
495 if (DEBUG) Log.i(TAG, "getSharedRelros() called");
496 synchronized (Linker.class) {
497 if (!sInBrowserProcess) {
498 if (DEBUG) Log.i(TAG, "... returning null Bundle");
502 // Return the Bundle created in finishLibraryLoad().
503 if (DEBUG) Log.i(TAG, "... returning " + sSharedRelros);
504 return sSharedRelros;
510 * Call this method before loading any libraries to indicate that this
511 * process shall neither create or reuse shared RELRO sections.
513 public static void disableSharedRelros() {
514 if (DEBUG) Log.i(TAG, "disableSharedRelros() called");
515 synchronized (Linker.class) {
516 sInBrowserProcess = false;
517 sWaitForSharedRelros = false;
518 sBrowserUsesSharedRelro = false;
523 * Call this method before loading any libraries to indicate that this
524 * process is ready to reuse shared RELRO sections from another one.
525 * Typically used when starting service processes.
526 * @param baseLoadAddress the base library load address to use.
528 public static void initServiceProcess(long baseLoadAddress) {
529 if (DEBUG) Log.i(TAG, String.format("initServiceProcess(0x%x) called", baseLoadAddress));
530 synchronized (Linker.class) {
531 ensureInitializedLocked();
532 sInBrowserProcess = false;
533 sBrowserUsesSharedRelro = false;
534 if (sRelroSharingSupported) {
535 sWaitForSharedRelros = true;
536 sBaseLoadAddress = baseLoadAddress;
537 sCurrentLoadAddress = baseLoadAddress;
543 * Retrieve the base load address of all shared RELRO sections.
544 * This also enforces the creation of shared RELRO sections in
545 * prepareLibraryLoad(), which can later be retrieved with getSharedRelros().
546 * @return a common, random base load address, or 0 if RELRO sharing is
549 public static long getBaseLoadAddress() {
550 synchronized (Linker.class) {
551 ensureInitializedLocked();
552 if (!sInBrowserProcess) {
553 Log.w(TAG, "Shared RELRO sections are disabled in this process!");
557 setupBaseLoadAddressLocked();
558 if (DEBUG) Log.i(TAG, String.format("getBaseLoadAddress() returns 0x%x",
560 return sBaseLoadAddress;
564 // Used internally to lazily setup the common random base load address.
565 private static void setupBaseLoadAddressLocked() {
566 assert Thread.holdsLock(Linker.class);
567 if (sBaseLoadAddress == 0) {
568 long address = computeRandomBaseLoadAddress();
569 sBaseLoadAddress = address;
570 sCurrentLoadAddress = address;
572 // If the computed address is 0, there are issues with the
573 // entropy source, so disable RELRO shared / fixed load addresses.
574 Log.w(TAG, "Disabling shared RELROs due to bad entropy sources");
575 sBrowserUsesSharedRelro = false;
576 sWaitForSharedRelros = false;
583 * Compute a random base load address where to place loaded libraries.
584 * @return new base load address, or 0 if the system does not support
587 private static long computeRandomBaseLoadAddress() {
588 // The kernel ASLR feature will place randomized mappings starting
589 // from this address. Never try to load anything above this
590 // explicitly to avoid random conflicts.
591 final long baseAddressLimit = 0x40000000;
593 // Start loading libraries from this base address.
594 final long baseAddress = 0x20000000;
596 // Maximum randomized base address value. Used to ensure a margin
597 // of 192 MB below baseAddressLimit.
598 final long baseAddressMax = baseAddressLimit - 192 * 1024 * 1024;
600 // The maximum limit of the desired random offset.
601 final long pageSize = nativeGetPageSize();
602 final int offsetLimit = (int)((baseAddressMax - baseAddress) / pageSize);
604 // Get the greatest power of 2 that is smaller or equal to offsetLimit.
606 for (; numBits > 1; numBits--) {
607 if ((1 << numBits) <= offsetLimit)
612 final int maxValue = (1 << numBits) - 1;
613 Log.i(TAG, String.format("offsetLimit=%d numBits=%d maxValue=%d (0x%x)",
614 offsetLimit, numBits, maxValue, maxValue));
617 // Find a random offset between 0 and (2^numBits - 1), included.
618 int offset = getRandomBits(numBits);
621 address = baseAddress + offset * pageSize;
625 String.format("Linker.computeRandomBaseLoadAddress() return 0x%x",
632 * Return a cryptographically-strong random number of numBits bits.
633 * @param numBits The number of bits in the result. Must be in 1..31 range.
634 * @return A random integer between 0 and (2^numBits - 1), inclusive, or -1
635 * in case of error (e.g. if /dev/urandom can't be opened or read).
637 private static int getRandomBits(int numBits) {
642 FileInputStream input;
644 // A naive implementation would read a 32-bit integer then use modulo, but
645 // this introduces a slight bias. Instead, read 32-bit integers from the
646 // entropy source until the value is positive but smaller than maxLimit.
647 input = new FileInputStream(new File("/dev/urandom"));
648 } catch (Exception e) {
649 Log.e(TAG, "Could not open /dev/urandom", e);
655 for (int n = 0; n < 4; n++)
656 result = (result << 8) | (input.read() & 255);
657 } catch (Exception e) {
658 Log.e(TAG, "Could not read /dev/urandom", e);
663 } catch (Exception e) {
664 // Can't really do anything here.
667 result &= (1 << numBits) - 1;
670 Log.i(TAG, String.format(
671 "getRandomBits(%d) returned %d", numBits, result));
677 // Used for debugging only.
678 private static void dumpBundle(Bundle bundle) {
679 if (DEBUG) Log.i(TAG, "Bundle has " + bundle.size() + " items: " + bundle);
683 * Use the shared RELRO section from a Bundle received form another process.
684 * Call this after calling setBaseLoadAddress() then loading all libraries
685 * with loadLibrary().
686 * @param a Bundle instance generated with createSharedRelroBundle() in
689 private static void useSharedRelrosLocked(Bundle bundle) {
690 assert Thread.holdsLock(Linker.class);
692 if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() called");
694 if (bundle == null) {
695 if (DEBUG) Log.i(TAG, "null bundle!");
699 if (!sRelroSharingSupported) {
700 if (DEBUG) Log.i(TAG, "System does not support RELRO sharing");
704 if (sLoadedLibraries == null) {
705 if (DEBUG) Log.i(TAG, "No libraries loaded!");
709 if (DEBUG) dumpBundle(bundle);
710 HashMap<String, LibInfo> relroMap = createLibInfoMapFromBundle(bundle);
712 // Apply the RELRO section to all libraries that were already loaded.
713 for (Map.Entry<String, LibInfo> entry : relroMap.entrySet()) {
714 String libName = entry.getKey();
715 LibInfo libInfo = entry.getValue();
716 if (!nativeUseSharedRelro(libName, libInfo)) {
717 Log.w(TAG, "Could not use shared RELRO section for " + libName);
719 if (DEBUG) Log.i(TAG, "Using shared RELRO section for " + libName);
723 // In service processes, close all file descriptors from the map now.
724 if (!sInBrowserProcess)
725 closeLibInfoMap(relroMap);
727 if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() exiting");
731 * Returns whether the linker was unable to load one library at a given fixed address.
733 * @return true if at least one library was not loaded at the expected fixed address.
735 public static boolean loadAtFixedAddressFailed() {
736 return sLoadAtFixedAddressFailed;
740 * Load a native shared library with the Chromium linker.
741 * If neither initSharedRelro() or readFromBundle() were called
742 * previously, this uses the standard linker (i.e. System.loadLibrary()).
744 * @param library The library's base name.
745 * @throws UnsatisfiedLinkError if the library does not exist.
747 public static void loadLibrary(String library) {
748 if (DEBUG) Log.i(TAG, "loadLibrary: " + library);
750 // Don't self-load the linker. This is because the build system is
751 // not clever enough to understand that all the libraries packaged
752 // in the final .apk don't need to be explicitly loaded.
753 // Also deal with the component build that adds a .cr suffix to the name.
754 if (library.equals(TAG) || library.equals(TAG + ".cr")) {
755 if (DEBUG) Log.i(TAG, "ignoring self-linker load");
759 synchronized (Linker.class) {
760 ensureInitializedLocked();
762 // Security: Ensure prepareLibraryLoad() was called before.
763 // In theory, this can be done lazily here, but it's more consistent
764 // to use a pair of functions (i.e. prepareLibraryLoad() + finishLibraryLoad())
765 // that wrap all calls to loadLibrary() in the library loader.
766 assert sPrepareLibraryLoadCalled;
768 String libName = System.mapLibraryName(library);
770 if (sLoadedLibraries == null)
771 sLoadedLibraries = new HashMap<String, LibInfo>();
773 if (sLoadedLibraries.containsKey(libName)) {
774 if (DEBUG) Log.i(TAG, "Not loading " + libName + " twice");
778 LibInfo libInfo = new LibInfo();
779 LibInfo relroLibInfo = null;
780 long loadAddress = 0;
781 if ((sInBrowserProcess && sBrowserUsesSharedRelro) || sWaitForSharedRelros) {
782 // Load the library at a fixed address.
783 loadAddress = sCurrentLoadAddress;
786 if (!nativeLoadLibrary(libName, loadAddress, libInfo)) {
787 String errorMessage = "Unable to load library: " + libName;
788 Log.e(TAG, errorMessage);
789 throw new UnsatisfiedLinkError(errorMessage);
791 // Keep track whether the library has been loaded at the expected load address.
792 if (loadAddress != 0 && loadAddress != libInfo.mLoadAddress)
793 sLoadAtFixedAddressFailed = true;
795 // Print the load address to the logcat when testing the linker. The format
796 // of the string is expected by the Python test_runner script as one of:
797 // BROWSER_LIBRARY_ADDRESS: <library-name> <address>
798 // RENDERER_LIBRARY_ADDRESS: <library-name> <address>
799 // Where <library-name> is the library name, and <address> is the hexadecimal load
801 if (NativeLibraries.ENABLE_LINKER_TESTS) {
802 Log.i(TAG, String.format(
803 "%s_LIBRARY_ADDRESS: %s %x",
804 sInBrowserProcess ? "BROWSER" : "RENDERER",
806 libInfo.mLoadAddress));
809 if (sInBrowserProcess) {
810 // Create a new shared RELRO section at the 'current' fixed load address.
811 if (!nativeCreateSharedRelro(libName, sCurrentLoadAddress, libInfo)) {
814 "Could not create shared RELRO for %s at %x",
815 libName, sCurrentLoadAddress));
817 if (DEBUG) Log.i(TAG,
819 "Created shared RELRO for %s at %x: %s",
822 libInfo.toString()));
826 if (sCurrentLoadAddress != 0) {
827 // Compute the next current load address. If sBaseLoadAddress
828 // is not 0, this is an explicit library load address. Otherwise,
829 // this is an explicit load address for relocated RELRO sections
831 sCurrentLoadAddress = libInfo.mLoadAddress + libInfo.mLoadSize;
834 sLoadedLibraries.put(libName, libInfo);
835 if (DEBUG) Log.i(TAG, "Library details " + libInfo.toString());
840 * Native method used to load a library.
841 * @param library Platform specific library name (e.g. libfoo.so)
842 * @param loadAddress Explicit load address, or 0 for randomized one.
843 * @param relro_info If not null, the mLoadAddress and mLoadSize fields
844 * of this LibInfo instance will set on success.
845 * @return true for success, false otherwise.
847 private static native boolean nativeLoadLibrary(String library,
852 * Native method used to create a shared RELRO section.
853 * If the library was already loaded at the same address using
854 * nativeLoadLibrary(), this creates the RELRO for it. Otherwise,
855 * this loads a new temporary library at the specified address,
856 * creates and extracts the RELRO section from it, then unloads it.
857 * @param library Library name.
858 * @param loadAddress load address, which can be different from the one
859 * used to load the library in the current process!
860 * @param LibInfo libInfo instance. On success, the mRelroStart, mRelroSize
861 * and mRelroFd will be set.
862 * @return true on success, false otherwise.
864 private static native boolean nativeCreateSharedRelro(String library,
869 * Native method used to use a shared RELRO section.
870 * @param library Library name.
871 * @param libInfo A LibInfo instance containing valid RELRO information
872 * @return true on success.
874 private static native boolean nativeUseSharedRelro(String library,
878 * Checks that the system supports shared RELROs. Old Android kernels
879 * have a bug in the way they check Ashmem region protection flags, which
880 * makes using shared RELROs unsafe. This method performs a simple runtime
881 * check for this misfeature, even though nativeEnableSharedRelro() will
882 * always fail if this returns false.
884 private static native boolean nativeCanUseSharedRelro();
886 // Returns the native page size in bytes.
887 private static native long nativeGetPageSize();
889 // Checks whether this is a low-memory device.
890 private static native boolean nativeIsLowMemoryDevice();
893 * Record information for a given library.
894 * IMPORTANT: Native code knows about this class's fields, so
895 * don't change them without modifying the corresponding C++ sources.
896 * Also, the LibInfo instance owns the ashmem file descriptor.
898 public static class LibInfo implements Parcelable {
908 public void close() {
911 ParcelFileDescriptor.adoptFd(mRelroFd).close();
912 } catch (java.io.IOException e) {
919 public LibInfo(Parcel in) {
920 mLoadAddress = in.readLong();
921 mLoadSize = in.readLong();
922 mRelroStart = in.readLong();
923 mRelroSize = in.readLong();
924 ParcelFileDescriptor fd = in.readFileDescriptor();
925 mRelroFd = fd.detachFd();
930 public void writeToParcel(Parcel out, int flags) {
932 out.writeLong(mLoadAddress);
933 out.writeLong(mLoadSize);
934 out.writeLong(mRelroStart);
935 out.writeLong(mRelroSize);
937 ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd);
938 fd.writeToParcel(out, 0);
940 } catch (java.io.IOException e) {
941 Log.e(TAG, "Cant' write LibInfo file descriptor to parcel", e);
948 public int describeContents() {
949 return Parcelable.CONTENTS_FILE_DESCRIPTOR;
953 public static final Parcelable.Creator<LibInfo> CREATOR
954 = new Parcelable.Creator<LibInfo>() {
955 public LibInfo createFromParcel(Parcel in) {
956 return new LibInfo(in);
959 public LibInfo[] newArray(int size) {
960 return new LibInfo[size];
964 public String toString() {
965 return String.format("[load=0x%x-0x%x relro=0x%x-0x%x fd=%d]",
967 mLoadAddress + mLoadSize,
969 mRelroStart + mRelroSize,
973 // IMPORTANT: Don't change these fields without modifying the
974 // native code that accesses them directly!
975 public long mLoadAddress; // page-aligned library load address.
976 public long mLoadSize; // page-aligned library load size.
977 public long mRelroStart; // page-aligned address in memory, or 0 if none.
978 public long mRelroSize; // page-aligned size in memory, or 0.
979 public int mRelroFd; // ashmem file descriptor, or -1
982 // Create a Bundle from a map of LibInfo objects.
983 private static Bundle createBundleFromLibInfoMap(HashMap<String, LibInfo> map) {
984 Bundle bundle = new Bundle(map.size());
985 for (Map.Entry<String, LibInfo> entry : map.entrySet())
986 bundle.putParcelable(entry.getKey(), entry.getValue());
991 // Create a new LibInfo map from a Bundle.
992 private static HashMap<String, LibInfo> createLibInfoMapFromBundle(Bundle bundle) {
993 HashMap<String, LibInfo> map = new HashMap<String, LibInfo>();
994 for (String library : bundle.keySet()) {
995 LibInfo libInfo = bundle.getParcelable(library);
996 map.put(library, libInfo);
1001 // Call the close() method on all values of a LibInfo map.
1002 private static void closeLibInfoMap(HashMap<String, LibInfo> map) {
1003 for (Map.Entry<String, LibInfo> entry : map.entrySet())
1004 entry.getValue().close();
1007 // The map of libraries that are currently loaded in this process.
1008 private static HashMap<String, LibInfo> sLoadedLibraries = null;
1010 // Used to pass the shared RELRO Bundle through Binder.
1011 public static final String EXTRA_LINKER_SHARED_RELROS =
1012 "org.chromium.content.common.linker.shared_relros";