WebViewFactory.java revision 2ed6fee15c85ff991f64ecfa8c1c4738e0fdf9b6
1/* 2 * Copyright (C) 2012 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package android.webkit; 18 19import android.annotation.SystemApi; 20import android.app.ActivityManagerInternal; 21import android.app.AppGlobals; 22import android.app.Application; 23import android.content.Context; 24import android.content.pm.ApplicationInfo; 25import android.content.pm.PackageInfo; 26import android.content.pm.PackageManager; 27import android.os.Build; 28import android.os.Process; 29import android.os.RemoteException; 30import android.os.ServiceManager; 31import android.os.StrictMode; 32import android.os.SystemProperties; 33import android.os.Trace; 34import android.text.TextUtils; 35import android.util.AndroidRuntimeException; 36import android.util.Log; 37 38import com.android.server.LocalServices; 39 40import dalvik.system.VMRuntime; 41 42import java.io.File; 43import java.util.Arrays; 44 45/** 46 * Top level factory, used creating all the main WebView implementation classes. 47 * 48 * @hide 49 */ 50@SystemApi 51public final class WebViewFactory { 52 53 private static final String CHROMIUM_WEBVIEW_FACTORY = 54 "com.android.webview.chromium.WebViewChromiumFactoryProvider"; 55 56 private static final String NULL_WEBVIEW_FACTORY = 57 "com.android.webview.nullwebview.NullWebViewFactoryProvider"; 58 59 private static final String CHROMIUM_WEBVIEW_NATIVE_RELRO_32 = 60 "/data/misc/shared_relro/libwebviewchromium32.relro"; 61 private static final String CHROMIUM_WEBVIEW_NATIVE_RELRO_64 = 62 "/data/misc/shared_relro/libwebviewchromium64.relro"; 63 64 public static final String CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY = 65 "persist.sys.webview.vmsize"; 66 private static final long CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES = 100 * 1024 * 1024; 67 68 private static final String LOGTAG = "WebViewFactory"; 69 70 private static final boolean DEBUG = false; 71 72 // Cache the factory both for efficiency, and ensure any one process gets all webviews from the 73 // same provider. 74 private static WebViewFactoryProvider sProviderInstance; 75 private static final Object sProviderLock = new Object(); 76 private static boolean sAddressSpaceReserved = false; 77 private static PackageInfo sPackageInfo; 78 79 /** @hide */ 80 public static String[] getWebViewPackageNames() { 81 return AppGlobals.getInitialApplication().getResources().getStringArray( 82 com.android.internal.R.array.config_webViewPackageNames); 83 } 84 85 // TODO (gsennton) remove when committing webview xts test change 86 public static String getWebViewPackageName() { 87 String[] webViewPackageNames = getWebViewPackageNames(); 88 return webViewPackageNames[webViewPackageNames.length-1]; 89 } 90 91 /** 92 * Return the package info of the first package in the webview priority list that contains 93 * webview. 94 * 95 * @hide 96 */ 97 public static PackageInfo findPreferredWebViewPackage() { 98 PackageManager pm = AppGlobals.getInitialApplication().getPackageManager(); 99 100 for (String packageName : getWebViewPackageNames()) { 101 try { 102 PackageInfo packageInfo = pm.getPackageInfo(packageName, 103 PackageManager.GET_META_DATA); 104 ApplicationInfo applicationInfo = packageInfo.applicationInfo; 105 106 // If the correct flag is set the package contains webview. 107 if (getWebViewLibrary(applicationInfo) != null) { 108 return packageInfo; 109 } 110 } catch (PackageManager.NameNotFoundException e) { 111 } 112 } 113 throw new AndroidRuntimeException("Could not find a loadable WebView package"); 114 } 115 116 private static ApplicationInfo getWebViewApplicationInfo() { 117 if (sPackageInfo == null) 118 return findPreferredWebViewPackage().applicationInfo; 119 else 120 return sPackageInfo.applicationInfo; 121 } 122 123 private static String getWebViewLibrary(ApplicationInfo ai) { 124 if (ai.metaData != null) 125 return ai.metaData.getString("com.android.webview.WebViewLibrary"); 126 return null; 127 } 128 129 public static PackageInfo getLoadedPackageInfo() { 130 return sPackageInfo; 131 } 132 133 static WebViewFactoryProvider getProvider() { 134 synchronized (sProviderLock) { 135 // For now the main purpose of this function (and the factory abstraction) is to keep 136 // us honest and minimize usage of WebView internals when binding the proxy. 137 if (sProviderInstance != null) return sProviderInstance; 138 139 final int uid = android.os.Process.myUid(); 140 if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID) { 141 throw new UnsupportedOperationException( 142 "For security reasons, WebView is not allowed in privileged processes"); 143 } 144 145 Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getProvider()"); 146 try { 147 // First fetch the package info so we can log the webview package version. 148 sPackageInfo = findPreferredWebViewPackage(); 149 Log.i(LOGTAG, "Loading " + sPackageInfo.packageName + " version " + 150 sPackageInfo.versionName + " (code " + sPackageInfo.versionCode + ")"); 151 152 Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.loadNativeLibrary()"); 153 loadNativeLibrary(); 154 Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); 155 156 Class<WebViewFactoryProvider> providerClass; 157 Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getFactoryClass()"); 158 try { 159 providerClass = getFactoryClass(); 160 } catch (ClassNotFoundException e) { 161 Log.e(LOGTAG, "error loading provider", e); 162 throw new AndroidRuntimeException(e); 163 } finally { 164 Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); 165 } 166 167 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads(); 168 Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()"); 169 try { 170 sProviderInstance = providerClass.getConstructor(WebViewDelegate.class) 171 .newInstance(new WebViewDelegate()); 172 if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance); 173 return sProviderInstance; 174 } catch (Exception e) { 175 Log.e(LOGTAG, "error instantiating provider", e); 176 throw new AndroidRuntimeException(e); 177 } finally { 178 Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); 179 StrictMode.setThreadPolicy(oldPolicy); 180 } 181 } finally { 182 Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); 183 } 184 } 185 } 186 187 private static Class<WebViewFactoryProvider> getFactoryClass() throws ClassNotFoundException { 188 Application initialApplication = AppGlobals.getInitialApplication(); 189 try { 190 // Construct a package context to load the Java code into the current app. 191 Context webViewContext = initialApplication.createPackageContext( 192 sPackageInfo.packageName, 193 Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY); 194 initialApplication.getAssets().addAssetPath( 195 webViewContext.getApplicationInfo().sourceDir); 196 ClassLoader clazzLoader = webViewContext.getClassLoader(); 197 Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "Class.forName()"); 198 try { 199 return (Class<WebViewFactoryProvider>) Class.forName(CHROMIUM_WEBVIEW_FACTORY, true, 200 clazzLoader); 201 } finally { 202 Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW); 203 } 204 } catch (PackageManager.NameNotFoundException e) { 205 // If the package doesn't exist, then try loading the null WebView instead. 206 // If that succeeds, then this is a device without WebView support; if it fails then 207 // swallow the failure, complain that the real WebView is missing and rethrow the 208 // original exception. 209 try { 210 return (Class<WebViewFactoryProvider>) Class.forName(NULL_WEBVIEW_FACTORY); 211 } catch (ClassNotFoundException e2) { 212 // Ignore. 213 } 214 Log.e(LOGTAG, "Chromium WebView package does not exist", e); 215 throw new AndroidRuntimeException(e); 216 } 217 } 218 219 /** 220 * Perform any WebView loading preparations that must happen in the zygote. 221 * Currently, this means allocating address space to load the real JNI library later. 222 */ 223 public static void prepareWebViewInZygote() { 224 try { 225 System.loadLibrary("webviewchromium_loader"); 226 long addressSpaceToReserve = 227 SystemProperties.getLong(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY, 228 CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES); 229 sAddressSpaceReserved = nativeReserveAddressSpace(addressSpaceToReserve); 230 231 if (sAddressSpaceReserved) { 232 if (DEBUG) { 233 Log.v(LOGTAG, "address space reserved: " + addressSpaceToReserve + " bytes"); 234 } 235 } else { 236 Log.e(LOGTAG, "reserving " + addressSpaceToReserve + 237 " bytes of address space failed"); 238 } 239 } catch (Throwable t) { 240 // Log and discard errors at this stage as we must not crash the zygote. 241 Log.e(LOGTAG, "error preparing native loader", t); 242 } 243 } 244 245 /** 246 * Perform any WebView loading preparations that must happen at boot from the system server, 247 * after the package manager has started or after an update to the webview is installed. 248 * This must be called in the system server. 249 * Currently, this means spawning the child processes which will create the relro files. 250 */ 251 public static void prepareWebViewInSystemServer() { 252 String[] nativePaths = null; 253 try { 254 nativePaths = getWebViewNativeLibraryPaths(); 255 } catch (Throwable t) { 256 // Log and discard errors at this stage as we must not crash the system server. 257 Log.e(LOGTAG, "error preparing webview native library", t); 258 } 259 prepareWebViewInSystemServer(nativePaths); 260 } 261 262 private static void prepareWebViewInSystemServer(String[] nativeLibraryPaths) { 263 if (DEBUG) Log.v(LOGTAG, "creating relro files"); 264 265 // We must always trigger createRelRo regardless of the value of nativeLibraryPaths. Any 266 // unexpected values will be handled there to ensure that we trigger notifying any process 267 // waiting on relreo creation. 268 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 269 if (DEBUG) Log.v(LOGTAG, "Create 32 bit relro"); 270 createRelroFile(false /* is64Bit */, nativeLibraryPaths); 271 } 272 273 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 274 if (DEBUG) Log.v(LOGTAG, "Create 64 bit relro"); 275 createRelroFile(true /* is64Bit */, nativeLibraryPaths); 276 } 277 } 278 279 public static void onWebViewUpdateInstalled() { 280 String[] nativeLibs = null; 281 try { 282 nativeLibs = WebViewFactory.getWebViewNativeLibraryPaths(); 283 if (nativeLibs != null) { 284 long newVmSize = 0L; 285 286 for (String path : nativeLibs) { 287 if (DEBUG) Log.d(LOGTAG, "Checking file size of " + path); 288 if (path == null) continue; 289 File f = new File(path); 290 if (f.exists()) { 291 long length = f.length(); 292 if (length > newVmSize) { 293 newVmSize = length; 294 } 295 } 296 } 297 298 if (DEBUG) { 299 Log.v(LOGTAG, "Based on library size, need " + newVmSize + 300 " bytes of address space."); 301 } 302 // The required memory can be larger than the file on disk (due to .bss), and an 303 // upgraded version of the library will likely be larger, so always attempt to 304 // reserve twice as much as we think to allow for the library to grow during this 305 // boot cycle. 306 newVmSize = Math.max(2 * newVmSize, CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES); 307 Log.d(LOGTAG, "Setting new address space to " + newVmSize); 308 SystemProperties.set(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY, 309 Long.toString(newVmSize)); 310 } 311 } catch (Throwable t) { 312 // Log and discard errors at this stage as we must not crash the system server. 313 Log.e(LOGTAG, "error preparing webview native library", t); 314 } 315 prepareWebViewInSystemServer(nativeLibs); 316 } 317 318 private static String[] getWebViewNativeLibraryPaths() 319 throws PackageManager.NameNotFoundException { 320 ApplicationInfo ai = getWebViewApplicationInfo(); 321 final String NATIVE_LIB_FILE_NAME = getWebViewLibrary(ai); 322 323 String path32; 324 String path64; 325 boolean primaryArchIs64bit = VMRuntime.is64BitAbi(ai.primaryCpuAbi); 326 if (!TextUtils.isEmpty(ai.secondaryCpuAbi)) { 327 // Multi-arch case. 328 if (primaryArchIs64bit) { 329 // Primary arch: 64-bit, secondary: 32-bit. 330 path64 = ai.nativeLibraryDir; 331 path32 = ai.secondaryNativeLibraryDir; 332 } else { 333 // Primary arch: 32-bit, secondary: 64-bit. 334 path64 = ai.secondaryNativeLibraryDir; 335 path32 = ai.nativeLibraryDir; 336 } 337 } else if (primaryArchIs64bit) { 338 // Single-arch 64-bit. 339 path64 = ai.nativeLibraryDir; 340 path32 = ""; 341 } else { 342 // Single-arch 32-bit. 343 path32 = ai.nativeLibraryDir; 344 path64 = ""; 345 } 346 if (!TextUtils.isEmpty(path32)) path32 += "/" + NATIVE_LIB_FILE_NAME; 347 if (!TextUtils.isEmpty(path64)) path64 += "/" + NATIVE_LIB_FILE_NAME; 348 return new String[] { path32, path64 }; 349 } 350 351 private static void createRelroFile(final boolean is64Bit, String[] nativeLibraryPaths) { 352 final String abi = 353 is64Bit ? Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 354 355 // crashHandler is invoked by the ActivityManagerService when the isolated process crashes. 356 Runnable crashHandler = new Runnable() { 357 @Override 358 public void run() { 359 try { 360 Log.e(LOGTAG, "relro file creator for " + abi + " crashed. Proceeding without"); 361 getUpdateService().notifyRelroCreationCompleted(is64Bit, false); 362 } catch (RemoteException e) { 363 Log.e(LOGTAG, "Cannot reach WebViewUpdateService. " + e.getMessage()); 364 } 365 } 366 }; 367 368 try { 369 if (nativeLibraryPaths == null 370 || nativeLibraryPaths[0] == null || nativeLibraryPaths[1] == null) { 371 throw new IllegalArgumentException( 372 "Native library paths to the WebView RelRo process must not be null!"); 373 } 374 int pid = LocalServices.getService(ActivityManagerInternal.class).startIsolatedProcess( 375 RelroFileCreator.class.getName(), nativeLibraryPaths, "WebViewLoader-" + abi, abi, 376 Process.SHARED_RELRO_UID, crashHandler); 377 if (pid <= 0) throw new Exception("Failed to start the relro file creator process"); 378 } catch (Throwable t) { 379 // Log and discard errors as we must not crash the system server. 380 Log.e(LOGTAG, "error starting relro file creator for abi " + abi, t); 381 crashHandler.run(); 382 } 383 } 384 385 private static class RelroFileCreator { 386 // Called in an unprivileged child process to create the relro file. 387 public static void main(String[] args) { 388 boolean result = false; 389 boolean is64Bit = VMRuntime.getRuntime().is64Bit(); 390 try{ 391 if (args.length != 2 || args[0] == null || args[1] == null) { 392 Log.e(LOGTAG, "Invalid RelroFileCreator args: " + Arrays.toString(args)); 393 return; 394 } 395 Log.v(LOGTAG, "RelroFileCreator (64bit = " + is64Bit + "), " + 396 " 32-bit lib: " + args[0] + ", 64-bit lib: " + args[1]); 397 if (!sAddressSpaceReserved) { 398 Log.e(LOGTAG, "can't create relro file; address space not reserved"); 399 return; 400 } 401 result = nativeCreateRelroFile(args[0] /* path32 */, 402 args[1] /* path64 */, 403 CHROMIUM_WEBVIEW_NATIVE_RELRO_32, 404 CHROMIUM_WEBVIEW_NATIVE_RELRO_64); 405 if (result && DEBUG) Log.v(LOGTAG, "created relro file"); 406 } finally { 407 // We must do our best to always notify the update service, even if something fails. 408 try { 409 getUpdateService().notifyRelroCreationCompleted(is64Bit, result); 410 } catch (RemoteException e) { 411 Log.e(LOGTAG, "error notifying update service", e); 412 } 413 414 if (!result) Log.e(LOGTAG, "failed to create relro file"); 415 416 // Must explicitly exit or else this process will just sit around after we return. 417 System.exit(0); 418 } 419 } 420 } 421 422 private static void loadNativeLibrary() { 423 if (!sAddressSpaceReserved) { 424 Log.e(LOGTAG, "can't load with relro file; address space not reserved"); 425 return; 426 } 427 428 try { 429 getUpdateService().waitForRelroCreationCompleted(VMRuntime.getRuntime().is64Bit()); 430 } catch (RemoteException e) { 431 Log.e(LOGTAG, "error waiting for relro creation, proceeding without", e); 432 return; 433 } 434 435 try { 436 String[] args = getWebViewNativeLibraryPaths(); 437 boolean result = nativeLoadWithRelroFile(args[0] /* path32 */, 438 args[1] /* path64 */, 439 CHROMIUM_WEBVIEW_NATIVE_RELRO_32, 440 CHROMIUM_WEBVIEW_NATIVE_RELRO_64); 441 if (!result) { 442 Log.w(LOGTAG, "failed to load with relro file, proceeding without"); 443 } else if (DEBUG) { 444 Log.v(LOGTAG, "loaded with relro file"); 445 } 446 } catch (PackageManager.NameNotFoundException e) { 447 Log.e(LOGTAG, "Failed to list WebView package libraries for loadNativeLibrary", e); 448 } 449 } 450 451 private static IWebViewUpdateService getUpdateService() { 452 return IWebViewUpdateService.Stub.asInterface(ServiceManager.getService("webviewupdate")); 453 } 454 455 private static native boolean nativeReserveAddressSpace(long addressSpaceToReserve); 456 private static native boolean nativeCreateRelroFile(String lib32, String lib64, 457 String relro32, String relro64); 458 private static native boolean nativeLoadWithRelroFile(String lib32, String lib64, 459 String relro32, String relro64); 460} 461