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