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.AccessedByNative;
14 import org.chromium.base.CalledByNative;
15 import org.chromium.base.SysUtils;
16 import org.chromium.base.ThreadUtils;
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 linker will try to use shared RELROs
378 * for the browser process.
380 public static boolean isUsingBrowserSharedRelros() {
381 synchronized (Linker.class) {
382 ensureInitializedLocked();
383 return sBrowserUsesSharedRelro;
388 * Call this method to determine if the chromium project must load
389 * the library directly from the zip file.
391 public static boolean isInZipFile() {
392 return NativeLibraries.USE_LIBRARY_IN_ZIP_FILE;
396 * Call this method just before loading any native shared libraries in this process.
398 public static void prepareLibraryLoad() {
399 if (DEBUG) Log.i(TAG, "prepareLibraryLoad() called");
400 synchronized (Linker.class) {
401 sPrepareLibraryLoadCalled = true;
403 if (sInBrowserProcess) {
404 // Force generation of random base load address, as well
405 // as creation of shared RELRO sections in this process.
406 setupBaseLoadAddressLocked();
412 * Call this method just after loading all native shared libraries in this process.
413 * Note that when in a service process, this will block until the RELRO bundle is
414 * received, i.e. when another thread calls useSharedRelros().
416 public static void finishLibraryLoad() {
417 if (DEBUG) Log.i(TAG, "finishLibraryLoad() called");
418 synchronized (Linker.class) {
419 if (DEBUG) Log.i(TAG, String.format(
421 "sInBrowserProcess=%s sBrowserUsesSharedRelro=%s sWaitForSharedRelros=%s",
422 sInBrowserProcess ? "true" : "false",
423 sBrowserUsesSharedRelro ? "true" : "false",
424 sWaitForSharedRelros ? "true" : "false"));
426 if (sLoadedLibraries == null) {
427 if (DEBUG) Log.i(TAG, "No libraries loaded");
429 if (sInBrowserProcess) {
430 // Create new Bundle containing RELRO section information
431 // for all loaded libraries. Make it available to getSharedRelros().
432 sSharedRelros = createBundleFromLibInfoMap(sLoadedLibraries);
434 Log.i(TAG, "Shared RELRO created");
435 dumpBundle(sSharedRelros);
438 if (sBrowserUsesSharedRelro) {
439 useSharedRelrosLocked(sSharedRelros);
443 if (sWaitForSharedRelros) {
444 assert !sInBrowserProcess;
446 // Wait until the shared relro bundle is received from useSharedRelros().
447 while (sSharedRelros == null) {
450 } catch (InterruptedException ie) {
454 useSharedRelrosLocked(sSharedRelros);
455 // Clear the Bundle to ensure its file descriptor references can't be reused.
456 sSharedRelros.clear();
457 sSharedRelros = null;
461 if (NativeLibraries.ENABLE_LINKER_TESTS && sTestRunnerClassName != null) {
462 // The TestRunner implementation must be instantiated _after_
463 // all libraries are loaded to ensure that its native methods
464 // are properly registered.
465 if (DEBUG) Log.i(TAG, "Instantiating " + sTestRunnerClassName);
466 TestRunner testRunner = null;
468 testRunner = (TestRunner)
469 Class.forName(sTestRunnerClassName).newInstance();
470 } catch (Exception e) {
471 Log.e(TAG, "Could not extract test runner class name", e);
474 if (testRunner != null) {
475 if (!testRunner.runChecks(sMemoryDeviceConfig, sInBrowserProcess)) {
476 Log.wtf(TAG, "Linker runtime tests failed in this process!!");
479 Log.i(TAG, "All linker tests passed!");
484 if (DEBUG) Log.i(TAG, "finishLibraryLoad() exiting");
488 * Call this to send a Bundle containing the shared RELRO sections to be
489 * used in this process. If initServiceProcess() was previously called,
490 * finishLibraryLoad() will not exit until this method is called in another
491 * thread with a non-null value.
492 * @param bundle The Bundle instance containing a map of shared RELRO sections
493 * to use in this process.
495 public static void useSharedRelros(Bundle bundle) {
496 // Ensure the bundle uses the application's class loader, not the framework
497 // one which doesn't know anything about LibInfo.
498 // Also, hold a fresh copy of it so the caller can't recycle it.
499 Bundle clonedBundle = null;
500 if (bundle != null) {
501 bundle.setClassLoader(LibInfo.class.getClassLoader());
502 clonedBundle = new Bundle(LibInfo.class.getClassLoader());
503 Parcel parcel = Parcel.obtain();
504 bundle.writeToParcel(parcel, 0);
505 parcel.setDataPosition(0);
506 clonedBundle.readFromParcel(parcel);
510 Log.i(TAG, "useSharedRelros() called with " + bundle +
511 ", cloned " + clonedBundle);
513 synchronized (Linker.class) {
514 // Note that in certain cases, this can be called before
515 // initServiceProcess() in service processes.
516 sSharedRelros = clonedBundle;
517 // Tell any listener blocked in finishLibraryLoad() about it.
518 Linker.class.notifyAll();
523 * Call this to retrieve the shared RELRO sections created in this process,
524 * after loading all libraries.
525 * @return a new Bundle instance, or null if RELRO sharing is disabled on
526 * this system, or if initServiceProcess() was called previously.
528 public static Bundle getSharedRelros() {
529 if (DEBUG) Log.i(TAG, "getSharedRelros() called");
530 synchronized (Linker.class) {
531 if (!sInBrowserProcess) {
532 if (DEBUG) Log.i(TAG, "... returning null Bundle");
536 // Return the Bundle created in finishLibraryLoad().
537 if (DEBUG) Log.i(TAG, "... returning " + sSharedRelros);
538 return sSharedRelros;
544 * Call this method before loading any libraries to indicate that this
545 * process shall neither create or reuse shared RELRO sections.
547 public static void disableSharedRelros() {
548 if (DEBUG) Log.i(TAG, "disableSharedRelros() called");
549 synchronized (Linker.class) {
550 sInBrowserProcess = false;
551 sWaitForSharedRelros = false;
552 sBrowserUsesSharedRelro = false;
557 * Call this method before loading any libraries to indicate that this
558 * process is ready to reuse shared RELRO sections from another one.
559 * Typically used when starting service processes.
560 * @param baseLoadAddress the base library load address to use.
562 public static void initServiceProcess(long baseLoadAddress) {
564 Log.i(TAG, String.format(
565 Locale.US, "initServiceProcess(0x%x) called", baseLoadAddress));
567 synchronized (Linker.class) {
568 ensureInitializedLocked();
569 sInBrowserProcess = false;
570 sBrowserUsesSharedRelro = false;
571 if (sRelroSharingSupported) {
572 sWaitForSharedRelros = true;
573 sBaseLoadAddress = baseLoadAddress;
574 sCurrentLoadAddress = baseLoadAddress;
580 * Retrieve the base load address of all shared RELRO sections.
581 * This also enforces the creation of shared RELRO sections in
582 * prepareLibraryLoad(), which can later be retrieved with getSharedRelros().
583 * @return a common, random base load address, or 0 if RELRO sharing is
586 public static long getBaseLoadAddress() {
587 synchronized (Linker.class) {
588 ensureInitializedLocked();
589 if (!sInBrowserProcess) {
590 Log.w(TAG, "Shared RELRO sections are disabled in this process!");
594 setupBaseLoadAddressLocked();
595 if (DEBUG) Log.i(TAG, String.format(Locale.US, "getBaseLoadAddress() returns 0x%x",
597 return sBaseLoadAddress;
601 // Used internally to lazily setup the common random base load address.
602 private static void setupBaseLoadAddressLocked() {
603 assert Thread.holdsLock(Linker.class);
604 if (sBaseLoadAddress == 0) {
605 long address = computeRandomBaseLoadAddress();
606 sBaseLoadAddress = address;
607 sCurrentLoadAddress = address;
609 // If the computed address is 0, there are issues with finding enough
610 // free address space, so disable RELRO shared / fixed load addresses.
611 Log.w(TAG, "Disabling shared RELROs due address space pressure");
612 sBrowserUsesSharedRelro = false;
613 sWaitForSharedRelros = false;
620 * Compute a random base load address at which to place loaded libraries.
621 * @return new base load address, or 0 if the system does not support
624 private static long computeRandomBaseLoadAddress() {
625 // nativeGetRandomBaseLoadAddress() returns an address at which it has previously
626 // successfully mapped an area of the given size, on the basis that we will be
627 // able, with high probability, to map our library into it.
629 // One issue with this is that we do not yet know the size of the library that
630 // we will load is. So here we pass a value that we expect will always be larger
631 // than that needed. If it is smaller the library mapping may still succeed. The
632 // other issue is that although highly unlikely, there is no guarantee that
633 // something else does not map into the area we are going to use between here and
634 // when we try to map into it.
636 // The above notes mean that all of this is probablistic. It is however okay to do
637 // because if, worst case and unlikely, we get unlucky in our choice of address,
638 // the back-out and retry without the shared RELRO in the ChildProcessService will
639 // keep things running.
640 final long maxExpectedBytes = 192 * 1024 * 1024;
641 final long address = nativeGetRandomBaseLoadAddress(maxExpectedBytes);
644 String.format(Locale.US, "Random native base load address: 0x%x", address));
649 // Used for debugging only.
650 private static void dumpBundle(Bundle bundle) {
651 if (DEBUG) Log.i(TAG, "Bundle has " + bundle.size() + " items: " + bundle);
655 * Use the shared RELRO section from a Bundle received form another process.
656 * Call this after calling setBaseLoadAddress() then loading all libraries
657 * with loadLibrary().
658 * @param bundle Bundle instance generated with createSharedRelroBundle() in
661 private static void useSharedRelrosLocked(Bundle bundle) {
662 assert Thread.holdsLock(Linker.class);
664 if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() called");
666 if (bundle == null) {
667 if (DEBUG) Log.i(TAG, "null bundle!");
671 if (!sRelroSharingSupported) {
672 if (DEBUG) Log.i(TAG, "System does not support RELRO sharing");
676 if (sLoadedLibraries == null) {
677 if (DEBUG) Log.i(TAG, "No libraries loaded!");
681 if (DEBUG) dumpBundle(bundle);
682 HashMap<String, LibInfo> relroMap = createLibInfoMapFromBundle(bundle);
684 // Apply the RELRO section to all libraries that were already loaded.
685 for (Map.Entry<String, LibInfo> entry : relroMap.entrySet()) {
686 String libName = entry.getKey();
687 LibInfo libInfo = entry.getValue();
688 if (!nativeUseSharedRelro(libName, libInfo)) {
689 Log.w(TAG, "Could not use shared RELRO section for " + libName);
691 if (DEBUG) Log.i(TAG, "Using shared RELRO section for " + libName);
695 // In service processes, close all file descriptors from the map now.
696 if (!sInBrowserProcess)
697 closeLibInfoMap(relroMap);
699 if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() exiting");
703 * Returns whether the linker was unable to load one library at a given fixed address.
705 * @return true if at least one library was not loaded at the expected fixed address.
707 public static boolean loadAtFixedAddressFailed() {
708 return sLoadAtFixedAddressFailed;
712 * Load a native shared library with the Chromium linker.
713 * The shared library is uncompressed and page aligned inside the zipfile.
714 * Note the crazy linker treats libraries and files as equivalent,
715 * so you can only open one library in a given zip file.
717 * @param zipfile The filename of the zipfile contain the library.
718 * @param library The library's base name.
720 public static void loadLibraryInZipFile(String zipfile, String library) {
721 loadLibraryMaybeInZipFile(zipfile, library);
725 * Load a native shared library with the Chromium linker.
727 * @param library The library's base name.
729 public static void loadLibrary(String library) {
730 loadLibraryMaybeInZipFile(null, library);
733 private static void loadLibraryMaybeInZipFile(
734 @Nullable String zipFile, String library) {
735 if (DEBUG) Log.i(TAG, "loadLibrary: " + library);
737 // Don't self-load the linker. This is because the build system is
738 // not clever enough to understand that all the libraries packaged
739 // in the final .apk don't need to be explicitly loaded.
740 // Also deal with the component build that adds a .cr suffix to the name.
741 if (library.equals(TAG) || library.equals(TAG + ".cr")) {
742 if (DEBUG) Log.i(TAG, "ignoring self-linker load");
746 synchronized (Linker.class) {
747 ensureInitializedLocked();
749 // Security: Ensure prepareLibraryLoad() was called before.
750 // In theory, this can be done lazily here, but it's more consistent
751 // to use a pair of functions (i.e. prepareLibraryLoad() + finishLibraryLoad())
752 // that wrap all calls to loadLibrary() in the library loader.
753 assert sPrepareLibraryLoadCalled;
755 String libName = System.mapLibraryName(library);
757 if (sLoadedLibraries == null)
758 sLoadedLibraries = new HashMap<String, LibInfo>();
760 if (sLoadedLibraries.containsKey(libName)) {
761 if (DEBUG) Log.i(TAG, "Not loading " + libName + " twice");
765 LibInfo libInfo = new LibInfo();
766 long loadAddress = 0;
767 if ((sInBrowserProcess && sBrowserUsesSharedRelro) || sWaitForSharedRelros) {
768 // Load the library at a fixed address.
769 loadAddress = sCurrentLoadAddress;
772 String sharedRelRoName = libName;
773 if (zipFile != null) {
774 if (!nativeLoadLibraryInZipFile(
775 zipFile, libName, loadAddress, libInfo)) {
776 String errorMessage =
777 "Unable to load library: " + libName + " in: " +
779 Log.e(TAG, errorMessage);
780 throw new UnsatisfiedLinkError(errorMessage);
782 sharedRelRoName = zipFile;
784 if (!nativeLoadLibrary(libName, loadAddress, libInfo)) {
785 String errorMessage = "Unable to load library: " + libName;
786 Log.e(TAG, errorMessage);
787 throw new UnsatisfiedLinkError(errorMessage);
790 // Keep track whether the library has been loaded at the expected load address.
791 if (loadAddress != 0 && loadAddress != libInfo.mLoadAddress)
792 sLoadAtFixedAddressFailed = true;
794 // Print the load address to the logcat when testing the linker. The format
795 // of the string is expected by the Python test_runner script as one of:
796 // BROWSER_LIBRARY_ADDRESS: <library-name> <address>
797 // RENDERER_LIBRARY_ADDRESS: <library-name> <address>
798 // Where <library-name> is the library name, and <address> is the hexadecimal load
800 if (NativeLibraries.ENABLE_LINKER_TESTS) {
801 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(sharedRelRoName, sCurrentLoadAddress, libInfo)) {
812 Log.w(TAG, String.format(Locale.US,
813 "Could not create shared RELRO for %s at %x", libName,
814 sCurrentLoadAddress));
816 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 * Move activity from the native thread to the main UI thread.
841 * Called from native code on its own thread. Posts a callback from
842 * the UI thread back to native code.
844 * @param opaque Opaque argument.
847 public static void postCallbackOnMainThread(final long opaque) {
848 ThreadUtils.postOnUiThread(new Runnable() {
851 nativeRunCallbackOnUiThread(opaque);
857 * Native method to run callbacks on the main UI thread.
858 * Supplied by the crazy linker and called by postCallbackOnMainThread.
859 * @param opaque Opaque crazy linker arguments.
861 private static native void nativeRunCallbackOnUiThread(long opaque);
864 * Native method used to load a library.
865 * @param library Platform specific library name (e.g. libfoo.so)
866 * @param loadAddress Explicit load address, or 0 for randomized one.
867 * @param libInfo If not null, the mLoadAddress and mLoadSize fields
868 * of this LibInfo instance will set on success.
869 * @return true for success, false otherwise.
871 private static native boolean nativeLoadLibrary(String library,
876 * Native method used to load a library which is inside a zipfile.
877 * @param zipfileName Filename of the zip file containing the library.
878 * @param library Platform specific library name (e.g. libfoo.so)
879 * @param loadAddress Explicit load address, or 0 for randomized one.
880 * @param libInfo If not null, the mLoadAddress and mLoadSize fields
881 * of this LibInfo instance will set on success.
882 * @return true for success, false otherwise.
884 private static native boolean nativeLoadLibraryInZipFile(
891 * Native method used to create a shared RELRO section.
892 * If the library was already loaded at the same address using
893 * nativeLoadLibrary(), this creates the RELRO for it. Otherwise,
894 * this loads a new temporary library at the specified address,
895 * creates and extracts the RELRO section from it, then unloads it.
896 * @param library Library name.
897 * @param loadAddress load address, which can be different from the one
898 * used to load the library in the current process!
899 * @param libInfo libInfo instance. On success, the mRelroStart, mRelroSize
900 * and mRelroFd will be set.
901 * @return true on success, false otherwise.
903 private static native boolean nativeCreateSharedRelro(String library,
908 * Native method used to use a shared RELRO section.
909 * @param library Library name.
910 * @param libInfo A LibInfo instance containing valid RELRO information
911 * @return true on success.
913 private static native boolean nativeUseSharedRelro(String library,
917 * Checks that the system supports shared RELROs. Old Android kernels
918 * have a bug in the way they check Ashmem region protection flags, which
919 * makes using shared RELROs unsafe. This method performs a simple runtime
920 * check for this misfeature, even though nativeEnableSharedRelro() will
921 * always fail if this returns false.
923 private static native boolean nativeCanUseSharedRelro();
926 * Return a random address that should be free to be mapped with the given size.
927 * Maps an area of size bytes, and if successful then unmaps it and returns
928 * the address of the area allocated by the system (with ASLR). The idea is
929 * that this area should remain free of other mappings until we map our library
931 * @param sizeBytes Size of area in bytes to search for.
932 * @return address to pass to future mmap, or 0 on error.
934 private static native long nativeGetRandomBaseLoadAddress(long sizeBytes);
937 * Record information for a given library.
938 * IMPORTANT: Native code knows about this class's fields, so
939 * don't change them without modifying the corresponding C++ sources.
940 * Also, the LibInfo instance owns the ashmem file descriptor.
942 public static class LibInfo implements Parcelable {
952 public void close() {
955 ParcelFileDescriptor.adoptFd(mRelroFd).close();
956 } catch (java.io.IOException e) {
957 if (DEBUG) Log.e(TAG, "Failed to close fd: " + mRelroFd);
964 public LibInfo(Parcel in) {
965 mLoadAddress = in.readLong();
966 mLoadSize = in.readLong();
967 mRelroStart = in.readLong();
968 mRelroSize = in.readLong();
969 ParcelFileDescriptor fd = in.readFileDescriptor();
970 // If CreateSharedRelro fails, the OS file descriptor will be -1 and |fd| will be null.
971 mRelroFd = (fd == null) ? -1 : fd.detachFd();
976 public void writeToParcel(Parcel out, int flags) {
978 out.writeLong(mLoadAddress);
979 out.writeLong(mLoadSize);
980 out.writeLong(mRelroStart);
981 out.writeLong(mRelroSize);
983 ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd);
984 fd.writeToParcel(out, 0);
986 } catch (java.io.IOException e) {
987 Log.e(TAG, "Cant' write LibInfo file descriptor to parcel", e);
994 public int describeContents() {
995 return Parcelable.CONTENTS_FILE_DESCRIPTOR;
999 public static final Parcelable.Creator<LibInfo> CREATOR =
1000 new Parcelable.Creator<LibInfo>() {
1002 public LibInfo createFromParcel(Parcel in) {
1003 return new LibInfo(in);
1007 public LibInfo[] newArray(int size) {
1008 return new LibInfo[size];
1013 public String toString() {
1014 return String.format(Locale.US,
1015 "[load=0x%x-0x%x relro=0x%x-0x%x fd=%d]",
1017 mLoadAddress + mLoadSize,
1019 mRelroStart + mRelroSize,
1023 // IMPORTANT: Don't change these fields without modifying the
1024 // native code that accesses them directly!
1026 public long mLoadAddress; // page-aligned library load address.
1028 public long mLoadSize; // page-aligned library load size.
1030 public long mRelroStart; // page-aligned address in memory, or 0 if none.
1032 public long mRelroSize; // page-aligned size in memory, or 0.
1034 public int mRelroFd; // ashmem file descriptor, or -1
1037 // Create a Bundle from a map of LibInfo objects.
1038 private static Bundle createBundleFromLibInfoMap(HashMap<String, LibInfo> map) {
1039 Bundle bundle = new Bundle(map.size());
1040 for (Map.Entry<String, LibInfo> entry : map.entrySet()) {
1041 bundle.putParcelable(entry.getKey(), entry.getValue());
1047 // Create a new LibInfo map from a Bundle.
1048 private static HashMap<String, LibInfo> createLibInfoMapFromBundle(Bundle bundle) {
1049 HashMap<String, LibInfo> map = new HashMap<String, LibInfo>();
1050 for (String library : bundle.keySet()) {
1051 LibInfo libInfo = bundle.getParcelable(library);
1052 map.put(library, libInfo);
1057 // Call the close() method on all values of a LibInfo map.
1058 private static void closeLibInfoMap(HashMap<String, LibInfo> map) {
1059 for (Map.Entry<String, LibInfo> entry : map.entrySet()) {
1060 entry.getValue().close();
1064 // The map of libraries that are currently loaded in this process.
1065 private static HashMap<String, LibInfo> sLoadedLibraries = null;
1067 // Used to pass the shared RELRO Bundle through Binder.
1068 public static final String EXTRA_LINKER_SHARED_RELROS =
1069 "org.chromium.base.android.linker.shared_relros";