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.io.FileNotFoundException;
19 import java.util.HashMap;
20 import java.util.Locale;
23 import javax.annotation.Nullable;
28 * The point of this class is to provide an alternative to System.loadLibrary()
29 * to load native shared libraries. One specific feature that it supports is the
30 * ability to save RAM by sharing the ELF RELRO sections between renderer
33 * When two processes load the same native library at the _same_ memory address,
34 * the content of their RELRO section (which includes C++ vtables or any
35 * constants that contain pointers) will be largely identical [1].
37 * By default, the RELRO section is backed by private RAM in each process,
38 * which is still significant on mobile (e.g. 1.28 MB / process on Chrome 30 for
41 * However, it is possible to save RAM by creating a shared memory region,
42 * copy the RELRO content into it, then have each process swap its private,
43 * regular RELRO, with a shared, read-only, mapping of the shared one.
45 * This trick saves 98% of the RELRO section size per extra process, after the
46 * first one. On the other hand, this requires careful communication between
47 * the process where the shared RELRO is created and the one(s) where it is used.
49 * Note that swapping the regular RELRO with the shared one is not an atomic
50 * operation. Care must be taken that no other thread tries to run native code
51 * that accesses it during it. In practice, this means the swap must happen
52 * before library native code is executed.
54 * [1] The exceptions are pointers to external, randomized, symbols, like
55 * those from some system libraries, but these are very few in practice.
59 * Security considerations:
61 * - Whether the browser process loads its native libraries at the same
62 * addresses as the service ones (to save RAM by sharing the RELRO too)
63 * depends on the configuration variable BROWSER_SHARED_RELRO_CONFIG below.
65 * Not using fixed library addresses in the browser process is preferred
66 * for regular devices since it maintains the efficacy of ASLR as an
67 * exploit mitigation across the render <-> browser privilege boundary.
69 * - The shared RELRO memory region is always forced read-only after creation,
70 * which means it is impossible for a compromised service process to map
71 * it read-write (e.g. by calling mmap() or mprotect()) and modify its
72 * content, altering values seen in other service processes.
74 * - Unfortunately, certain Android systems use an old, buggy kernel, that
75 * doesn't check Ashmem region permissions correctly. See CVE-2011-1149
76 * for details. This linker probes the system on startup and will completely
77 * disable shared RELROs if it detects the problem. For the record, this is
78 * common for Android emulator system images (which are still based on 2.6.29)
80 * - Once the RELRO ashmem region is mapped into a service process' address
81 * space, the corresponding file descriptor is immediately closed. The
82 * file descriptor is kept opened in the browser process, because a copy needs
83 * to be sent to each new potential service process.
85 * - The common library load addresses are randomized for each instance of
86 * the program on the device. See computeRandomBaseLoadAddress() for more
87 * details on how this is computed.
89 * - When loading several libraries in service processes, a simple incremental
90 * approach from the original random base load address is used. This is
91 * sufficient to deal correctly with component builds (which can use dozens
92 * of shared libraries), while regular builds always embed a single shared
97 * Here's an explanation of how this class is supposed to be used:
99 * - Native shared libraries should be loaded with Linker.loadLibrary(),
100 * instead of System.loadLibrary(). The two functions take the same parameter
101 * and should behave the same (at a high level).
103 * - Before loading any library, prepareLibraryLoad() should be called.
105 * - After loading all libraries, finishLibraryLoad() should be called, before
106 * running any native code from any of the libraries (except their static
107 * constructors, which can't be avoided).
109 * - A service process shall call either initServiceProcess() or
110 * disableSharedRelros() early (i.e. before any loadLibrary() call).
111 * Otherwise, the linker considers that it is running inside the browser
112 * process. This is because various Chromium projects have vastly
113 * different initialization paths.
115 * disableSharedRelros() completely disables shared RELROs, and loadLibrary()
116 * will behave exactly like System.loadLibrary().
118 * initServiceProcess(baseLoadAddress) indicates that shared RELROs are to be
119 * used in this process.
121 * - The browser is in charge of deciding where in memory each library should
122 * be loaded. This address must be passed to each service process (see
123 * ChromiumLinkerParams.java in content for a helper class to do so).
125 * - The browser will also generate shared RELROs for each library it loads.
126 * More specifically, by default when in the browser process, the linker
129 * - Load libraries randomly (just like System.loadLibrary()).
130 * - Compute the fixed address to be used to load the same library
131 * in service processes.
132 * - Create a shared memory region populated with the RELRO region
133 * content pre-relocated for the specific fixed address above.
135 * Note that these shared RELRO regions cannot be used inside the browser
136 * process. They are also never mapped into it.
138 * This behaviour is altered by the BROWSER_SHARED_RELRO_CONFIG configuration
139 * variable below, which may force the browser to load the libraries at
140 * fixed addresses too.
142 * - Once all libraries are loaded in the browser process, one can call
143 * getSharedRelros() which returns a Bundle instance containing a map that
144 * links each loaded library to its shared RELRO region.
146 * This Bundle must be passed to each service process, for example through
147 * a Binder call (note that the Bundle includes file descriptors and cannot
148 * be added as an Intent extra).
150 * - In a service process, finishLibraryLoad() will block until the RELRO
151 * section Bundle is received. This is typically done by calling
152 * useSharedRelros() from another thread.
154 * This method also ensures the process uses the shared RELROs.
156 public class Linker {
158 // Log tag for this class. This must match the name of the linker's native library.
159 private static final String TAG = "chromium_android_linker";
161 // Set to true to enable debug logs.
162 private static final boolean DEBUG = false;
164 // Constants used to control the behaviour of the browser process with
165 // regards to the shared RELRO section.
166 // NEVER -> The browser never uses it itself.
167 // LOW_RAM_ONLY -> It is only used on devices with low RAM.
168 // ALWAYS -> It is always used.
169 // NOTE: These names are known and expected by the Linker test scripts.
170 public static final int BROWSER_SHARED_RELRO_CONFIG_NEVER = 0;
171 public static final int BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY = 1;
172 public static final int BROWSER_SHARED_RELRO_CONFIG_ALWAYS = 2;
174 // Configuration variable used to control how the browser process uses the
175 // shared RELRO. Only change this while debugging linker-related issues.
176 // NOTE: This variable's name is known and expected by the Linker test scripts.
177 public static final int BROWSER_SHARED_RELRO_CONFIG =
178 BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY;
180 // Constants used to control the value of sMemoryDeviceConfig.
181 // INIT -> Value is undetermined (will check at runtime).
182 // LOW -> This is a low-memory device.
183 // NORMAL -> This is not a low-memory device.
184 public static final int MEMORY_DEVICE_CONFIG_INIT = 0;
185 public static final int MEMORY_DEVICE_CONFIG_LOW = 1;
186 public static final int MEMORY_DEVICE_CONFIG_NORMAL = 2;
188 // Indicates if this is a low-memory device or not. The default is to
189 // determine this by probing the system at runtime, but this can be forced
190 // for testing by calling setMemoryDeviceConfig().
191 private static int sMemoryDeviceConfig = MEMORY_DEVICE_CONFIG_INIT;
193 // Becomes true after linker initialization.
194 private static boolean sInitialized = false;
196 // Set to true to indicate that the system supports safe sharing of RELRO sections.
197 private static boolean sRelroSharingSupported = false;
199 // Set to true if this runs in the browser process. Disabled by initServiceProcess().
200 // TODO(petrcermak): This flag can be incorrectly set to false (even though this might run in
201 // the browser process) on low-memory devices.
202 private static boolean sInBrowserProcess = true;
204 // Becomes true to indicate this process needs to wait for a shared RELRO in
205 // finishLibraryLoad().
206 private static boolean sWaitForSharedRelros = false;
208 // Becomes true when initialization determines that the browser process can use the
210 private static boolean sBrowserUsesSharedRelro = false;
212 // The map of all RELRO sections either created or used in this process.
213 private static Bundle sSharedRelros = null;
215 // Current common random base load address.
216 private static long sBaseLoadAddress = 0;
218 // Current fixed-location load address for the next library called by loadLibrary().
219 private static long sCurrentLoadAddress = 0;
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.sUseLinker) {
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 Log.w(TAG, "Couldn't load lib" + TAG + ".so, trying lib" + TAG + ".cr.so");
237 System.loadLibrary(TAG + ".cr");
239 sRelroSharingSupported = nativeCanUseSharedRelro();
240 if (!sRelroSharingSupported)
241 Log.w(TAG, "This system cannot safely share RELRO sections");
243 if (DEBUG) Log.i(TAG, "This system supports safe shared RELRO sections");
246 if (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT) {
247 sMemoryDeviceConfig = SysUtils.isLowEndDevice()
248 ? MEMORY_DEVICE_CONFIG_LOW : MEMORY_DEVICE_CONFIG_NORMAL;
251 switch (BROWSER_SHARED_RELRO_CONFIG) {
252 case BROWSER_SHARED_RELRO_CONFIG_NEVER:
253 sBrowserUsesSharedRelro = false;
255 case BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY:
256 sBrowserUsesSharedRelro =
257 (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW);
258 if (sBrowserUsesSharedRelro)
259 Log.w(TAG, "Low-memory device: shared RELROs used in all processes");
261 case BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
262 Log.w(TAG, "Beware: shared RELROs used in all processes!");
263 sBrowserUsesSharedRelro = true;
266 assert false : "Unreached";
270 if (DEBUG) Log.i(TAG, "Linker disabled");
273 if (!sRelroSharingSupported) {
275 sBrowserUsesSharedRelro = false;
276 sWaitForSharedRelros = false;
284 * A public interface used to run runtime linker tests after loading
285 * libraries. Should only be used to implement the linker unit tests,
286 * which is controlled by the value of NativeLibraries.sEnableLinkerTests
287 * configured at build time.
289 public interface TestRunner {
291 * Run runtime checks and return true if they all pass.
292 * @param memoryDeviceConfig The current memory device configuration.
293 * @param inBrowserProcess true iff this is the browser process.
295 public boolean runChecks(int memoryDeviceConfig, boolean inBrowserProcess);
298 // The name of a class that implements TestRunner.
299 static String sTestRunnerClassName = null;
302 * Set the TestRunner by its class name. It will be instantiated at
303 * runtime after all libraries are loaded.
304 * @param testRunnerClassName null or a String for the class name of the
307 public static void setTestRunnerClassName(String testRunnerClassName) {
308 if (DEBUG) Log.i(TAG, "setTestRunnerByClassName(" + testRunnerClassName + ") called");
310 if (!NativeLibraries.sEnableLinkerTests) {
311 // Ignore this in production code to prevent malvolent runtime injection.
315 synchronized (Linker.class) {
316 assert sTestRunnerClassName == null;
317 sTestRunnerClassName = testRunnerClassName;
322 * Call this to retrieve the name of the current TestRunner class name
323 * if any. This can be useful to pass it from the browser process to
325 * @return null or a String holding the name of the class implementing
326 * the TestRunner set by calling setTestRunnerClassName() previously.
328 public static String getTestRunnerClassName() {
329 synchronized (Linker.class) {
330 return sTestRunnerClassName;
335 * Call this method before any other Linker method to force a specific
336 * memory device configuration. Should only be used for testing.
337 * @param memoryDeviceConfig either MEMORY_DEVICE_CONFIG_LOW or MEMORY_DEVICE_CONFIG_NORMAL.
339 public static void setMemoryDeviceConfig(int memoryDeviceConfig) {
340 if (DEBUG) Log.i(TAG, "setMemoryDeviceConfig(" + memoryDeviceConfig + ") called");
341 // Sanity check. This method should only be called during tests.
342 assert NativeLibraries.sEnableLinkerTests;
343 synchronized (Linker.class) {
344 assert sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT;
345 assert memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW
346 || memoryDeviceConfig == MEMORY_DEVICE_CONFIG_NORMAL;
348 if (memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW)
349 Log.i(TAG, "Simulating a low-memory device");
351 Log.i(TAG, "Simulating a regular-memory device");
353 sMemoryDeviceConfig = memoryDeviceConfig;
358 * Call this method to determine if this chromium project must
359 * use this linker. If not, System.loadLibrary() should be used to load
362 public static boolean isUsed() {
363 // Only GYP targets that are APKs and have the 'use_chromium_linker' variable
364 // defined as 1 will use this linker. For all others (the default), the
365 // auto-generated NativeLibraries.sUseLinker variable will be false.
366 if (!NativeLibraries.sUseLinker)
369 synchronized (Linker.class) {
370 ensureInitializedLocked();
371 // At the moment, there is also no point in using this linker if the
372 // system does not support RELRO sharing safely.
373 return sRelroSharingSupported;
378 * Call this method to determine if the linker will try to use shared RELROs
379 * for the browser process.
381 public static boolean isUsingBrowserSharedRelros() {
382 synchronized (Linker.class) {
383 ensureInitializedLocked();
384 return sBrowserUsesSharedRelro;
389 * Call this method to determine if the chromium project must load
390 * the library directly from the zip file.
392 public static boolean isInZipFile() {
393 return NativeLibraries.sUseLibraryInZipFile;
397 * Call this method just before loading any native shared libraries in this process.
399 public static void prepareLibraryLoad() {
400 if (DEBUG) Log.i(TAG, "prepareLibraryLoad() called");
401 synchronized (Linker.class) {
402 sPrepareLibraryLoadCalled = true;
404 if (sInBrowserProcess) {
405 // Force generation of random base load address, as well
406 // as creation of shared RELRO sections in this process.
407 setupBaseLoadAddressLocked();
413 * Call this method just after loading all native shared libraries in this process.
414 * Note that when in a service process, this will block until the RELRO bundle is
415 * received, i.e. when another thread calls useSharedRelros().
417 public static void finishLibraryLoad() {
418 if (DEBUG) Log.i(TAG, "finishLibraryLoad() called");
419 synchronized (Linker.class) {
420 if (DEBUG) Log.i(TAG, String.format(
422 "sInBrowserProcess=%s sBrowserUsesSharedRelro=%s sWaitForSharedRelros=%s",
423 sInBrowserProcess ? "true" : "false",
424 sBrowserUsesSharedRelro ? "true" : "false",
425 sWaitForSharedRelros ? "true" : "false"));
427 if (sLoadedLibraries == null) {
428 if (DEBUG) Log.i(TAG, "No libraries loaded");
430 if (sInBrowserProcess) {
431 // Create new Bundle containing RELRO section information
432 // for all loaded libraries. Make it available to getSharedRelros().
433 sSharedRelros = createBundleFromLibInfoMap(sLoadedLibraries);
435 Log.i(TAG, "Shared RELRO created");
436 dumpBundle(sSharedRelros);
439 if (sBrowserUsesSharedRelro) {
440 useSharedRelrosLocked(sSharedRelros);
444 if (sWaitForSharedRelros) {
445 assert !sInBrowserProcess;
447 // Wait until the shared relro bundle is received from useSharedRelros().
448 while (sSharedRelros == null) {
451 } catch (InterruptedException ie) {
455 useSharedRelrosLocked(sSharedRelros);
456 // Clear the Bundle to ensure its file descriptor references can't be reused.
457 sSharedRelros.clear();
458 sSharedRelros = null;
462 if (NativeLibraries.sEnableLinkerTests && sTestRunnerClassName != null) {
463 // The TestRunner implementation must be instantiated _after_
464 // all libraries are loaded to ensure that its native methods
465 // are properly registered.
466 if (DEBUG) Log.i(TAG, "Instantiating " + sTestRunnerClassName);
467 TestRunner testRunner = null;
469 testRunner = (TestRunner)
470 Class.forName(sTestRunnerClassName).newInstance();
471 } catch (Exception e) {
472 Log.e(TAG, "Could not extract test runner class name", e);
475 if (testRunner != null) {
476 if (!testRunner.runChecks(sMemoryDeviceConfig, sInBrowserProcess)) {
477 Log.wtf(TAG, "Linker runtime tests failed in this process!!");
480 Log.i(TAG, "All linker tests passed!");
485 if (DEBUG) Log.i(TAG, "finishLibraryLoad() exiting");
489 * Call this to send a Bundle containing the shared RELRO sections to be
490 * used in this process. If initServiceProcess() was previously called,
491 * finishLibraryLoad() will not exit until this method is called in another
492 * thread with a non-null value.
493 * @param bundle The Bundle instance containing a map of shared RELRO sections
494 * to use in this process.
496 public static void useSharedRelros(Bundle bundle) {
497 // Ensure the bundle uses the application's class loader, not the framework
498 // one which doesn't know anything about LibInfo.
499 // Also, hold a fresh copy of it so the caller can't recycle it.
500 Bundle clonedBundle = null;
501 if (bundle != null) {
502 bundle.setClassLoader(LibInfo.class.getClassLoader());
503 clonedBundle = new Bundle(LibInfo.class.getClassLoader());
504 Parcel parcel = Parcel.obtain();
505 bundle.writeToParcel(parcel, 0);
506 parcel.setDataPosition(0);
507 clonedBundle.readFromParcel(parcel);
511 Log.i(TAG, "useSharedRelros() called with " + bundle
512 + ", cloned " + clonedBundle);
514 synchronized (Linker.class) {
515 // Note that in certain cases, this can be called before
516 // initServiceProcess() in service processes.
517 sSharedRelros = clonedBundle;
518 // Tell any listener blocked in finishLibraryLoad() about it.
519 Linker.class.notifyAll();
524 * Call this to retrieve the shared RELRO sections created in this process,
525 * after loading all libraries.
526 * @return a new Bundle instance, or null if RELRO sharing is disabled on
527 * this system, or if initServiceProcess() was called previously.
529 public static Bundle getSharedRelros() {
530 if (DEBUG) Log.i(TAG, "getSharedRelros() called");
531 synchronized (Linker.class) {
532 if (!sInBrowserProcess) {
533 if (DEBUG) Log.i(TAG, "... returning null Bundle");
537 // Return the Bundle created in finishLibraryLoad().
538 if (DEBUG) Log.i(TAG, "... returning " + sSharedRelros);
539 return sSharedRelros;
545 * Call this method before loading any libraries to indicate that this
546 * process shall neither create or reuse shared RELRO sections.
548 public static void disableSharedRelros() {
549 if (DEBUG) Log.i(TAG, "disableSharedRelros() called");
550 synchronized (Linker.class) {
551 sInBrowserProcess = false;
552 sWaitForSharedRelros = false;
553 sBrowserUsesSharedRelro = false;
558 * Call this method before loading any libraries to indicate that this
559 * process is ready to reuse shared RELRO sections from another one.
560 * Typically used when starting service processes.
561 * @param baseLoadAddress the base library load address to use.
563 public static void initServiceProcess(long baseLoadAddress) {
565 Log.i(TAG, String.format(
566 Locale.US, "initServiceProcess(0x%x) called", baseLoadAddress));
568 synchronized (Linker.class) {
569 ensureInitializedLocked();
570 sInBrowserProcess = false;
571 sBrowserUsesSharedRelro = false;
572 if (sRelroSharingSupported) {
573 sWaitForSharedRelros = true;
574 sBaseLoadAddress = baseLoadAddress;
575 sCurrentLoadAddress = baseLoadAddress;
581 * Retrieve the base load address of all shared RELRO sections.
582 * This also enforces the creation of shared RELRO sections in
583 * prepareLibraryLoad(), which can later be retrieved with getSharedRelros().
584 * @return a common, random base load address, or 0 if RELRO sharing is
587 public static long getBaseLoadAddress() {
588 synchronized (Linker.class) {
589 ensureInitializedLocked();
590 if (!sInBrowserProcess) {
591 Log.w(TAG, "Shared RELRO sections are disabled in this process!");
595 setupBaseLoadAddressLocked();
596 if (DEBUG) Log.i(TAG, String.format(Locale.US, "getBaseLoadAddress() returns 0x%x",
598 return sBaseLoadAddress;
602 // Used internally to lazily setup the common random base load address.
603 private static void setupBaseLoadAddressLocked() {
604 assert Thread.holdsLock(Linker.class);
605 if (sBaseLoadAddress == 0) {
606 long address = computeRandomBaseLoadAddress();
607 sBaseLoadAddress = address;
608 sCurrentLoadAddress = address;
610 // If the computed address is 0, there are issues with finding enough
611 // free address space, so disable RELRO shared / fixed load addresses.
612 Log.w(TAG, "Disabling shared RELROs due address space pressure");
613 sBrowserUsesSharedRelro = false;
614 sWaitForSharedRelros = false;
621 * Compute a random base load address at which to place loaded libraries.
622 * @return new base load address, or 0 if the system does not support
625 private static long computeRandomBaseLoadAddress() {
626 // nativeGetRandomBaseLoadAddress() returns an address at which it has previously
627 // successfully mapped an area of the given size, on the basis that we will be
628 // able, with high probability, to map our library into it.
630 // One issue with this is that we do not yet know the size of the library that
631 // we will load is. So here we pass a value that we expect will always be larger
632 // than that needed. If it is smaller the library mapping may still succeed. The
633 // other issue is that although highly unlikely, there is no guarantee that
634 // something else does not map into the area we are going to use between here and
635 // when we try to map into it.
637 // The above notes mean that all of this is probablistic. It is however okay to do
638 // because if, worst case and unlikely, we get unlucky in our choice of address,
639 // the back-out and retry without the shared RELRO in the ChildProcessService will
640 // keep things running.
641 final long maxExpectedBytes = 192 * 1024 * 1024;
642 final long address = nativeGetRandomBaseLoadAddress(maxExpectedBytes);
644 Log.i(TAG, 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 * Load a native shared library with the Chromium linker. If the zip file
704 * is not null, the shared library must be uncompressed and page aligned
705 * inside the zipfile. Note the crazy linker treats libraries and files as
706 * equivalent, so you can only open one library in a given zip file. The
707 * library must not be the Chromium linker library.
709 * @param zipFilePath The path of the zip file containing the library (or null).
710 * @param libFilePath The path of the library (possibly in the zip file).
712 public static void loadLibrary(@Nullable String zipFilePath, String libFilePath) {
713 if (DEBUG) Log.i(TAG, "loadLibrary: " + zipFilePath + ", " + libFilePath);
715 synchronized (Linker.class) {
716 ensureInitializedLocked();
718 // Security: Ensure prepareLibraryLoad() was called before.
719 // In theory, this can be done lazily here, but it's more consistent
720 // to use a pair of functions (i.e. prepareLibraryLoad() + finishLibraryLoad())
721 // that wrap all calls to loadLibrary() in the library loader.
722 assert sPrepareLibraryLoadCalled;
724 if (sLoadedLibraries == null) sLoadedLibraries = new HashMap<String, LibInfo>();
726 if (sLoadedLibraries.containsKey(libFilePath)) {
727 if (DEBUG) Log.i(TAG, "Not loading " + libFilePath + " twice");
731 LibInfo libInfo = new LibInfo();
732 long loadAddress = 0;
733 if ((sInBrowserProcess && sBrowserUsesSharedRelro) || sWaitForSharedRelros) {
734 // Load the library at a fixed address.
735 loadAddress = sCurrentLoadAddress;
738 String sharedRelRoName = libFilePath;
739 if (zipFilePath != null) {
740 if (!nativeLoadLibraryInZipFile(zipFilePath, libFilePath, loadAddress, libInfo)) {
741 String errorMessage = "Unable to load library: " + libFilePath
742 + ", in: " + zipFilePath;
743 Log.e(TAG, errorMessage);
744 throw new UnsatisfiedLinkError(errorMessage);
746 sharedRelRoName = zipFilePath;
748 if (!nativeLoadLibrary(libFilePath, loadAddress, libInfo)) {
749 String errorMessage = "Unable to load library: " + libFilePath;
750 Log.e(TAG, errorMessage);
751 throw new UnsatisfiedLinkError(errorMessage);
755 // Print the load address to the logcat when testing the linker. The format
756 // of the string is expected by the Python test_runner script as one of:
757 // BROWSER_LIBRARY_ADDRESS: <library-name> <address>
758 // RENDERER_LIBRARY_ADDRESS: <library-name> <address>
759 // Where <library-name> is the library name, and <address> is the hexadecimal load
761 if (NativeLibraries.sEnableLinkerTests) {
762 Log.i(TAG, String.format(
764 "%s_LIBRARY_ADDRESS: %s %x",
765 sInBrowserProcess ? "BROWSER" : "RENDERER",
767 libInfo.mLoadAddress));
770 if (sInBrowserProcess) {
771 // Create a new shared RELRO section at the 'current' fixed load address.
772 if (!nativeCreateSharedRelro(sharedRelRoName, sCurrentLoadAddress, libInfo)) {
773 Log.w(TAG, String.format(Locale.US,
774 "Could not create shared RELRO for %s at %x", libFilePath,
775 sCurrentLoadAddress));
777 if (DEBUG) Log.i(TAG,
780 "Created shared RELRO for %s at %x: %s",
783 libInfo.toString()));
787 if (sCurrentLoadAddress != 0) {
788 // Compute the next current load address. If sBaseLoadAddress
789 // is not 0, this is an explicit library load address. Otherwise,
790 // this is an explicit load address for relocated RELRO sections
792 sCurrentLoadAddress = libInfo.mLoadAddress + libInfo.mLoadSize;
795 sLoadedLibraries.put(sharedRelRoName, libInfo);
796 if (DEBUG) Log.i(TAG, "Library details " + libInfo.toString());
801 * Enable the fallback due to lack of support for mapping the APK file with
802 * executable permission (see crbug.com/398425).
804 public static void enableNoMapExecSupportFallback() {
805 synchronized (Linker.class) {
806 ensureInitializedLocked();
808 if (DEBUG) Log.i(TAG, "Enabling no map executable support fallback");
809 nativeEnableNoMapExecSupportFallback();
814 * Determine whether a library is the linker library. Also deal with the
815 * component build that adds a .cr suffix to the name.
817 public static boolean isChromiumLinkerLibrary(String library) {
818 return library.equals(TAG) || library.equals(TAG + ".cr");
822 * Get the full library path in zip file (lib/<abi>/crazy.<lib_name>).
824 * @param library The library's base name.
825 * @return the library path.
827 public static String getLibraryFilePathInZipFile(String library) throws FileNotFoundException {
828 synchronized (Linker.class) {
829 ensureInitializedLocked();
831 String path = nativeGetLibraryFilePathInZipFile(library);
832 if (path.equals("")) {
833 throw new FileNotFoundException(
834 "Failed to retrieve path in zip file for library " + library);
841 * Check whether the device supports mapping the APK file with executable permission.
843 * @param apkFile Filename of the APK.
844 * @return true if supported.
846 public static boolean checkMapExecSupport(String apkFile) {
847 assert apkFile != null;
848 synchronized (Linker.class) {
849 ensureInitializedLocked();
851 if (DEBUG) Log.i(TAG, "checkMapExecSupport: " + apkFile);
852 boolean supported = nativeCheckMapExecSupport(apkFile);
853 if (DEBUG) Log.i(TAG, "Mapping the APK file with executable permission "
854 + (supported ? "" : "NOT ") + "supported");
860 * Check whether a library is page aligned and uncompressed in the APK file.
862 * @param apkFile Filename of the APK.
863 * @param library The library's base name.
864 * @return true if page aligned and uncompressed.
866 public static boolean checkLibraryIsMappableInApk(String apkFile, String library) {
867 synchronized (Linker.class) {
868 ensureInitializedLocked();
870 if (DEBUG) Log.i(TAG, "checkLibraryIsMappableInApk: " + apkFile + ", " + library);
871 boolean aligned = nativeCheckLibraryIsMappableInApk(apkFile, library);
872 if (DEBUG) Log.i(TAG, library + " is " + (aligned ? "" : "NOT ")
873 + "page aligned in " + apkFile);
879 * Move activity from the native thread to the main UI thread.
880 * Called from native code on its own thread. Posts a callback from
881 * the UI thread back to native code.
883 * @param opaque Opaque argument.
886 public static void postCallbackOnMainThread(final long opaque) {
887 ThreadUtils.postOnUiThread(new Runnable() {
890 nativeRunCallbackOnUiThread(opaque);
896 * Native method to run callbacks on the main UI thread.
897 * Supplied by the crazy linker and called by postCallbackOnMainThread.
898 * @param opaque Opaque crazy linker arguments.
900 private static native void nativeRunCallbackOnUiThread(long opaque);
903 * Native method used to load a library.
904 * @param library Platform specific library name (e.g. libfoo.so)
905 * @param loadAddress Explicit load address, or 0 for randomized one.
906 * @param libInfo If not null, the mLoadAddress and mLoadSize fields
907 * of this LibInfo instance will set on success.
908 * @return true for success, false otherwise.
910 private static native boolean nativeLoadLibrary(String library,
915 * Native method used to load a library which is inside a zipfile.
916 * @param zipfileName Filename of the zip file containing the library.
917 * @param library Platform specific library name (e.g. libfoo.so)
918 * @param loadAddress Explicit load address, or 0 for randomized one.
919 * @param libInfo If not null, the mLoadAddress and mLoadSize fields
920 * of this LibInfo instance will set on success.
921 * @return true for success, false otherwise.
923 private static native boolean nativeLoadLibraryInZipFile(String zipfileName,
929 * Native method used to enable the fallback due to lack of support for
930 * mapping the APK file with executable permission.
932 private static native void nativeEnableNoMapExecSupportFallback();
935 * Native method used to create a shared RELRO section.
936 * If the library was already loaded at the same address using
937 * nativeLoadLibrary(), this creates the RELRO for it. Otherwise,
938 * this loads a new temporary library at the specified address,
939 * creates and extracts the RELRO section from it, then unloads it.
940 * @param library Library name.
941 * @param loadAddress load address, which can be different from the one
942 * used to load the library in the current process!
943 * @param libInfo libInfo instance. On success, the mRelroStart, mRelroSize
944 * and mRelroFd will be set.
945 * @return true on success, false otherwise.
947 private static native boolean nativeCreateSharedRelro(String library,
952 * Native method used to use a shared RELRO section.
953 * @param library Library name.
954 * @param libInfo A LibInfo instance containing valid RELRO information
955 * @return true on success.
957 private static native boolean nativeUseSharedRelro(String library,
961 * Checks that the system supports shared RELROs. Old Android kernels
962 * have a bug in the way they check Ashmem region protection flags, which
963 * makes using shared RELROs unsafe. This method performs a simple runtime
964 * check for this misfeature, even though nativeEnableSharedRelro() will
965 * always fail if this returns false.
967 private static native boolean nativeCanUseSharedRelro();
970 * Return a random address that should be free to be mapped with the given size.
971 * Maps an area of size bytes, and if successful then unmaps it and returns
972 * the address of the area allocated by the system (with ASLR). The idea is
973 * that this area should remain free of other mappings until we map our library
975 * @param sizeBytes Size of area in bytes to search for.
976 * @return address to pass to future mmap, or 0 on error.
978 private static native long nativeGetRandomBaseLoadAddress(long sizeBytes);
981 * Native method used to get the full library path in zip file
982 * (lib/<abi>/crazy.<lib_name>).
984 * @param library The library's base name.
985 * @return the library path (or empty string on failure).
987 private static native String nativeGetLibraryFilePathInZipFile(String library);
990 * Native method which checks whether the device supports mapping the APK file
991 * with executable permission.
993 * @param apkFile Filename of the APK.
994 * @return true if supported.
996 private static native boolean nativeCheckMapExecSupport(String apkFile);
999 * Native method which checks whether a library is page aligned and
1000 * uncompressed in the APK file.
1002 * @param apkFile Filename of the APK.
1003 * @param library The library's base name.
1004 * @return true if page aligned and uncompressed.
1006 private static native boolean nativeCheckLibraryIsMappableInApk(String apkFile, String library);
1009 * Record information for a given library.
1010 * IMPORTANT: Native code knows about this class's fields, so
1011 * don't change them without modifying the corresponding C++ sources.
1012 * Also, the LibInfo instance owns the ashmem file descriptor.
1014 public static class LibInfo implements Parcelable {
1024 public void close() {
1025 if (mRelroFd >= 0) {
1027 ParcelFileDescriptor.adoptFd(mRelroFd).close();
1028 } catch (java.io.IOException e) {
1029 if (DEBUG) Log.e(TAG, "Failed to close fd: " + mRelroFd);
1036 public LibInfo(Parcel in) {
1037 mLoadAddress = in.readLong();
1038 mLoadSize = in.readLong();
1039 mRelroStart = in.readLong();
1040 mRelroSize = in.readLong();
1041 ParcelFileDescriptor fd = in.readFileDescriptor();
1042 // If CreateSharedRelro fails, the OS file descriptor will be -1 and |fd| will be null.
1043 mRelroFd = (fd == null) ? -1 : fd.detachFd();
1048 public void writeToParcel(Parcel out, int flags) {
1049 if (mRelroFd >= 0) {
1050 out.writeLong(mLoadAddress);
1051 out.writeLong(mLoadSize);
1052 out.writeLong(mRelroStart);
1053 out.writeLong(mRelroSize);
1055 ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd);
1056 fd.writeToParcel(out, 0);
1058 } catch (java.io.IOException e) {
1059 Log.e(TAG, "Cant' write LibInfo file descriptor to parcel", e);
1066 public int describeContents() {
1067 return Parcelable.CONTENTS_FILE_DESCRIPTOR;
1071 public static final Parcelable.Creator<LibInfo> CREATOR =
1072 new Parcelable.Creator<LibInfo>() {
1074 public LibInfo createFromParcel(Parcel in) {
1075 return new LibInfo(in);
1079 public LibInfo[] newArray(int size) {
1080 return new LibInfo[size];
1085 public String toString() {
1086 return String.format(Locale.US,
1087 "[load=0x%x-0x%x relro=0x%x-0x%x fd=%d]",
1089 mLoadAddress + mLoadSize,
1091 mRelroStart + mRelroSize,
1095 // IMPORTANT: Don't change these fields without modifying the
1096 // native code that accesses them directly!
1098 public long mLoadAddress; // page-aligned library load address.
1100 public long mLoadSize; // page-aligned library load size.
1102 public long mRelroStart; // page-aligned address in memory, or 0 if none.
1104 public long mRelroSize; // page-aligned size in memory, or 0.
1106 public int mRelroFd; // ashmem file descriptor, or -1
1109 // Create a Bundle from a map of LibInfo objects.
1110 private static Bundle createBundleFromLibInfoMap(HashMap<String, LibInfo> map) {
1111 Bundle bundle = new Bundle(map.size());
1112 for (Map.Entry<String, LibInfo> entry : map.entrySet()) {
1113 bundle.putParcelable(entry.getKey(), entry.getValue());
1119 // Create a new LibInfo map from a Bundle.
1120 private static HashMap<String, LibInfo> createLibInfoMapFromBundle(Bundle bundle) {
1121 HashMap<String, LibInfo> map = new HashMap<String, LibInfo>();
1122 for (String library : bundle.keySet()) {
1123 LibInfo libInfo = bundle.getParcelable(library);
1124 map.put(library, libInfo);
1129 // Call the close() method on all values of a LibInfo map.
1130 private static void closeLibInfoMap(HashMap<String, LibInfo> map) {
1131 for (Map.Entry<String, LibInfo> entry : map.entrySet()) {
1132 entry.getValue().close();
1136 // The map of libraries that are currently loaded in this process.
1137 private static HashMap<String, LibInfo> sLoadedLibraries = null;
1139 // Used to pass the shared RELRO Bundle through Binder.
1140 public static final String EXTRA_LINKER_SHARED_RELROS =
1141 "org.chromium.base.android.linker.shared_relros";