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 package org.chromium.base.library_loader;
7 import android.os.Bundle;
8 import android.os.Parcel;
9 import android.os.ParcelFileDescriptor;
10 import android.os.Parcelable;
11 import android.util.Log;
13 import org.chromium.base.SysUtils;
14 import org.chromium.base.ThreadUtils;
17 import java.io.FileInputStream;
18 import java.util.HashMap;
19 import java.util.Locale;
22 import javax.annotation.Nullable;
27 * The point of this class is to provide an alternative to System.loadLibrary()
28 * to load native shared libraries. One specific feature that it supports is the
29 * ability to save RAM by sharing the ELF RELRO sections between renderer
32 * When two processes load the same native library at the _same_ memory address,
33 * the content of their RELRO section (which includes C++ vtables or any
34 * constants that contain pointers) will be largely identical [1].
36 * By default, the RELRO section is backed by private RAM in each process,
37 * which is still significant on mobile (e.g. 1.28 MB / process on Chrome 30 for
40 * However, it is possible to save RAM by creating a shared memory region,
41 * copy the RELRO content into it, then have each process swap its private,
42 * regular RELRO, with a shared, read-only, mapping of the shared one.
44 * This trick saves 98% of the RELRO section size per extra process, after the
45 * first one. On the other hand, this requires careful communication between
46 * the process where the shared RELRO is created and the one(s) where it is used.
48 * Note that swapping the regular RELRO with the shared one is not an atomic
49 * operation. Care must be taken that no other thread tries to run native code
50 * that accesses it during it. In practice, this means the swap must happen
51 * before library native code is executed.
53 * [1] The exceptions are pointers to external, randomized, symbols, like
54 * those from some system libraries, but these are very few in practice.
58 * Security considerations:
60 * - Whether the browser process loads its native libraries at the same
61 * addresses as the service ones (to save RAM by sharing the RELRO too)
62 * depends on the configuration variable BROWSER_SHARED_RELRO_CONFIG below.
64 * Not using fixed library addresses in the browser process is preferred
65 * for regular devices since it maintains the efficacy of ASLR as an
66 * exploit mitigation across the render <-> browser privilege boundary.
68 * - The shared RELRO memory region is always forced read-only after creation,
69 * which means it is impossible for a compromised service process to map
70 * it read-write (e.g. by calling mmap() or mprotect()) and modify its
71 * content, altering values seen in other service processes.
73 * - Unfortunately, certain Android systems use an old, buggy kernel, that
74 * doesn't check Ashmem region permissions correctly. See CVE-2011-1149
75 * for details. This linker probes the system on startup and will completely
76 * disable shared RELROs if it detects the problem. For the record, this is
77 * common for Android emulator system images (which are still based on 2.6.29)
79 * - Once the RELRO ashmem region is mapped into a service process' address
80 * space, the corresponding file descriptor is immediately closed. The
81 * file descriptor is kept opened in the browser process, because a copy needs
82 * to be sent to each new potential service process.
84 * - The common library load addresses are randomized for each instance of
85 * the program on the device. See computeRandomBaseLoadAddress() for more
86 * details on how this is computed.
88 * - When loading several libraries in service processes, a simple incremental
89 * approach from the original random base load address is used. This is
90 * sufficient to deal correctly with component builds (which can use dozens
91 * of shared libraries), while regular builds always embed a single shared
96 * Here's an explanation of how this class is supposed to be used:
98 * - Native shared libraries should be loaded with Linker.loadLibrary(),
99 * instead of System.loadLibrary(). The two functions take the same parameter
100 * and should behave the same (at a high level).
102 * - Before loading any library, prepareLibraryLoad() should be called.
104 * - After loading all libraries, finishLibraryLoad() should be called, before
105 * running any native code from any of the libraries (except their static
106 * constructors, which can't be avoided).
108 * - A service process shall call either initServiceProcess() or
109 * disableSharedRelros() early (i.e. before any loadLibrary() call).
110 * Otherwise, the linker considers that it is running inside the browser
111 * process. This is because various Chromium projects have vastly
112 * different initialization paths.
114 * disableSharedRelros() completely disables shared RELROs, and loadLibrary()
115 * will behave exactly like System.loadLibrary().
117 * initServiceProcess(baseLoadAddress) indicates that shared RELROs are to be
118 * used in this process.
120 * - The browser is in charge of deciding where in memory each library should
121 * be loaded. This address must be passed to each service process (see
122 * ChromiumLinkerParams.java in content for a helper class to do so).
124 * - The browser will also generate shared RELROs for each library it loads.
125 * More specifically, by default when in the browser process, the linker
128 * - Load libraries randomly (just like System.loadLibrary()).
129 * - Compute the fixed address to be used to load the same library
130 * in service processes.
131 * - Create a shared memory region populated with the RELRO region
132 * content pre-relocated for the specific fixed address above.
134 * Note that these shared RELRO regions cannot be used inside the browser
135 * process. They are also never mapped into it.
137 * This behaviour is altered by the BROWSER_SHARED_RELRO_CONFIG configuration
138 * variable below, which may force the browser to load the libraries at
139 * fixed addresses to.
141 * - Once all libraries are loaded in the browser process, one can call
142 * getSharedRelros() which returns a Bundle instance containing a map that
143 * links each loaded library to its shared RELRO region.
145 * This Bundle must be passed to each service process, for example through
146 * a Binder call (note that the Bundle includes file descriptors and cannot
147 * be added as an Intent extra).
149 * - In a service process, finishLibraryLoad() will block until the RELRO
150 * section Bundle is received. This is typically done by calling
151 * useSharedRelros() from another thread.
153 * This method also ensures the process uses the shared RELROs.
155 public class Linker {
157 // Log tag for this class. This must match the name of the linker's native library.
158 private static final String TAG = "chromium_android_linker";
160 // Set to true to enable debug logs.
161 private static final boolean DEBUG = false;
163 // Constants used to control the behaviour of the browser process with
164 // regards to the shared RELRO section.
165 // NEVER -> The browser never uses it itself.
166 // LOW_RAM_ONLY -> It is only used on devices with low RAM.
167 // ALWAYS -> It is always used.
168 // NOTE: These names are known and expected by the Linker test scripts.
169 public static final int BROWSER_SHARED_RELRO_CONFIG_NEVER = 0;
170 public static final int BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY = 1;
171 public static final int BROWSER_SHARED_RELRO_CONFIG_ALWAYS = 2;
173 // Configuration variable used to control how the browser process uses the
174 // shared RELRO. Only change this while debugging linker-related issues.
175 // NOTE: This variable's name is known and expected by the Linker test scripts.
176 public static final int BROWSER_SHARED_RELRO_CONFIG =
177 BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY;
179 // Constants used to control the value of sMemoryDeviceConfig.
180 // INIT -> Value is undetermined (will check at runtime).
181 // LOW -> This is a low-memory device.
182 // NORMAL -> This is not a low-memory device.
183 public static final int MEMORY_DEVICE_CONFIG_INIT = 0;
184 public static final int MEMORY_DEVICE_CONFIG_LOW = 1;
185 public static final int MEMORY_DEVICE_CONFIG_NORMAL = 2;
187 // Indicates if this is a low-memory device or not. The default is to
188 // determine this by probing the system at runtime, but this can be forced
189 // for testing by calling setMemoryDeviceConfig().
190 private static int sMemoryDeviceConfig = MEMORY_DEVICE_CONFIG_INIT;
192 // Becomes true after linker initialization.
193 private static boolean sInitialized = false;
195 // Set to true to indicate that the system supports safe sharing of RELRO sections.
196 private static boolean sRelroSharingSupported = false;
198 // Set to true if this runs in the browser process. Disabled by initServiceProcess().
199 private static boolean sInBrowserProcess = true;
201 // Becomes true to indicate this process needs to wait for a shared RELRO in
202 // finishLibraryLoad().
203 private static boolean sWaitForSharedRelros = false;
205 // Becomes true when initialization determines that the browser process can use the
207 private static boolean sBrowserUsesSharedRelro = false;
209 // The map of all RELRO sections either created or used in this process.
210 private static Bundle sSharedRelros = null;
212 // Current common random base load address.
213 private static long sBaseLoadAddress = 0;
215 // Current fixed-location load address for the next library called by loadLibrary().
216 private static long sCurrentLoadAddress = 0;
218 // Becomes true if any library fails to load at a given, non-0, fixed address.
219 private static boolean sLoadAtFixedAddressFailed = false;
221 // Becomes true once prepareLibraryLoad() has been called.
222 private static boolean sPrepareLibraryLoadCalled = false;
224 // Used internally to initialize the linker's static data. Assume lock is held.
225 private static void ensureInitializedLocked() {
226 assert Thread.holdsLock(Linker.class);
229 sRelroSharingSupported = false;
230 if (NativeLibraries.USE_LINKER) {
231 if (DEBUG) Log.i(TAG, "Loading lib" + TAG + ".so");
233 System.loadLibrary(TAG);
234 } catch (UnsatisfiedLinkError e) {
235 // In a component build, the ".cr" suffix is added to each library name.
236 System.loadLibrary(TAG + ".cr");
238 sRelroSharingSupported = nativeCanUseSharedRelro();
239 if (!sRelroSharingSupported)
240 Log.w(TAG, "This system cannot safely share RELRO sections");
242 if (DEBUG) Log.i(TAG, "This system supports safe shared RELRO sections");
245 if (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT) {
246 sMemoryDeviceConfig = SysUtils.isLowEndDevice() ?
247 MEMORY_DEVICE_CONFIG_LOW : MEMORY_DEVICE_CONFIG_NORMAL;
250 switch (BROWSER_SHARED_RELRO_CONFIG) {
251 case BROWSER_SHARED_RELRO_CONFIG_NEVER:
252 sBrowserUsesSharedRelro = false;
254 case BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY:
255 sBrowserUsesSharedRelro =
256 (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW);
257 if (sBrowserUsesSharedRelro)
258 Log.w(TAG, "Low-memory device: shared RELROs used in all processes");
260 case BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
261 Log.w(TAG, "Beware: shared RELROs used in all processes!");
262 sBrowserUsesSharedRelro = true;
265 assert false : "Unreached";
269 if (DEBUG) Log.i(TAG, "Linker disabled");
272 if (!sRelroSharingSupported) {
274 sBrowserUsesSharedRelro = false;
275 sWaitForSharedRelros = false;
283 * A public interface used to run runtime linker tests after loading
284 * libraries. Should only be used to implement the linker unit tests,
285 * which is controlled by the value of NativeLibraries.ENABLE_LINKER_TESTS
286 * configured at build time.
288 public interface TestRunner {
290 * Run runtime checks and return true if they all pass.
291 * @param memoryDeviceConfig The current memory device configuration.
292 * @param inBrowserProcess true iff this is the browser process.
294 public boolean runChecks(int memoryDeviceConfig, boolean inBrowserProcess);
297 // The name of a class that implements TestRunner.
298 static String sTestRunnerClassName = null;
301 * Set the TestRunner by its class name. It will be instantiated at
302 * runtime after all libraries are loaded.
303 * @param testRunnerClassName null or a String for the class name of the
306 public static void setTestRunnerClassName(String testRunnerClassName) {
307 if (DEBUG) Log.i(TAG, "setTestRunnerByClassName(" + testRunnerClassName + ") called");
309 if (!NativeLibraries.ENABLE_LINKER_TESTS) {
310 // Ignore this in production code to prevent malvolent runtime injection.
314 synchronized (Linker.class) {
315 assert sTestRunnerClassName == null;
316 sTestRunnerClassName = testRunnerClassName;
321 * Call this to retrieve the name of the current TestRunner class name
322 * if any. This can be useful to pass it from the browser process to
324 * @return null or a String holding the name of the class implementing
325 * the TestRunner set by calling setTestRunnerClassName() previously.
327 public static String getTestRunnerClassName() {
328 synchronized (Linker.class) {
329 return sTestRunnerClassName;
334 * Call this method before any other Linker method to force a specific
335 * memory device configuration. Should only be used for testing.
336 * @param memoryDeviceConfig either MEMORY_DEVICE_CONFIG_LOW or MEMORY_DEVICE_CONFIG_NORMAL.
338 public static void setMemoryDeviceConfig(int memoryDeviceConfig) {
339 if (DEBUG) Log.i(TAG, "setMemoryDeviceConfig(" + memoryDeviceConfig + ") called");
340 // Sanity check. This method should only be called during tests.
341 assert NativeLibraries.ENABLE_LINKER_TESTS;
342 synchronized (Linker.class) {
343 assert sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT;
344 assert memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW ||
345 memoryDeviceConfig == MEMORY_DEVICE_CONFIG_NORMAL;
347 if (memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW)
348 Log.i(TAG, "Simulating a low-memory device");
350 Log.i(TAG, "Simulating a regular-memory device");
352 sMemoryDeviceConfig = memoryDeviceConfig;
357 * Call this method to determine if this chromium project must
358 * use this linker. If not, System.loadLibrary() should be used to load
361 public static boolean isUsed() {
362 // Only GYP targets that are APKs and have the 'use_chromium_linker' variable
363 // defined as 1 will use this linker. For all others (the default), the
364 // auto-generated NativeLibraries.USE_LINKER variable will be false.
365 if (!NativeLibraries.USE_LINKER)
368 synchronized (Linker.class) {
369 ensureInitializedLocked();
370 // At the moment, there is also no point in using this linker if the
371 // system does not support RELRO sharing safely.
372 return sRelroSharingSupported;
377 * Call this method to determine if the chromium project must load
378 * the library directly from the zip file.
380 public static boolean isInZipFile() {
381 return NativeLibraries.USE_LIBRARY_IN_ZIP_FILE;
385 * Call this method just before loading any native shared libraries in this process.
387 public static void prepareLibraryLoad() {
388 if (DEBUG) Log.i(TAG, "prepareLibraryLoad() called");
389 synchronized (Linker.class) {
390 sPrepareLibraryLoadCalled = true;
392 if (sInBrowserProcess) {
393 // Force generation of random base load address, as well
394 // as creation of shared RELRO sections in this process.
395 setupBaseLoadAddressLocked();
401 * Call this method just after loading all native shared libraries in this process.
402 * Note that when in a service process, this will block until the RELRO bundle is
403 * received, i.e. when another thread calls useSharedRelros().
405 public static void finishLibraryLoad() {
406 if (DEBUG) Log.i(TAG, "finishLibraryLoad() called");
407 synchronized (Linker.class) {
408 if (DEBUG) Log.i(TAG, String.format(
410 "sInBrowserProcess=%s sBrowserUsesSharedRelro=%s sWaitForSharedRelros=%s",
411 sInBrowserProcess ? "true" : "false",
412 sBrowserUsesSharedRelro ? "true" : "false",
413 sWaitForSharedRelros ? "true" : "false"));
415 if (sLoadedLibraries == null) {
416 if (DEBUG) Log.i(TAG, "No libraries loaded");
418 if (sInBrowserProcess) {
419 // Create new Bundle containing RELRO section information
420 // for all loaded libraries. Make it available to getSharedRelros().
421 sSharedRelros = createBundleFromLibInfoMap(sLoadedLibraries);
423 Log.i(TAG, "Shared RELRO created");
424 dumpBundle(sSharedRelros);
427 if (sBrowserUsesSharedRelro) {
428 useSharedRelrosLocked(sSharedRelros);
432 if (sWaitForSharedRelros) {
433 assert !sInBrowserProcess;
435 // Wait until the shared relro bundle is received from useSharedRelros().
436 while (sSharedRelros == null) {
439 } catch (InterruptedException ie) {
443 useSharedRelrosLocked(sSharedRelros);
444 // Clear the Bundle to ensure its file descriptor references can't be reused.
445 sSharedRelros.clear();
446 sSharedRelros = null;
450 if (NativeLibraries.ENABLE_LINKER_TESTS && sTestRunnerClassName != null) {
451 // The TestRunner implementation must be instantiated _after_
452 // all libraries are loaded to ensure that its native methods
453 // are properly registered.
454 if (DEBUG) Log.i(TAG, "Instantiating " + sTestRunnerClassName);
455 TestRunner testRunner = null;
457 testRunner = (TestRunner)
458 Class.forName(sTestRunnerClassName).newInstance();
459 } catch (Exception e) {
460 Log.e(TAG, "Could not extract test runner class name", e);
463 if (testRunner != null) {
464 if (!testRunner.runChecks(sMemoryDeviceConfig, sInBrowserProcess)) {
465 Log.wtf(TAG, "Linker runtime tests failed in this process!!");
468 Log.i(TAG, "All linker tests passed!");
473 if (DEBUG) Log.i(TAG, "finishLibraryLoad() exiting");
477 * Call this to send a Bundle containing the shared RELRO sections to be
478 * used in this process. If initServiceProcess() was previously called,
479 * finishLibraryLoad() will not exit until this method is called in another
480 * thread with a non-null value.
481 * @param bundle The Bundle instance containing a map of shared RELRO sections
482 * to use in this process.
484 public static void useSharedRelros(Bundle bundle) {
485 // Ensure the bundle uses the application's class loader, not the framework
486 // one which doesn't know anything about LibInfo.
487 // Also, hold a fresh copy of it so the caller can't recycle it.
488 Bundle clonedBundle = null;
489 if (bundle != null) {
490 bundle.setClassLoader(LibInfo.class.getClassLoader());
491 clonedBundle = new Bundle(LibInfo.class.getClassLoader());
492 Parcel parcel = Parcel.obtain();
493 bundle.writeToParcel(parcel, 0);
494 parcel.setDataPosition(0);
495 clonedBundle.readFromParcel(parcel);
499 Log.i(TAG, "useSharedRelros() called with " + bundle +
500 ", cloned " + clonedBundle);
502 synchronized (Linker.class) {
503 // Note that in certain cases, this can be called before
504 // initServiceProcess() in service processes.
505 sSharedRelros = clonedBundle;
506 // Tell any listener blocked in finishLibraryLoad() about it.
507 Linker.class.notifyAll();
512 * Call this to retrieve the shared RELRO sections created in this process,
513 * after loading all libraries.
514 * @return a new Bundle instance, or null if RELRO sharing is disabled on
515 * this system, or if initServiceProcess() was called previously.
517 public static Bundle getSharedRelros() {
518 if (DEBUG) Log.i(TAG, "getSharedRelros() called");
519 synchronized (Linker.class) {
520 if (!sInBrowserProcess) {
521 if (DEBUG) Log.i(TAG, "... returning null Bundle");
525 // Return the Bundle created in finishLibraryLoad().
526 if (DEBUG) Log.i(TAG, "... returning " + sSharedRelros);
527 return sSharedRelros;
533 * Call this method before loading any libraries to indicate that this
534 * process shall neither create or reuse shared RELRO sections.
536 public static void disableSharedRelros() {
537 if (DEBUG) Log.i(TAG, "disableSharedRelros() called");
538 synchronized (Linker.class) {
539 sInBrowserProcess = false;
540 sWaitForSharedRelros = false;
541 sBrowserUsesSharedRelro = false;
546 * Call this method before loading any libraries to indicate that this
547 * process is ready to reuse shared RELRO sections from another one.
548 * Typically used when starting service processes.
549 * @param baseLoadAddress the base library load address to use.
551 public static void initServiceProcess(long baseLoadAddress) {
553 Log.i(TAG, String.format(
554 Locale.US, "initServiceProcess(0x%x) called", baseLoadAddress));
556 synchronized (Linker.class) {
557 ensureInitializedLocked();
558 sInBrowserProcess = false;
559 sBrowserUsesSharedRelro = false;
560 if (sRelroSharingSupported) {
561 sWaitForSharedRelros = true;
562 sBaseLoadAddress = baseLoadAddress;
563 sCurrentLoadAddress = baseLoadAddress;
569 * Retrieve the base load address of all shared RELRO sections.
570 * This also enforces the creation of shared RELRO sections in
571 * prepareLibraryLoad(), which can later be retrieved with getSharedRelros().
572 * @return a common, random base load address, or 0 if RELRO sharing is
575 public static long getBaseLoadAddress() {
576 synchronized (Linker.class) {
577 ensureInitializedLocked();
578 if (!sInBrowserProcess) {
579 Log.w(TAG, "Shared RELRO sections are disabled in this process!");
583 setupBaseLoadAddressLocked();
584 if (DEBUG) Log.i(TAG, String.format(Locale.US, "getBaseLoadAddress() returns 0x%x",
586 return sBaseLoadAddress;
590 // Used internally to lazily setup the common random base load address.
591 private static void setupBaseLoadAddressLocked() {
592 assert Thread.holdsLock(Linker.class);
593 if (sBaseLoadAddress == 0) {
594 long address = computeRandomBaseLoadAddress();
595 sBaseLoadAddress = address;
596 sCurrentLoadAddress = address;
598 // If the computed address is 0, there are issues with the
599 // entropy source, so disable RELRO shared / fixed load addresses.
600 Log.w(TAG, "Disabling shared RELROs due to bad entropy sources");
601 sBrowserUsesSharedRelro = false;
602 sWaitForSharedRelros = false;
609 * Compute a random base load address where to place loaded libraries.
610 * @return new base load address, or 0 if the system does not support
613 private static long computeRandomBaseLoadAddress() {
614 // The kernel ASLR feature will place randomized mappings starting
615 // from this address. Never try to load anything above this
616 // explicitly to avoid random conflicts.
617 final long baseAddressLimit = 0x40000000;
619 // Start loading libraries from this base address.
620 final long baseAddress = 0x20000000;
622 // Maximum randomized base address value. Used to ensure a margin
623 // of 192 MB below baseAddressLimit.
624 final long baseAddressMax = baseAddressLimit - 192 * 1024 * 1024;
626 // The maximum limit of the desired random offset.
627 final long pageSize = nativeGetPageSize();
628 final int offsetLimit = (int) ((baseAddressMax - baseAddress) / pageSize);
630 // Get the greatest power of 2 that is smaller or equal to offsetLimit.
632 for (; numBits > 1; numBits--) {
633 if ((1 << numBits) <= offsetLimit)
638 final int maxValue = (1 << numBits) - 1;
639 Log.i(TAG, String.format(Locale.US, "offsetLimit=%d numBits=%d maxValue=%d (0x%x)",
640 offsetLimit, numBits, maxValue, maxValue));
643 // Find a random offset between 0 and (2^numBits - 1), included.
644 int offset = getRandomBits(numBits);
647 address = baseAddress + offset * pageSize;
651 String.format(Locale.US, "Linker.computeRandomBaseLoadAddress() return 0x%x",
658 * Return a cryptographically-strong random number of numBits bits.
659 * @param numBits The number of bits in the result. Must be in 1..31 range.
660 * @return A random integer between 0 and (2^numBits - 1), inclusive, or -1
661 * in case of error (e.g. if /dev/urandom can't be opened or read).
663 private static int getRandomBits(int numBits) {
668 FileInputStream input;
670 // A naive implementation would read a 32-bit integer then use modulo, but
671 // this introduces a slight bias. Instead, read 32-bit integers from the
672 // entropy source until the value is positive but smaller than maxLimit.
673 input = new FileInputStream(new File("/dev/urandom"));
674 } catch (Exception e) {
675 Log.e(TAG, "Could not open /dev/urandom", e);
681 for (int n = 0; n < 4; n++) {
682 result = (result << 8) | (input.read() & 255);
684 } catch (Exception e) {
685 Log.e(TAG, "Could not read /dev/urandom", e);
690 } catch (Exception e) {
691 // Can't really do anything here.
694 result &= (1 << numBits) - 1;
697 Log.i(TAG, String.format(
698 Locale.US, "getRandomBits(%d) returned %d", numBits, result));
704 // Used for debugging only.
705 private static void dumpBundle(Bundle bundle) {
706 if (DEBUG) Log.i(TAG, "Bundle has " + bundle.size() + " items: " + bundle);
710 * Use the shared RELRO section from a Bundle received form another process.
711 * Call this after calling setBaseLoadAddress() then loading all libraries
712 * with loadLibrary().
713 * @param bundle Bundle instance generated with createSharedRelroBundle() in
716 private static void useSharedRelrosLocked(Bundle bundle) {
717 assert Thread.holdsLock(Linker.class);
719 if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() called");
721 if (bundle == null) {
722 if (DEBUG) Log.i(TAG, "null bundle!");
726 if (!sRelroSharingSupported) {
727 if (DEBUG) Log.i(TAG, "System does not support RELRO sharing");
731 if (sLoadedLibraries == null) {
732 if (DEBUG) Log.i(TAG, "No libraries loaded!");
736 if (DEBUG) dumpBundle(bundle);
737 HashMap<String, LibInfo> relroMap = createLibInfoMapFromBundle(bundle);
739 // Apply the RELRO section to all libraries that were already loaded.
740 for (Map.Entry<String, LibInfo> entry : relroMap.entrySet()) {
741 String libName = entry.getKey();
742 LibInfo libInfo = entry.getValue();
743 if (!nativeUseSharedRelro(libName, libInfo)) {
744 Log.w(TAG, "Could not use shared RELRO section for " + libName);
746 if (DEBUG) Log.i(TAG, "Using shared RELRO section for " + libName);
750 // In service processes, close all file descriptors from the map now.
751 if (!sInBrowserProcess)
752 closeLibInfoMap(relroMap);
754 if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() exiting");
758 * Returns whether the linker was unable to load one library at a given fixed address.
760 * @return true if at least one library was not loaded at the expected fixed address.
762 public static boolean loadAtFixedAddressFailed() {
763 return sLoadAtFixedAddressFailed;
767 * Load a native shared library with the Chromium linker.
768 * The shared library is uncompressed and page aligned inside the zipfile.
769 * Note the crazy linker treats libraries and files as equivalent,
770 * so you can only open one library in a given zip file.
772 * @param zipfile The filename of the zipfile contain the library.
773 * @param library The library's base name.
775 public static void loadLibraryInZipFile(String zipfile, String library) {
776 loadLibraryMaybeInZipFile(zipfile, library);
780 * Load a native shared library with the Chromium linker.
782 * @param library The library's base name.
784 public static void loadLibrary(String library) {
785 loadLibraryMaybeInZipFile(null, library);
788 private static void loadLibraryMaybeInZipFile(
789 @Nullable String zipFile, String library) {
790 if (DEBUG) Log.i(TAG, "loadLibrary: " + library);
792 // Don't self-load the linker. This is because the build system is
793 // not clever enough to understand that all the libraries packaged
794 // in the final .apk don't need to be explicitly loaded.
795 // Also deal with the component build that adds a .cr suffix to the name.
796 if (library.equals(TAG) || library.equals(TAG + ".cr")) {
797 if (DEBUG) Log.i(TAG, "ignoring self-linker load");
801 synchronized (Linker.class) {
802 ensureInitializedLocked();
804 // Security: Ensure prepareLibraryLoad() was called before.
805 // In theory, this can be done lazily here, but it's more consistent
806 // to use a pair of functions (i.e. prepareLibraryLoad() + finishLibraryLoad())
807 // that wrap all calls to loadLibrary() in the library loader.
808 assert sPrepareLibraryLoadCalled;
810 String libName = System.mapLibraryName(library);
812 if (sLoadedLibraries == null)
813 sLoadedLibraries = new HashMap<String, LibInfo>();
815 if (sLoadedLibraries.containsKey(libName)) {
816 if (DEBUG) Log.i(TAG, "Not loading " + libName + " twice");
820 LibInfo libInfo = new LibInfo();
821 long loadAddress = 0;
822 if ((sInBrowserProcess && sBrowserUsesSharedRelro) || sWaitForSharedRelros) {
823 // Load the library at a fixed address.
824 loadAddress = sCurrentLoadAddress;
827 String sharedRelRoName = libName;
828 if (zipFile != null) {
829 if (!nativeLoadLibraryInZipFile(
830 zipFile, libName, loadAddress, libInfo)) {
831 String errorMessage =
832 "Unable to load library: " + libName + " in: " +
834 Log.e(TAG, errorMessage);
835 throw new UnsatisfiedLinkError(errorMessage);
837 sharedRelRoName = zipFile;
839 if (!nativeLoadLibrary(libName, loadAddress, libInfo)) {
840 String errorMessage = "Unable to load library: " + libName;
841 Log.e(TAG, errorMessage);
842 throw new UnsatisfiedLinkError(errorMessage);
845 // Keep track whether the library has been loaded at the expected load address.
846 if (loadAddress != 0 && loadAddress != libInfo.mLoadAddress)
847 sLoadAtFixedAddressFailed = true;
849 // Print the load address to the logcat when testing the linker. The format
850 // of the string is expected by the Python test_runner script as one of:
851 // BROWSER_LIBRARY_ADDRESS: <library-name> <address>
852 // RENDERER_LIBRARY_ADDRESS: <library-name> <address>
853 // Where <library-name> is the library name, and <address> is the hexadecimal load
855 if (NativeLibraries.ENABLE_LINKER_TESTS) {
856 Log.i(TAG, String.format(
858 "%s_LIBRARY_ADDRESS: %s %x",
859 sInBrowserProcess ? "BROWSER" : "RENDERER",
861 libInfo.mLoadAddress));
864 if (sInBrowserProcess) {
865 // Create a new shared RELRO section at the 'current' fixed load address.
866 if (!nativeCreateSharedRelro(sharedRelRoName, sCurrentLoadAddress, libInfo)) {
867 Log.w(TAG, String.format(Locale.US,
868 "Could not create shared RELRO for %s at %x", libName,
869 sCurrentLoadAddress));
871 if (DEBUG) Log.i(TAG,
874 "Created shared RELRO for %s at %x: %s",
877 libInfo.toString()));
881 if (sCurrentLoadAddress != 0) {
882 // Compute the next current load address. If sBaseLoadAddress
883 // is not 0, this is an explicit library load address. Otherwise,
884 // this is an explicit load address for relocated RELRO sections
886 sCurrentLoadAddress = libInfo.mLoadAddress + libInfo.mLoadSize;
889 sLoadedLibraries.put(libName, libInfo);
890 if (DEBUG) Log.i(TAG, "Library details " + libInfo.toString());
895 * Move activity from the native thread to the main UI thread.
896 * Called from native code on its own thread. Posts a callback from
897 * the UI thread back to native code.
899 * @param opaque Opaque argument.
901 public static void postCallbackOnMainThread(final long opaque) {
902 ThreadUtils.postOnUiThread(new Runnable() {
905 nativeRunCallbackOnUiThread(opaque);
911 * Native method to run callbacks on the main UI thread.
912 * Supplied by the crazy linker and called by postCallbackOnMainThread.
913 * @param opaque Opaque crazy linker arguments.
915 private static native void nativeRunCallbackOnUiThread(long opaque);
918 * Native method used to load a library.
919 * @param library Platform specific library name (e.g. libfoo.so)
920 * @param loadAddress Explicit load address, or 0 for randomized one.
921 * @param libInfo If not null, the mLoadAddress and mLoadSize fields
922 * of this LibInfo instance will set on success.
923 * @return true for success, false otherwise.
925 private static native boolean nativeLoadLibrary(String library,
930 * Native method used to load a library which is inside a zipfile.
931 * @param zipfileName Filename of the zip file containing the library.
932 * @param library Platform specific library name (e.g. libfoo.so)
933 * @param loadAddress Explicit load address, or 0 for randomized one.
934 * @param libInfo If not null, the mLoadAddress and mLoadSize fields
935 * of this LibInfo instance will set on success.
936 * @return true for success, false otherwise.
938 private static native boolean nativeLoadLibraryInZipFile(
945 * Native method used to create a shared RELRO section.
946 * If the library was already loaded at the same address using
947 * nativeLoadLibrary(), this creates the RELRO for it. Otherwise,
948 * this loads a new temporary library at the specified address,
949 * creates and extracts the RELRO section from it, then unloads it.
950 * @param library Library name.
951 * @param loadAddress load address, which can be different from the one
952 * used to load the library in the current process!
953 * @param libInfo libInfo instance. On success, the mRelroStart, mRelroSize
954 * and mRelroFd will be set.
955 * @return true on success, false otherwise.
957 private static native boolean nativeCreateSharedRelro(String library,
962 * Native method used to use a shared RELRO section.
963 * @param library Library name.
964 * @param libInfo A LibInfo instance containing valid RELRO information
965 * @return true on success.
967 private static native boolean nativeUseSharedRelro(String library,
971 * Checks that the system supports shared RELROs. Old Android kernels
972 * have a bug in the way they check Ashmem region protection flags, which
973 * makes using shared RELROs unsafe. This method performs a simple runtime
974 * check for this misfeature, even though nativeEnableSharedRelro() will
975 * always fail if this returns false.
977 private static native boolean nativeCanUseSharedRelro();
979 // Returns the native page size in bytes.
980 private static native long nativeGetPageSize();
983 * Record information for a given library.
984 * IMPORTANT: Native code knows about this class's fields, so
985 * don't change them without modifying the corresponding C++ sources.
986 * Also, the LibInfo instance owns the ashmem file descriptor.
988 public static class LibInfo implements Parcelable {
998 public void close() {
1001 ParcelFileDescriptor.adoptFd(mRelroFd).close();
1002 } catch (java.io.IOException e) {
1003 if (DEBUG) Log.e(TAG, "Failed to close fd: " + mRelroFd);
1010 public LibInfo(Parcel in) {
1011 mLoadAddress = in.readLong();
1012 mLoadSize = in.readLong();
1013 mRelroStart = in.readLong();
1014 mRelroSize = in.readLong();
1015 ParcelFileDescriptor fd = in.readFileDescriptor();
1016 mRelroFd = fd.detachFd();
1021 public void writeToParcel(Parcel out, int flags) {
1022 if (mRelroFd >= 0) {
1023 out.writeLong(mLoadAddress);
1024 out.writeLong(mLoadSize);
1025 out.writeLong(mRelroStart);
1026 out.writeLong(mRelroSize);
1028 ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd);
1029 fd.writeToParcel(out, 0);
1031 } catch (java.io.IOException e) {
1032 Log.e(TAG, "Cant' write LibInfo file descriptor to parcel", e);
1039 public int describeContents() {
1040 return Parcelable.CONTENTS_FILE_DESCRIPTOR;
1044 public static final Parcelable.Creator<LibInfo> CREATOR =
1045 new Parcelable.Creator<LibInfo>() {
1047 public LibInfo createFromParcel(Parcel in) {
1048 return new LibInfo(in);
1052 public LibInfo[] newArray(int size) {
1053 return new LibInfo[size];
1058 public String toString() {
1059 return String.format(Locale.US,
1060 "[load=0x%x-0x%x relro=0x%x-0x%x fd=%d]",
1062 mLoadAddress + mLoadSize,
1064 mRelroStart + mRelroSize,
1068 // IMPORTANT: Don't change these fields without modifying the
1069 // native code that accesses them directly!
1070 public long mLoadAddress; // page-aligned library load address.
1071 public long mLoadSize; // page-aligned library load size.
1072 public long mRelroStart; // page-aligned address in memory, or 0 if none.
1073 public long mRelroSize; // page-aligned size in memory, or 0.
1074 public int mRelroFd; // ashmem file descriptor, or -1
1077 // Create a Bundle from a map of LibInfo objects.
1078 private static Bundle createBundleFromLibInfoMap(HashMap<String, LibInfo> map) {
1079 Bundle bundle = new Bundle(map.size());
1080 for (Map.Entry<String, LibInfo> entry : map.entrySet()) {
1081 bundle.putParcelable(entry.getKey(), entry.getValue());
1087 // Create a new LibInfo map from a Bundle.
1088 private static HashMap<String, LibInfo> createLibInfoMapFromBundle(Bundle bundle) {
1089 HashMap<String, LibInfo> map = new HashMap<String, LibInfo>();
1090 for (String library : bundle.keySet()) {
1091 LibInfo libInfo = bundle.getParcelable(library);
1092 map.put(library, libInfo);
1097 // Call the close() method on all values of a LibInfo map.
1098 private static void closeLibInfoMap(HashMap<String, LibInfo> map) {
1099 for (Map.Entry<String, LibInfo> entry : map.entrySet()) {
1100 entry.getValue().close();
1104 // The map of libraries that are currently loaded in this process.
1105 private static HashMap<String, LibInfo> sLoadedLibraries = null;
1107 // Used to pass the shared RELRO Bundle through Binder.
1108 public static final String EXTRA_LINKER_SHARED_RELROS =
1109 "org.chromium.base.android.linker.shared_relros";