Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / base / android / java / src / org / chromium / base / library_loader / Linker.java
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.
4
5 package org.chromium.base.library_loader;
6
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;
12
13 import org.chromium.base.SysUtils;
14 import org.chromium.base.ThreadUtils;
15
16 import java.io.File;
17 import java.io.FileInputStream;
18 import java.util.HashMap;
19 import java.util.Locale;
20 import java.util.Map;
21
22 import javax.annotation.Nullable;
23
24 /*
25  * Technical note:
26  *
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
30  * processes.
31  *
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].
35  *
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
38  * Android).
39  *
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.
43  *
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.
47  *
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.
52  *
53  * [1] The exceptions are pointers to external, randomized, symbols, like
54  * those from some system libraries, but these are very few in practice.
55  */
56
57 /*
58  * Security considerations:
59  *
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.
63  *
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.
67  *
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.
72  *
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)
78  *
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.
83  *
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.
87  *
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
92  *   library per APK.
93  */
94
95 /**
96  * Here's an explanation of how this class is supposed to be used:
97  *
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).
101  *
102  *  - Before loading any library, prepareLibraryLoad() should be called.
103  *
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).
107  *
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.
113  *
114  *    disableSharedRelros() completely disables shared RELROs, and loadLibrary()
115  *    will behave exactly like System.loadLibrary().
116  *
117  *    initServiceProcess(baseLoadAddress) indicates that shared RELROs are to be
118  *    used in this process.
119  *
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).
123  *
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
126  *    will:
127  *
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.
133  *
134  *    Note that these shared RELRO regions cannot be used inside the browser
135  *    process. They are also never mapped into it.
136  *
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.
140  *
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.
144  *
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).
148  *
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.
152  *
153  *    This method also ensures the process uses the shared RELROs.
154  */
155 public class Linker {
156
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";
159
160     // Set to true to enable debug logs.
161     private static final boolean DEBUG = false;
162
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;
172
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;
178
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;
186
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;
191
192     // Becomes true after linker initialization.
193     private static boolean sInitialized = false;
194
195     // Set to true to indicate that the system supports safe sharing of RELRO sections.
196     private static boolean sRelroSharingSupported = false;
197
198     // Set to true if this runs in the browser process. Disabled by initServiceProcess().
199     private static boolean sInBrowserProcess = true;
200
201     // Becomes true to indicate this process needs to wait for a shared RELRO in
202     // finishLibraryLoad().
203     private static boolean sWaitForSharedRelros = false;
204
205     // Becomes true when initialization determines that the browser process can use the
206     // shared RELRO.
207     private static boolean sBrowserUsesSharedRelro = false;
208
209     // The map of all RELRO sections either created or used in this process.
210     private static Bundle sSharedRelros = null;
211
212     // Current common random base load address.
213     private static long sBaseLoadAddress = 0;
214
215     // Current fixed-location load address for the next library called by loadLibrary().
216     private static long sCurrentLoadAddress = 0;
217
218     // Becomes true if any library fails to load at a given, non-0, fixed address.
219     private static boolean sLoadAtFixedAddressFailed = false;
220
221     // Becomes true once prepareLibraryLoad() has been called.
222     private static boolean sPrepareLibraryLoadCalled = false;
223
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);
227
228         if (!sInitialized) {
229             sRelroSharingSupported = false;
230             if (NativeLibraries.USE_LINKER) {
231                 if (DEBUG) Log.i(TAG, "Loading lib" + TAG + ".so");
232                 try {
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");
237                 }
238                 sRelroSharingSupported = nativeCanUseSharedRelro();
239                 if (!sRelroSharingSupported)
240                     Log.w(TAG, "This system cannot safely share RELRO sections");
241                 else {
242                     if (DEBUG) Log.i(TAG, "This system supports safe shared RELRO sections");
243                 }
244
245                 if (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT) {
246                     sMemoryDeviceConfig = SysUtils.isLowEndDevice() ?
247                             MEMORY_DEVICE_CONFIG_LOW : MEMORY_DEVICE_CONFIG_NORMAL;
248                 }
249
250                 switch (BROWSER_SHARED_RELRO_CONFIG) {
251                     case BROWSER_SHARED_RELRO_CONFIG_NEVER:
252                         sBrowserUsesSharedRelro = false;
253                         break;
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");
259                         break;
260                     case BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
261                         Log.w(TAG, "Beware: shared RELROs used in all processes!");
262                         sBrowserUsesSharedRelro = true;
263                         break;
264                     default:
265                         assert false : "Unreached";
266                         break;
267                 }
268             } else {
269                 if (DEBUG) Log.i(TAG, "Linker disabled");
270             }
271
272             if (!sRelroSharingSupported) {
273                 // Sanity.
274                 sBrowserUsesSharedRelro = false;
275                 sWaitForSharedRelros = false;
276             }
277
278             sInitialized = true;
279         }
280     }
281
282     /**
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.
287      */
288     public interface TestRunner {
289         /**
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.
293          */
294         public boolean runChecks(int memoryDeviceConfig, boolean inBrowserProcess);
295     }
296
297     // The name of a class that implements TestRunner.
298     static String sTestRunnerClassName = null;
299
300     /**
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
304      * TestRunner to use.
305      */
306     public static void setTestRunnerClassName(String testRunnerClassName) {
307         if (DEBUG) Log.i(TAG, "setTestRunnerByClassName(" + testRunnerClassName + ") called");
308
309         if (!NativeLibraries.ENABLE_LINKER_TESTS) {
310             // Ignore this in production code to prevent malvolent runtime injection.
311             return;
312         }
313
314         synchronized (Linker.class) {
315             assert sTestRunnerClassName == null;
316             sTestRunnerClassName = testRunnerClassName;
317         }
318     }
319
320     /**
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
323      * child ones.
324      * @return null or a String holding the name of the class implementing
325      * the TestRunner set by calling setTestRunnerClassName() previously.
326      */
327     public static String getTestRunnerClassName() {
328         synchronized (Linker.class) {
329             return sTestRunnerClassName;
330         }
331     }
332
333     /**
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.
337      */
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;
346             if (DEBUG) {
347                 if (memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW)
348                     Log.i(TAG, "Simulating a low-memory device");
349                 else
350                     Log.i(TAG, "Simulating a regular-memory device");
351             }
352             sMemoryDeviceConfig = memoryDeviceConfig;
353         }
354     }
355
356     /**
357      * Call this method to determine if this chromium project must
358      * use this linker. If not, System.loadLibrary() should be used to load
359      * libraries instead.
360      */
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)
366             return false;
367
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;
373         }
374     }
375
376     /**
377      * Call this method to determine if the chromium project must load
378      * the library directly from the zip file.
379      */
380     public static boolean isInZipFile() {
381         return NativeLibraries.USE_LIBRARY_IN_ZIP_FILE;
382     }
383
384     /**
385      * Call this method just before loading any native shared libraries in this process.
386      */
387     public static void prepareLibraryLoad() {
388         if (DEBUG) Log.i(TAG, "prepareLibraryLoad() called");
389         synchronized (Linker.class) {
390             sPrepareLibraryLoadCalled = true;
391
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();
396             }
397         }
398     }
399
400     /**
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().
404      */
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(
409                     Locale.US,
410                     "sInBrowserProcess=%s sBrowserUsesSharedRelro=%s sWaitForSharedRelros=%s",
411                     sInBrowserProcess ? "true" : "false",
412                     sBrowserUsesSharedRelro ? "true" : "false",
413                     sWaitForSharedRelros ? "true" : "false"));
414
415             if (sLoadedLibraries == null) {
416                 if (DEBUG) Log.i(TAG, "No libraries loaded");
417             } else {
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);
422                     if (DEBUG) {
423                         Log.i(TAG, "Shared RELRO created");
424                         dumpBundle(sSharedRelros);
425                     }
426
427                     if (sBrowserUsesSharedRelro) {
428                         useSharedRelrosLocked(sSharedRelros);
429                     }
430                 }
431
432                 if (sWaitForSharedRelros) {
433                     assert !sInBrowserProcess;
434
435                     // Wait until the shared relro bundle is received from useSharedRelros().
436                     while (sSharedRelros == null) {
437                         try {
438                             Linker.class.wait();
439                         } catch (InterruptedException ie) {
440                             // no-op
441                         }
442                     }
443                     useSharedRelrosLocked(sSharedRelros);
444                     // Clear the Bundle to ensure its file descriptor references can't be reused.
445                     sSharedRelros.clear();
446                     sSharedRelros = null;
447                 }
448             }
449
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;
456                 try {
457                     testRunner = (TestRunner)
458                             Class.forName(sTestRunnerClassName).newInstance();
459                 } catch (Exception e) {
460                     Log.e(TAG, "Could not extract test runner class name", e);
461                     testRunner = null;
462                 }
463                 if (testRunner != null) {
464                     if (!testRunner.runChecks(sMemoryDeviceConfig, sInBrowserProcess)) {
465                         Log.wtf(TAG, "Linker runtime tests failed in this process!!");
466                         assert false;
467                     } else {
468                         Log.i(TAG, "All linker tests passed!");
469                     }
470                 }
471             }
472         }
473         if (DEBUG) Log.i(TAG, "finishLibraryLoad() exiting");
474     }
475
476     /**
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.
483      */
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);
496             parcel.recycle();
497         }
498         if (DEBUG) {
499             Log.i(TAG, "useSharedRelros() called with " + bundle +
500                     ", cloned " + clonedBundle);
501         }
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();
508         }
509     }
510
511     /**
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.
516      */
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");
522                 return null;
523             }
524
525             // Return the Bundle created in finishLibraryLoad().
526             if (DEBUG) Log.i(TAG, "... returning " + sSharedRelros);
527             return sSharedRelros;
528         }
529     }
530
531
532     /**
533      * Call this method before loading any libraries to indicate that this
534      * process shall neither create or reuse shared RELRO sections.
535      */
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;
542         }
543     }
544
545     /**
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.
550      */
551     public static void initServiceProcess(long baseLoadAddress) {
552         if (DEBUG) {
553             Log.i(TAG, String.format(
554                     Locale.US, "initServiceProcess(0x%x) called", baseLoadAddress));
555         }
556         synchronized (Linker.class) {
557             ensureInitializedLocked();
558             sInBrowserProcess = false;
559             sBrowserUsesSharedRelro = false;
560             if (sRelroSharingSupported) {
561                 sWaitForSharedRelros = true;
562                 sBaseLoadAddress = baseLoadAddress;
563                 sCurrentLoadAddress = baseLoadAddress;
564             }
565         }
566     }
567
568     /**
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
573      * disabled.
574      */
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!");
580                 return 0;
581             }
582
583             setupBaseLoadAddressLocked();
584             if (DEBUG) Log.i(TAG, String.format(Locale.US, "getBaseLoadAddress() returns 0x%x",
585                                                 sBaseLoadAddress));
586             return sBaseLoadAddress;
587         }
588     }
589
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;
597             if (address == 0) {
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;
603             }
604         }
605     }
606
607
608     /**
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
611      * RELRO sharing.
612      */
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;
618
619         // Start loading libraries from this base address.
620         final long baseAddress = 0x20000000;
621
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;
625
626         // The maximum limit of the desired random offset.
627         final long pageSize = nativeGetPageSize();
628         final int offsetLimit = (int) ((baseAddressMax - baseAddress) / pageSize);
629
630         // Get the greatest power of 2 that is smaller or equal to offsetLimit.
631         int numBits = 30;
632         for (; numBits > 1; numBits--) {
633             if ((1 << numBits) <= offsetLimit)
634                 break;
635         }
636
637         if (DEBUG) {
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));
641         }
642
643         // Find a random offset between 0 and (2^numBits - 1), included.
644         int offset = getRandomBits(numBits);
645         long address = 0;
646         if (offset >= 0)
647             address = baseAddress + offset * pageSize;
648
649         if (DEBUG) {
650             Log.i(TAG,
651                   String.format(Locale.US, "Linker.computeRandomBaseLoadAddress() return 0x%x",
652                                 address));
653         }
654         return address;
655     }
656
657     /**
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).
662      */
663     private static int getRandomBits(int numBits) {
664         // Sanity check.
665         assert numBits > 0;
666         assert numBits < 32;
667
668         FileInputStream input;
669         try {
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);
676             return -1;
677         }
678
679         int result = 0;
680         try {
681             for (int n = 0; n < 4; n++) {
682                 result = (result << 8) | (input.read() & 255);
683             }
684         } catch (Exception e) {
685             Log.e(TAG, "Could not read /dev/urandom", e);
686             return -1;
687         } finally {
688             try {
689                 input.close();
690             } catch (Exception e) {
691                 // Can't really do anything here.
692             }
693         }
694         result &= (1 << numBits) - 1;
695
696         if (DEBUG) {
697             Log.i(TAG, String.format(
698                     Locale.US, "getRandomBits(%d) returned %d", numBits, result));
699         }
700
701         return result;
702     }
703
704     // Used for debugging only.
705     private static void dumpBundle(Bundle bundle) {
706         if (DEBUG) Log.i(TAG, "Bundle has " + bundle.size() + " items: " + bundle);
707     }
708
709     /**
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
714      * another process.
715      */
716     private static void useSharedRelrosLocked(Bundle bundle) {
717         assert Thread.holdsLock(Linker.class);
718
719         if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() called");
720
721         if (bundle == null) {
722             if (DEBUG) Log.i(TAG, "null bundle!");
723             return;
724         }
725
726         if (!sRelroSharingSupported) {
727             if (DEBUG) Log.i(TAG, "System does not support RELRO sharing");
728             return;
729         }
730
731         if (sLoadedLibraries == null) {
732             if (DEBUG) Log.i(TAG, "No libraries loaded!");
733             return;
734         }
735
736         if (DEBUG) dumpBundle(bundle);
737         HashMap<String, LibInfo> relroMap = createLibInfoMapFromBundle(bundle);
738
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);
745             } else {
746                 if (DEBUG) Log.i(TAG, "Using shared RELRO section for " + libName);
747             }
748         }
749
750         // In service processes, close all file descriptors from the map now.
751         if (!sInBrowserProcess)
752             closeLibInfoMap(relroMap);
753
754         if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() exiting");
755     }
756
757     /**
758      * Returns whether the linker was unable to load one library at a given fixed address.
759      *
760      * @return true if at least one library was not loaded at the expected fixed address.
761      */
762     public static boolean loadAtFixedAddressFailed() {
763         return sLoadAtFixedAddressFailed;
764     }
765
766     /**
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.
771      *
772      * @param zipfile The filename of the zipfile contain the library.
773      * @param library The library's base name.
774      */
775     public static void loadLibraryInZipFile(String zipfile, String library) {
776         loadLibraryMaybeInZipFile(zipfile, library);
777     }
778
779     /**
780      * Load a native shared library with the Chromium linker.
781      *
782      * @param library The library's base name.
783      */
784     public static void loadLibrary(String library) {
785         loadLibraryMaybeInZipFile(null, library);
786     }
787
788     private static void loadLibraryMaybeInZipFile(
789             @Nullable String zipFile, String library) {
790         if (DEBUG) Log.i(TAG, "loadLibrary: " + library);
791
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");
798             return;
799         }
800
801         synchronized (Linker.class) {
802             ensureInitializedLocked();
803
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;
809
810             String libName = System.mapLibraryName(library);
811
812             if (sLoadedLibraries == null)
813               sLoadedLibraries = new HashMap<String, LibInfo>();
814
815             if (sLoadedLibraries.containsKey(libName)) {
816                 if (DEBUG) Log.i(TAG, "Not loading " + libName + " twice");
817                 return;
818             }
819
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;
825             }
826
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: " +
833                             zipFile;
834                     Log.e(TAG, errorMessage);
835                     throw new UnsatisfiedLinkError(errorMessage);
836                 }
837                 sharedRelRoName = zipFile;
838             } else {
839                 if (!nativeLoadLibrary(libName, loadAddress, libInfo)) {
840                     String errorMessage = "Unable to load library: " + libName;
841                     Log.e(TAG, errorMessage);
842                     throw new UnsatisfiedLinkError(errorMessage);
843                 }
844             }
845             // Keep track whether the library has been loaded at the expected load address.
846             if (loadAddress != 0 && loadAddress != libInfo.mLoadAddress)
847                 sLoadAtFixedAddressFailed = true;
848
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
854             // address.
855             if (NativeLibraries.ENABLE_LINKER_TESTS) {
856                 Log.i(TAG, String.format(
857                         Locale.US,
858                         "%s_LIBRARY_ADDRESS: %s %x",
859                         sInBrowserProcess ? "BROWSER" : "RENDERER",
860                         libName,
861                         libInfo.mLoadAddress));
862             }
863
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));
870                 } else {
871                     if (DEBUG) Log.i(TAG,
872                         String.format(
873                             Locale.US,
874                             "Created shared RELRO for %s at %x: %s",
875                             sharedRelRoName,
876                             sCurrentLoadAddress,
877                             libInfo.toString()));
878                 }
879             }
880
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
885                 // only.
886                 sCurrentLoadAddress = libInfo.mLoadAddress + libInfo.mLoadSize;
887             }
888
889             sLoadedLibraries.put(libName, libInfo);
890             if (DEBUG) Log.i(TAG, "Library details " + libInfo.toString());
891         }
892     }
893
894     /**
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.
898      *
899      * @param opaque Opaque argument.
900      */
901     public static void postCallbackOnMainThread(final long opaque) {
902         ThreadUtils.postOnUiThread(new Runnable() {
903             @Override
904             public void run() {
905                 nativeRunCallbackOnUiThread(opaque);
906             }
907         });
908     }
909
910     /**
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.
914      */
915     private static native void nativeRunCallbackOnUiThread(long opaque);
916
917     /**
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.
924      */
925     private static native boolean nativeLoadLibrary(String library,
926                                                     long loadAddress,
927                                                     LibInfo libInfo);
928
929     /**
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.
937      */
938     private static native boolean nativeLoadLibraryInZipFile(
939         String zipfileName,
940         String libraryName,
941         long loadAddress,
942         LibInfo libInfo);
943
944     /**
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.
956      */
957     private static native boolean nativeCreateSharedRelro(String library,
958                                                           long loadAddress,
959                                                           LibInfo libInfo);
960
961     /**
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.
966      */
967     private static native boolean nativeUseSharedRelro(String library,
968                                                        LibInfo libInfo);
969
970     /**
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.
976      */
977     private static native boolean nativeCanUseSharedRelro();
978
979     // Returns the native page size in bytes.
980     private static native long nativeGetPageSize();
981
982     /**
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.
987      */
988     public static class LibInfo implements Parcelable {
989
990         public LibInfo() {
991             mLoadAddress = 0;
992             mLoadSize = 0;
993             mRelroStart = 0;
994             mRelroSize = 0;
995             mRelroFd = -1;
996         }
997
998         public void close() {
999             if (mRelroFd >= 0) {
1000                 try {
1001                     ParcelFileDescriptor.adoptFd(mRelroFd).close();
1002                 } catch (java.io.IOException e) {
1003                     if (DEBUG) Log.e(TAG, "Failed to close fd: " + mRelroFd);
1004                 }
1005                 mRelroFd = -1;
1006             }
1007         }
1008
1009         // from Parcelable
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();
1017         }
1018
1019         // from Parcelable
1020         @Override
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);
1027                 try {
1028                     ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd);
1029                     fd.writeToParcel(out, 0);
1030                     fd.close();
1031                 } catch (java.io.IOException e) {
1032                     Log.e(TAG, "Cant' write LibInfo file descriptor to parcel", e);
1033                 }
1034             }
1035         }
1036
1037         // from Parcelable
1038         @Override
1039         public int describeContents() {
1040             return Parcelable.CONTENTS_FILE_DESCRIPTOR;
1041         }
1042
1043         // from Parcelable
1044         public static final Parcelable.Creator<LibInfo> CREATOR =
1045                 new Parcelable.Creator<LibInfo>() {
1046                     @Override
1047                     public LibInfo createFromParcel(Parcel in) {
1048                         return new LibInfo(in);
1049                     }
1050
1051                     @Override
1052                     public LibInfo[] newArray(int size) {
1053                         return new LibInfo[size];
1054                     }
1055                 };
1056
1057         @Override
1058         public String toString() {
1059             return String.format(Locale.US,
1060                                  "[load=0x%x-0x%x relro=0x%x-0x%x fd=%d]",
1061                                  mLoadAddress,
1062                                  mLoadAddress + mLoadSize,
1063                                  mRelroStart,
1064                                  mRelroStart + mRelroSize,
1065                                  mRelroFd);
1066         }
1067
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
1075     }
1076
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());
1082         }
1083
1084         return bundle;
1085     }
1086
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);
1093         }
1094         return map;
1095     }
1096
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();
1101         }
1102     }
1103
1104     // The map of libraries that are currently loaded in this process.
1105     private static HashMap<String, LibInfo> sLoadedLibraries = null;
1106
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";
1110 }