- add sources.
[platform/framework/web/crosswalk.git] / src / content / public / android / java / src / org / chromium / content / app / Linker.java
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 package org.chromium.content.app;
6
7 import java.io.File;
8 import java.io.FileInputStream;
9
10 import java.util.HashMap;
11 import java.util.Map;
12 import java.util.Set;
13
14 import android.content.Context;
15 import android.os.Bundle;
16 import android.os.Parcel;
17 import android.os.Parcelable;
18 import android.os.ParcelFileDescriptor;
19 import android.util.Log;
20
21 /*
22  * Technical note:
23  *
24  * The point of this class is to provide an alternative to System.loadLibrary()
25  * to load native shared libraries. One specific feature that it supports is the
26  * ability to save RAM by sharing the ELF RELRO sections between renderer
27  * processes.
28  *
29  * When two processes load the same native library at the _same_ memory address,
30  * the content of their RELRO section (which includes C++ vtables or any
31  * constants that contain pointers) will be largely identical [1].
32  *
33  * By default, the RELRO section is backed by private RAM in each process,
34  * which is still significant on mobile (e.g. 1.28 MB / process on Chrome 30 for
35  * Android).
36  *
37  * However, it is possible to save RAM by creating a shared memory region,
38  * copy the RELRO content into it, then have each process swap its private,
39  * regular RELRO, with a shared, read-only, mapping of the shared one.
40  *
41  * This trick saves 98% of the RELRO section size per extra process, after the
42  * first one. On the other hand, this requires careful communication between
43  * the process where the shared RELRO is created and the one(s) where it is used.
44  *
45  * Note that swapping the regular RELRO with the shared one is not an atomic
46  * operation. Care must be taken that no other thread tries to run native code
47  * that accesses it during it. In practice, this means the swap must happen
48  * before library native code is executed.
49  *
50  * [1] The exceptions are pointers to external, randomized, symbols, like
51  * those from some system libraries, but these are very few in practice.
52  */
53
54 /*
55  * Security considerations:
56  *
57  * - Whether the browser process loads its native libraries at the same
58  *   addresses as the service ones (to save RAM by sharing the RELRO too)
59  *   depends on the configuration variable BROWSER_SHARED_RELRO_CONFIG below.
60  *
61  *   Not using fixed library addresses in the browser process is preferred
62  *   for regular devices since it maintains the efficacy of ASLR as an
63  *   exploit mitigation across the render <-> browser privilege boundary.
64  *
65  * - The shared RELRO memory region is always forced read-only after creation,
66  *   which means it is impossible for a compromised service process to map
67  *   it read-write (e.g. by calling mmap() or mprotect()) and modify its
68  *   content, altering values seen in other service processes.
69  *
70  * - Unfortunately, certain Android systems use an old, buggy kernel, that
71  *   doesn't check Ashmem region permissions correctly. See CVE-2011-1149
72  *   for details. This linker probes the system on startup and will completely
73  *   disable shared RELROs if it detects the problem. For the record, this is
74  *   common for Android emulator system images (which are still based on 2.6.29)
75  *
76  * - Once the RELRO ashmem region is mapped into a service process' address
77  *   space, the corresponding file descriptor is immediately closed. The
78  *   file descriptor is kept opened in the browser process, because a copy needs
79  *   to be sent to each new potential service process.
80  *
81  * - The common library load addresses are randomized for each instance of
82  *   the program on the device. See computeRandomBaseLoadAddress() for more
83  *   details on how this is computed.
84  *
85  * - When loading several libraries in service processes, a simple incremental
86  *   approach from the original random base load address is used. This is
87  *   sufficient to deal correctly with component builds (which can use dozens
88  *   of shared libraries), while regular builds always embed a single shared
89  *   library per APK.
90  */
91
92 /*
93  * Here's an explanation of how this class is supposed to be used:
94  *
95  *  - Native shared libraries should be loaded with Linker.loadLibrary(),
96  *    instead of System.loadLibrary(). The two functions take the same parameter
97  *    and should behave the same (at a high level).
98  *
99  *  - Before loading any library, prepareLibraryLoad() should be called.
100  *
101  *  - After loading all libraries, finishLibraryLoad() should be called, before
102  *    running any native code from any of the libraries (except their static
103  *    constructors, which can't be avoided).
104  *
105  *  - A service process shall call either initServiceProcess() or
106  *    disableSharedRelros() early (i.e. before any loadLibrary() call).
107  *    Otherwise, the linker considers that it is running inside the browser
108  *    process. This is because various content-based projects have vastly
109  *    different initialization paths.
110  *
111  *    disableSharedRelros() completely disables shared RELROs, and loadLibrary()
112  *    will behave exactly like System.loadLibrary().
113  *
114  *    initServiceProcess(baseLoadAddress) indicates that shared RELROs are to be
115  *    used in this process.
116  *
117  *  - The browser is in charge of deciding where in memory each library should
118  *    be loaded. This address must be passed to each service process (see
119  *    LinkerParams.java for a helper class to do so).
120  *
121  *  - The browser will also generate shared RELROs for each library it loads.
122  *    More specifically, by default when in the browser process, the linker
123  *    will:
124  *
125  *       - Load libraries randomly (just like System.loadLibrary()).
126  *       - Compute the fixed address to be used to load the same library
127  *         in service processes.
128  *       - Create a shared memory region populated with the RELRO region
129  *         content pre-relocated for the specific fixed address above.
130  *
131  *    Note that these shared RELRO regions cannot be used inside the browser
132  *    process. They are also never mapped into it.
133  *
134  *    This behaviour is altered by the BROWSER_SHARED_RELRO_CONFIG configuration
135  *    variable below, which may force the browser to load the libraries at
136  *    fixed addresses to.
137  *
138  *  - Once all libraries are loaded in the browser process, one can call
139  *    getSharedRelros() which returns a Bundle instance containing a map that
140  *    links each loaded library to its shared RELRO region.
141  *
142  *    This Bundle must be passed to each service process, for example through
143  *    a Binder call (note that the Bundle includes file descriptors and cannot
144  *    be added as an Intent extra).
145  *
146  *  - In a service process, finishLibraryLoad() will block until the RELRO
147  *    section Bundle is received. This is typically done by calling
148  *    useSharedRelros() from another thread.
149  *
150  *    This method also ensures the process uses the shared RELROs.
151  */
152 public class Linker {
153
154     // Log tag for this class. This must match the name of the linker's native library.
155     private static final String TAG = "content_android_linker";
156
157     // Set to true to enable debug logs.
158     private static final boolean DEBUG = false;
159
160     // Constants used to control the behaviour of the browser process with
161     // regards to the shared RELRO section.
162     //   NEVER        -> The browser never uses it itself.
163     //   LOW_RAM_ONLY -> It is only used on devices with low RAM.
164     //   ALWAYS       -> It is always used.
165     // NOTE: These names are known and expected by the Linker test scripts.
166     public static final int BROWSER_SHARED_RELRO_CONFIG_NEVER = 0;
167     public static final int BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY = 1;
168     public static final int BROWSER_SHARED_RELRO_CONFIG_ALWAYS = 2;
169
170     // Configuration variable used to control how the browser process uses the
171     // shared RELRO. Only change this while debugging linker-related issues.
172     // NOTE: This variable's name is known and expected by the Linker test scripts.
173     public static final int BROWSER_SHARED_RELRO_CONFIG =
174             BROWSER_SHARED_RELRO_CONFIG_ALWAYS;
175
176     // Constants used to control the value of sMemoryDeviceConfig.
177     //   INIT         -> Value is undetermined (will check at runtime).
178     //   LOW          -> This is a low-memory device.
179     //   NORMAL       -> This is not a low-memory device.
180     public static final int MEMORY_DEVICE_CONFIG_INIT = 0;
181     public static final int MEMORY_DEVICE_CONFIG_LOW = 1;
182     public static final int MEMORY_DEVICE_CONFIG_NORMAL = 2;
183
184     // Indicates if this is a low-memory device or not. The default is to
185     // determine this by probing the system at runtime, but this can be forced
186     // for testing by calling setMemoryDeviceConfig().
187     private static int sMemoryDeviceConfig = MEMORY_DEVICE_CONFIG_INIT;
188
189     // Becomes true after linker initialization.
190     private static boolean sInitialized = false;
191
192     // Set to true to indicate that the system supports safe sharing of RELRO sections.
193     private static boolean sRelroSharingSupported = false;
194
195     // Set to true if this runs in the browser process. Disabled by initServiceProcess().
196     private static boolean sInBrowserProcess = true;
197
198     // Becomes true to indicate this process needs to wait for a shared RELRO in
199     // finishLibraryLoad().
200     private static boolean sWaitForSharedRelros = false;
201
202     // Becomes true when initialization determines that the browser process can use the
203     // shared RELRO.
204     private static boolean sBrowserUsesSharedRelro = false;
205
206     // The map of all RELRO sections either created or used in this process.
207     private static Bundle sSharedRelros = null;
208
209     // Current common random base load address.
210     private static long sBaseLoadAddress = 0;
211
212     // Current fixed-location load address for the next library called by loadLibrary().
213     private static long sCurrentLoadAddress = 0;
214
215     // Becomes true if any library fails to load at a given, non-0, fixed address.
216     private static boolean sLoadAtFixedAddressFailed = false;
217
218     // Becomes true once prepareLibraryLoad() has been called.
219     private static boolean sPrepareLibraryLoadCalled = false;
220
221     // Used internally to initialize the linker's static data. Assume lock is held.
222     private static void ensureInitializedLocked() {
223         assert Thread.holdsLock(Linker.class);
224
225         if (!sInitialized) {
226             sRelroSharingSupported = false;
227             if (NativeLibraries.USE_LINKER) {
228                 if (DEBUG) Log.i(TAG, "Loading lib" + TAG + ".so");
229                 try {
230                     System.loadLibrary(TAG);
231                 } catch (UnsatisfiedLinkError  e) {
232                     // In a component build, the ".cr" suffix is added to each library name.
233                     System.loadLibrary(TAG + ".cr");
234                 }
235                 sRelroSharingSupported = nativeCanUseSharedRelro();
236                 if (!sRelroSharingSupported)
237                     Log.w(TAG, "This system cannot safely share RELRO sections");
238                 else {
239                     if (DEBUG) Log.i(TAG, "This system supports safe shared RELRO sections");
240                 }
241
242                 if (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT) {
243                     sMemoryDeviceConfig = nativeIsLowMemoryDevice() ?
244                             MEMORY_DEVICE_CONFIG_LOW : MEMORY_DEVICE_CONFIG_NORMAL;
245                 }
246
247                 switch (BROWSER_SHARED_RELRO_CONFIG) {
248                     case BROWSER_SHARED_RELRO_CONFIG_NEVER:
249                         sBrowserUsesSharedRelro = false;
250                         break;
251                     case BROWSER_SHARED_RELRO_CONFIG_LOW_RAM_ONLY:
252                         sBrowserUsesSharedRelro =
253                                 (sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW);
254                         if (sBrowserUsesSharedRelro)
255                             Log.w(TAG, "Low-memory device: shared RELROs used in all processes");
256                         break;
257                     case BROWSER_SHARED_RELRO_CONFIG_ALWAYS:
258                         Log.w(TAG, "Beware: shared RELROs used in all processes!");
259                         sBrowserUsesSharedRelro = true;
260                         break;
261                     default:
262                         assert false : "Unreached";
263                         break;
264                 }
265             } else {
266                 if (DEBUG) Log.i(TAG, "Linker disabled");
267             }
268
269             if (!sRelroSharingSupported) {
270                 // Sanity.
271                 sBrowserUsesSharedRelro = false;
272                 sWaitForSharedRelros = false;
273             }
274
275             sInitialized = true;
276         }
277     }
278
279     /**
280      * A public interface used to run runtime linker tests after loading
281      * libraries. Should only be used to implement the linker unit tests,
282      * which is controlled by the value of NativeLibraries.ENABLE_LINKER_TESTS
283      * configured at build time.
284      */
285     public interface TestRunner {
286         /**
287          * Run runtime checks and return true if they all pass.
288          * @param memoryDeviceConfig The current memory device configuration.
289          * @param inBrowserProcess true iff this is the browser process.
290          */
291         public boolean runChecks(int memoryDeviceConfig, boolean inBrowserProcess);
292     }
293
294     // The name of a class that implements TestRunner.
295     static String sTestRunnerClassName = null;
296
297     /**
298      * Set the TestRunner by its class name. It will be instantiated at
299      * runtime after all libraries are loaded.
300      * @param testRunnerClassName null or a String for the class name of the
301      * TestRunner to use.
302      */
303     public static void setTestRunnerClassName(String testRunnerClassName) {
304         if (DEBUG) Log.i(TAG, "setTestRunnerByClassName(" + testRunnerClassName + ") called");
305
306         if (!NativeLibraries.ENABLE_LINKER_TESTS) {
307             // Ignore this in production code to prevent malvolent runtime injection.
308             return;
309         }
310
311         synchronized (Linker.class) {
312             assert sTestRunnerClassName == null;
313             sTestRunnerClassName = testRunnerClassName;
314         }
315     }
316
317     /**
318      * Call this to retrieve the name of the current TestRunner class name
319      * if any. This can be useful to pass it from the browser process to
320      * child ones.
321      * @return null or a String holding the name of the class implementing
322      * the TestRunner set by calling setTestRunnerClassName() previously.
323      */
324     public static String getTestRunnerClassName() {
325         synchronized (Linker.class) {
326             return sTestRunnerClassName;
327         }
328     }
329
330     /**
331      * Call this method before any other Linker method to force a specific
332      * memory device configuration. Should only be used for testing.
333      * @param config either MEMORY_DEVICE_CONFIG_LOW or MEMORY_DEVICE_CONFIG_NORMAL.
334      */
335     public static void setMemoryDeviceConfig(int memoryDeviceConfig) {
336         if (DEBUG) Log.i(TAG, "setMemoryDeviceConfig(" + memoryDeviceConfig + ") called");
337         // Sanity check. This method should only be called during tests.
338         assert NativeLibraries.ENABLE_LINKER_TESTS;
339         synchronized (Linker.class) {
340             assert sMemoryDeviceConfig == MEMORY_DEVICE_CONFIG_INIT;
341             assert memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW ||
342                    memoryDeviceConfig == MEMORY_DEVICE_CONFIG_NORMAL;
343             if (DEBUG) {
344                 if (memoryDeviceConfig == MEMORY_DEVICE_CONFIG_LOW)
345                     Log.i(TAG, "Simulating a low-memory device");
346                 else
347                     Log.i(TAG, "Simulating a regular-memory device");
348             }
349             sMemoryDeviceConfig = memoryDeviceConfig;
350         }
351     }
352
353     /**
354      * Call this method to determine if this content-based project must
355      * use this linker. If not, System.loadLibrary() should be used to load
356      * libraries instead.
357      */
358     public static boolean isUsed() {
359         // Only GYP targets that are APKs and have the 'use_content_linker' variable
360         // defined as 1 will use this linker. For all others (the default), the
361         // auto-generated NativeLibraries.USE_LINKER variable will be false.
362         if (!NativeLibraries.USE_LINKER)
363             return false;
364
365         synchronized (Linker.class) {
366             ensureInitializedLocked();
367             // At the moment, there is also no point in using this linker if the
368             // system does not support RELRO sharing safely.
369             return sRelroSharingSupported;
370         }
371     }
372
373     /**
374      * Call this method just before loading any native shared libraries in this process.
375      */
376     public static void prepareLibraryLoad() {
377         if (DEBUG) Log.i(TAG, "prepareLibraryLoad() called");
378         synchronized (Linker.class) {
379             sPrepareLibraryLoadCalled = true;
380
381             if (sInBrowserProcess) {
382                 // Force generation of random base load address, as well
383                 // as creation of shared RELRO sections in this process.
384                 setupBaseLoadAddressLocked();
385             }
386         }
387     }
388
389     /**
390      * Call this method just after loading all native shared libraries in this process.
391      * Note that when in a service process, this will block until the RELRO bundle is
392      * received, i.e. when another thread calls useSharedRelros().
393      */
394      public static void finishLibraryLoad() {
395         if (DEBUG) Log.i(TAG, "finishLibraryLoad() called");
396         synchronized (Linker.class) {
397             if (DEBUG) Log.i(TAG, String.format(
398                     "sInBrowserProcess=%s sBrowserUsesSharedRelro=%s sWaitForSharedRelros=%s",
399                     sInBrowserProcess ? "true" : "false",
400                     sBrowserUsesSharedRelro ? "true" : "false",
401                     sWaitForSharedRelros ? "true" : "false"));
402
403             if (sLoadedLibraries == null) {
404                 if (DEBUG) Log.i(TAG, "No libraries loaded");
405             } else {
406                 if (sInBrowserProcess) {
407                     // Create new Bundle containing RELRO section information
408                     // for all loaded libraries. Make it available to getSharedRelros().
409                     sSharedRelros = createBundleFromLibInfoMap(sLoadedLibraries);
410                     if (DEBUG) {
411                         Log.i(TAG, "Shared RELRO created");
412                         dumpBundle(sSharedRelros);
413                     }
414
415                     if (sBrowserUsesSharedRelro) {
416                         useSharedRelrosLocked(sSharedRelros);
417                     }
418                 }
419
420                 if (sWaitForSharedRelros) {
421                     assert !sInBrowserProcess;
422
423                     // Wait until the shared relro bundle is received from useSharedRelros().
424                     while (sSharedRelros == null) {
425                         try {
426                             Linker.class.wait();
427                         } catch (InterruptedException ie) {
428                         }
429                     }
430                     useSharedRelrosLocked(sSharedRelros);
431                     // Clear the Bundle to ensure its file descriptor references can't be reused.
432                     sSharedRelros.clear();
433                     sSharedRelros = null;
434                 }
435             }
436
437             if (NativeLibraries.ENABLE_LINKER_TESTS && sTestRunnerClassName != null) {
438                 // The TestRunner implementation must be instantiated _after_
439                 // all libraries are loaded to ensure that its native methods
440                 // are properly registered.
441                 if (DEBUG) Log.i(TAG, "Instantiating " + sTestRunnerClassName);
442                 TestRunner testRunner = null;
443                 try {
444                     testRunner = (TestRunner)
445                             Class.forName(sTestRunnerClassName).newInstance();
446                 } catch (Exception e) {
447                     Log.e(TAG, "Could not extract test runner class name", e);
448                     testRunner = null;
449                 }
450                 if (testRunner != null) {
451                     if (!testRunner.runChecks(sMemoryDeviceConfig, sInBrowserProcess)) {
452                         Log.wtf(TAG, "Linker runtime tests failed in this process!!");
453                         assert false;
454                     } else {
455                         Log.i(TAG, "All linker tests passed!");
456                     }
457                 }
458             }
459         }
460         if (DEBUG) Log.i(TAG, "finishLibraryLoad() exiting");
461      }
462
463     /**
464      * Call this to send a Bundle containing the shared RELRO sections to be
465      * used in this process. If initServiceProcess() was previously called,
466      * finishLibraryLoad() will not exit until this method is called in another
467      * thread with a non-null value.
468      * @param bundle The Bundle instance containing a map of shared RELRO sections
469      * to use in this process.
470      */
471     public static void useSharedRelros(Bundle bundle) {
472         // Ensure the bundle uses the application's class loader, not the framework
473         // one which doesn't know anything about LibInfo.
474         if (bundle != null)
475             bundle.setClassLoader(LibInfo.class.getClassLoader());
476
477         if (DEBUG) Log.i(TAG, "useSharedRelros() called with " + bundle);
478
479         synchronized (Linker.class) {
480             // Note that in certain cases, this can be called before
481             // initServiceProcess() in service processes.
482             sSharedRelros = bundle;
483             // Tell any listener blocked in finishLibraryLoad() about it.
484             Linker.class.notifyAll();
485         }
486     }
487
488     /**
489      * Call this to retrieve the shared RELRO sections created in this process,
490      * after loading all libraries.
491      * @return a new Bundle instance, or null if RELRO sharing is disabled on
492      * this system, or if initServiceProcess() was called previously.
493      */
494     public static Bundle getSharedRelros() {
495         if (DEBUG) Log.i(TAG, "getSharedRelros() called");
496         synchronized (Linker.class) {
497             if (!sInBrowserProcess) {
498                 if (DEBUG) Log.i(TAG, "... returning null Bundle");
499                 return null;
500             }
501
502             // Return the Bundle created in finishLibraryLoad().
503             if (DEBUG) Log.i(TAG, "... returning " + sSharedRelros);
504             return sSharedRelros;
505         }
506     }
507
508
509     /**
510      * Call this method before loading any libraries to indicate that this
511      * process shall neither create or reuse shared RELRO sections.
512      */
513     public static void disableSharedRelros() {
514         if (DEBUG) Log.i(TAG, "disableSharedRelros() called");
515         synchronized (Linker.class) {
516             sInBrowserProcess = false;
517             sWaitForSharedRelros = false;
518             sBrowserUsesSharedRelro = false;
519         }
520     }
521
522     /**
523      * Call this method before loading any libraries to indicate that this
524      * process is ready to reuse shared RELRO sections from another one.
525      * Typically used when starting service processes.
526      * @param baseLoadAddress the base library load address to use.
527      */
528     public static void initServiceProcess(long baseLoadAddress) {
529         if (DEBUG) Log.i(TAG, String.format("initServiceProcess(0x%x) called", baseLoadAddress));
530         synchronized (Linker.class) {
531             ensureInitializedLocked();
532             sInBrowserProcess = false;
533             sBrowserUsesSharedRelro = false;
534             if (sRelroSharingSupported) {
535                 sWaitForSharedRelros = true;
536                 sBaseLoadAddress = baseLoadAddress;
537                 sCurrentLoadAddress = baseLoadAddress;
538             }
539         }
540     }
541
542     /**
543      * Retrieve the base load address of all shared RELRO sections.
544      * This also enforces the creation of shared RELRO sections in
545      * prepareLibraryLoad(), which can later be retrieved with getSharedRelros().
546      * @return a common, random base load address, or 0 if RELRO sharing is
547      * disabled.
548      */
549     public static long getBaseLoadAddress() {
550         synchronized (Linker.class) {
551             ensureInitializedLocked();
552             if (!sInBrowserProcess) {
553                 Log.w(TAG, "Shared RELRO sections are disabled in this process!");
554                 return 0;
555             }
556
557             setupBaseLoadAddressLocked();
558             if (DEBUG) Log.i(TAG, String.format("getBaseLoadAddress() returns 0x%x",
559                                                 sBaseLoadAddress));
560             return sBaseLoadAddress;
561         }
562     }
563
564     // Used internally to lazily setup the common random base load address.
565     private static void setupBaseLoadAddressLocked() {
566         assert Thread.holdsLock(Linker.class);
567         if (sBaseLoadAddress == 0) {
568             long address = computeRandomBaseLoadAddress();
569             sBaseLoadAddress = address;
570             sCurrentLoadAddress = address;
571             if (address == 0) {
572               // If the computed address is 0, there are issues with the
573               // entropy source, so disable RELRO shared / fixed load addresses.
574               Log.w(TAG, "Disabling shared RELROs due to bad entropy sources");
575               sBrowserUsesSharedRelro = false;
576               sWaitForSharedRelros = false;
577             }
578         }
579     }
580
581
582     /**
583      * Compute a random base load address where to place loaded libraries.
584      * @return new base load address, or 0 if the system does not support
585      * RELRO sharing.
586      */
587     private static long computeRandomBaseLoadAddress() {
588         // The kernel ASLR feature will place randomized mappings starting
589         // from this address. Never try to load anything above this
590         // explicitly to avoid random conflicts.
591         final long baseAddressLimit = 0x40000000;
592
593         // Start loading libraries from this base address.
594         final long baseAddress = 0x20000000;
595
596         // Maximum randomized base address value. Used to ensure a margin
597         // of 192 MB below baseAddressLimit.
598         final long baseAddressMax = baseAddressLimit - 192 * 1024 * 1024;
599
600         // The maximum limit of the desired random offset.
601         final long pageSize = nativeGetPageSize();
602         final int offsetLimit = (int)((baseAddressMax - baseAddress) / pageSize);
603
604         // Get the greatest power of 2 that is smaller or equal to offsetLimit.
605         int numBits = 30;
606         for (; numBits > 1; numBits--) {
607             if ((1 << numBits) <= offsetLimit)
608                 break;
609         }
610
611         if (DEBUG) {
612             final int maxValue = (1 << numBits) - 1;
613             Log.i(TAG, String.format("offsetLimit=%d numBits=%d maxValue=%d (0x%x)",
614                 offsetLimit, numBits, maxValue, maxValue));
615         }
616
617         // Find a random offset between 0 and (2^numBits - 1), included.
618         int offset = getRandomBits(numBits);
619         long address = 0;
620         if (offset >= 0)
621             address = baseAddress + offset * pageSize;
622
623         if (DEBUG) {
624             Log.i(TAG,
625                   String.format("Linker.computeRandomBaseLoadAddress() return 0x%x",
626                                 address));
627         }
628         return address;
629     }
630
631     /**
632      * Return a cryptographically-strong random number of numBits bits.
633      * @param numBits The number of bits in the result. Must be in 1..31 range.
634      * @return A random integer between 0 and (2^numBits - 1), inclusive, or -1
635      * in case of error (e.g. if /dev/urandom can't be opened or read).
636      */
637     private static int getRandomBits(int numBits) {
638         // Sanity check.
639         assert numBits > 0;
640         assert numBits < 32;
641
642         FileInputStream input;
643         try {
644             // A naive implementation would read a 32-bit integer then use modulo, but
645             // this introduces a slight bias. Instead, read 32-bit integers from the
646             // entropy source until the value is positive but smaller than maxLimit.
647             input = new FileInputStream(new File("/dev/urandom"));
648         } catch (Exception e) {
649             Log.e(TAG, "Could not open /dev/urandom", e);
650             return -1;
651         }
652
653         int result = 0;
654         try {
655             for (int n = 0; n < 4; n++)
656                 result = (result << 8) | (input.read() & 255);
657         } catch (Exception e) {
658             Log.e(TAG, "Could not read /dev/urandom", e);
659             return -1;
660         } finally {
661             try {
662                 input.close();
663             } catch (Exception e) {
664                 // Can't really do anything here.
665             }
666         }
667         result &= (1 << numBits) - 1;
668
669         if (DEBUG) {
670             Log.i(TAG, String.format(
671                     "getRandomBits(%d) returned %d", numBits, result));
672         }
673
674         return result;
675     }
676
677     // Used for debugging only.
678     private static void dumpBundle(Bundle bundle) {
679         if (DEBUG) Log.i(TAG, "Bundle has " + bundle.size() + " items: " + bundle);
680     }
681
682     /**
683      * Use the shared RELRO section from a Bundle received form another process.
684      * Call this after calling setBaseLoadAddress() then loading all libraries
685      * with loadLibrary().
686      * @param a Bundle instance generated with createSharedRelroBundle() in
687      * another process.
688      */
689     private static void useSharedRelrosLocked(Bundle bundle) {
690         assert Thread.holdsLock(Linker.class);
691
692         if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() called");
693
694         if (bundle == null) {
695             if (DEBUG) Log.i(TAG, "null bundle!");
696             return;
697         }
698
699         if (!sRelroSharingSupported) {
700             if (DEBUG) Log.i(TAG, "System does not support RELRO sharing");
701             return;
702         }
703
704         if (sLoadedLibraries == null) {
705             if (DEBUG) Log.i(TAG, "No libraries loaded!");
706             return;
707         }
708
709         if (DEBUG) dumpBundle(bundle);
710         HashMap<String, LibInfo> relroMap = createLibInfoMapFromBundle(bundle);
711
712         // Apply the RELRO section to all libraries that were already loaded.
713         for (Map.Entry<String, LibInfo> entry : relroMap.entrySet()) {
714             String libName = entry.getKey();
715             LibInfo libInfo = entry.getValue();
716             if (!nativeUseSharedRelro(libName, libInfo)) {
717                 Log.w(TAG, "Could not use shared RELRO section for " + libName);
718             } else {
719                 if (DEBUG) Log.i(TAG, "Using shared RELRO section for " + libName);
720             }
721         }
722
723         // In service processes, close all file descriptors from the map now.
724         if (!sInBrowserProcess)
725             closeLibInfoMap(relroMap);
726
727         if (DEBUG) Log.i(TAG, "Linker.useSharedRelrosLocked() exiting");
728     }
729
730     /**
731      * Returns whether the linker was unable to load one library at a given fixed address.
732      *
733      * @return true if at least one library was not loaded at the expected fixed address.
734      */
735     public static boolean loadAtFixedAddressFailed() {
736         return sLoadAtFixedAddressFailed;
737     }
738
739     /**
740      * Load a native shared library with the Chromium linker.
741      * If neither initSharedRelro() or readFromBundle() were called
742      * previously, this uses the standard linker (i.e. System.loadLibrary()).
743      *
744      * @param library The library's base name.
745      * @throws UnsatisfiedLinkError if the library does not exist.
746      */
747     public static void loadLibrary(String library) {
748         if (DEBUG) Log.i(TAG, "loadLibrary: " + library);
749
750         // Don't self-load the linker. This is because the build system is
751         // not clever enough to understand that all the libraries packaged
752         // in the final .apk don't need to be explicitly loaded.
753         // Also deal with the component build that adds a .cr suffix to the name.
754         if (library.equals(TAG) || library.equals(TAG + ".cr")) {
755             if (DEBUG) Log.i(TAG, "ignoring self-linker load");
756             return;
757         }
758
759         synchronized (Linker.class) {
760             ensureInitializedLocked();
761
762             // Security: Ensure prepareLibraryLoad() was called before.
763             // In theory, this can be done lazily here, but it's more consistent
764             // to use a pair of functions (i.e. prepareLibraryLoad() + finishLibraryLoad())
765             // that wrap all calls to loadLibrary() in the library loader.
766             assert sPrepareLibraryLoadCalled;
767
768             String libName = System.mapLibraryName(library);
769
770             if (sLoadedLibraries == null)
771               sLoadedLibraries = new HashMap<String, LibInfo>();
772
773             if (sLoadedLibraries.containsKey(libName)) {
774                 if (DEBUG) Log.i(TAG, "Not loading " + libName + " twice");
775                 return;
776             }
777
778             LibInfo libInfo = new LibInfo();
779             LibInfo relroLibInfo = null;
780             long loadAddress = 0;
781             if ((sInBrowserProcess && sBrowserUsesSharedRelro) || sWaitForSharedRelros) {
782                 // Load the library at a fixed address.
783                 loadAddress = sCurrentLoadAddress;
784             }
785
786             if (!nativeLoadLibrary(libName, loadAddress, libInfo)) {
787                 String errorMessage = "Unable to load library: " + libName;
788                 Log.e(TAG, errorMessage);
789                 throw new UnsatisfiedLinkError(errorMessage);
790             }
791             // Keep track whether the library has been loaded at the expected load address.
792             if (loadAddress != 0 && loadAddress != libInfo.mLoadAddress)
793                 sLoadAtFixedAddressFailed = true;
794
795             // Print the load address to the logcat when testing the linker. The format
796             // of the string is expected by the Python test_runner script as one of:
797             //    BROWSER_LIBRARY_ADDRESS: <library-name> <address>
798             //    RENDERER_LIBRARY_ADDRESS: <library-name> <address>
799             // Where <library-name> is the library name, and <address> is the hexadecimal load
800             // address.
801             if (NativeLibraries.ENABLE_LINKER_TESTS) {
802                 Log.i(TAG, String.format(
803                         "%s_LIBRARY_ADDRESS: %s %x",
804                         sInBrowserProcess ? "BROWSER" : "RENDERER",
805                         libName,
806                         libInfo.mLoadAddress));
807             }
808
809             if (sInBrowserProcess) {
810                 // Create a new shared RELRO section at the 'current' fixed load address.
811                 if (!nativeCreateSharedRelro(libName, sCurrentLoadAddress, libInfo)) {
812                   Log.w(TAG,
813                       String.format(
814                           "Could not create shared RELRO for %s at %x",
815                           libName, sCurrentLoadAddress));
816                 } else {
817                     if (DEBUG) Log.i(TAG,
818                         String.format(
819                             "Created shared RELRO for %s at %x: %s",
820                             libName,
821                             sCurrentLoadAddress,
822                             libInfo.toString()));
823                 }
824             }
825
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
830                 // only.
831                 sCurrentLoadAddress = libInfo.mLoadAddress + libInfo.mLoadSize;
832             }
833
834             sLoadedLibraries.put(libName, libInfo);
835             if (DEBUG) Log.i(TAG, "Library details " + libInfo.toString());
836         }
837     }
838
839     /**
840      * Native method used to load a library.
841      * @param library Platform specific library name (e.g. libfoo.so)
842      * @param loadAddress Explicit load address, or 0 for randomized one.
843      * @param relro_info If not null, the mLoadAddress and mLoadSize fields
844      * of this LibInfo instance will set on success.
845      * @return true for success, false otherwise.
846      */
847     private static native boolean nativeLoadLibrary(String library,
848                                                     long  loadAddress,
849                                                     LibInfo libInfo);
850
851     /**
852      * Native method used to create a shared RELRO section.
853      * If the library was already loaded at the same address using
854      * nativeLoadLibrary(), this creates the RELRO for it. Otherwise,
855      * this loads a new temporary library at the specified address,
856      * creates and extracts the RELRO section from it, then unloads it.
857      * @param library Library name.
858      * @param loadAddress load address, which can be different from the one
859      * used to load the library in the current process!
860      * @param LibInfo libInfo instance. On success, the mRelroStart, mRelroSize
861      * and mRelroFd will be set.
862      * @return true on success, false otherwise.
863      */
864     private static native boolean nativeCreateSharedRelro(String library,
865                                                           long loadAddress,
866                                                           LibInfo libInfo);
867
868     /**
869      * Native method used to use a shared RELRO section.
870      * @param library Library name.
871      * @param libInfo A LibInfo instance containing valid RELRO information
872      * @return true on success.
873      */
874     private static native boolean nativeUseSharedRelro(String library,
875                                                        LibInfo libInfo);
876
877     /**
878      * Checks that the system supports shared RELROs. Old Android kernels
879      * have a bug in the way they check Ashmem region protection flags, which
880      * makes using shared RELROs unsafe. This method performs a simple runtime
881      * check for this misfeature, even though nativeEnableSharedRelro() will
882      * always fail if this returns false.
883      */
884     private static native boolean nativeCanUseSharedRelro();
885
886     // Returns the native page size in bytes.
887     private static native long nativeGetPageSize();
888
889     // Checks whether this is a low-memory device.
890     private static native boolean nativeIsLowMemoryDevice();
891
892     /**
893      * Record information for a given library.
894      * IMPORTANT: Native code knows about this class's fields, so
895      * don't change them without modifying the corresponding C++ sources.
896      * Also, the LibInfo instance owns the ashmem file descriptor.
897      */
898     public static class LibInfo implements Parcelable {
899
900         public LibInfo() {
901             mLoadAddress = 0;
902             mLoadSize = 0;
903             mRelroStart = 0;
904             mRelroSize = 0;
905             mRelroFd = -1;
906         }
907
908         public void close() {
909             if (mRelroFd >= 0) {
910               try {
911                   ParcelFileDescriptor.adoptFd(mRelroFd).close();
912               } catch (java.io.IOException e) {
913               }
914               mRelroFd = -1;
915             }
916         }
917
918         // from Parcelable
919         public LibInfo(Parcel in) {
920             mLoadAddress = in.readLong();
921             mLoadSize = in.readLong();
922             mRelroStart = in.readLong();
923             mRelroSize = in.readLong();
924             ParcelFileDescriptor fd = in.readFileDescriptor();
925             mRelroFd = fd.detachFd();
926         }
927
928         // from Parcelable
929         @Override
930         public void writeToParcel(Parcel out, int flags) {
931             if (mRelroFd >= 0) {
932                 out.writeLong(mLoadAddress);
933                 out.writeLong(mLoadSize);
934                 out.writeLong(mRelroStart);
935                 out.writeLong(mRelroSize);
936                 try {
937                     ParcelFileDescriptor fd = ParcelFileDescriptor.fromFd(mRelroFd);
938                     fd.writeToParcel(out, 0);
939                     fd.close();
940                 } catch (java.io.IOException e) {
941                     Log.e(TAG, "Cant' write LibInfo file descriptor to parcel", e);
942                 }
943             }
944         }
945
946         // from Parcelable
947         @Override
948         public int describeContents() {
949             return Parcelable.CONTENTS_FILE_DESCRIPTOR;
950         }
951
952         // from Parcelable
953         public static final Parcelable.Creator<LibInfo> CREATOR
954                 = new Parcelable.Creator<LibInfo>() {
955             public LibInfo createFromParcel(Parcel in) {
956                 return new LibInfo(in);
957             }
958
959             public LibInfo[] newArray(int size) {
960                 return new LibInfo[size];
961             }
962         };
963
964         public String toString() {
965             return String.format("[load=0x%x-0x%x relro=0x%x-0x%x fd=%d]",
966                                  mLoadAddress,
967                                  mLoadAddress + mLoadSize,
968                                  mRelroStart,
969                                  mRelroStart + mRelroSize,
970                                  mRelroFd);
971         }
972
973         // IMPORTANT: Don't change these fields without modifying the
974         // native code that accesses them directly!
975         public long mLoadAddress; // page-aligned library load address.
976         public long mLoadSize;    // page-aligned library load size.
977         public long mRelroStart;  // page-aligned address in memory, or 0 if none.
978         public long mRelroSize;   // page-aligned size in memory, or 0.
979         public int  mRelroFd;     // ashmem file descriptor, or -1
980     }
981
982     // Create a Bundle from a map of LibInfo objects.
983     private static Bundle createBundleFromLibInfoMap(HashMap<String, LibInfo> map) {
984         Bundle bundle = new Bundle(map.size());
985         for (Map.Entry<String, LibInfo> entry : map.entrySet())
986             bundle.putParcelable(entry.getKey(), entry.getValue());
987
988         return bundle;
989     }
990
991     // Create a new LibInfo map from a Bundle.
992     private static HashMap<String, LibInfo> createLibInfoMapFromBundle(Bundle bundle) {
993         HashMap<String, LibInfo> map = new HashMap<String, LibInfo>();
994         for (String library : bundle.keySet()) {
995           LibInfo libInfo = bundle.getParcelable(library);
996           map.put(library, libInfo);
997         }
998         return map;
999     }
1000
1001     // Call the close() method on all values of a LibInfo map.
1002     private static void closeLibInfoMap(HashMap<String, LibInfo> map) {
1003         for (Map.Entry<String, LibInfo> entry : map.entrySet())
1004             entry.getValue().close();
1005     }
1006
1007     // The map of libraries that are currently loaded in this process.
1008     private static HashMap<String, LibInfo> sLoadedLibraries = null;
1009
1010     // Used to pass the shared RELRO Bundle through Binder.
1011     public static final String EXTRA_LINKER_SHARED_RELROS =
1012         "org.chromium.content.common.linker.shared_relros";
1013 }