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