WebViewChromiumFactoryProvider.java 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877
  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. package com.android.webview.chromium;
  5. import android.content.Context;
  6. import android.content.ContextWrapper;
  7. import android.content.Intent;
  8. import android.content.SharedPreferences;
  9. import android.content.pm.ApplicationInfo;
  10. import android.content.pm.PackageInfo;
  11. import android.content.res.AssetManager;
  12. import android.net.Uri;
  13. import android.os.Build;
  14. import android.os.SystemClock;
  15. import android.provider.Settings;
  16. import android.webkit.CookieManager;
  17. import android.webkit.GeolocationPermissions;
  18. import android.webkit.PacProcessor;
  19. import android.webkit.ServiceWorkerController;
  20. import android.webkit.TokenBindingService;
  21. import android.webkit.TracingController;
  22. import android.webkit.ValueCallback;
  23. import android.webkit.WebStorage;
  24. import android.webkit.WebView;
  25. import android.webkit.WebViewDatabase;
  26. import android.webkit.WebViewDelegate;
  27. import android.webkit.WebViewFactory;
  28. import android.webkit.WebViewFactoryProvider;
  29. import android.webkit.WebViewProvider;
  30. import androidx.annotation.IntDef;
  31. import androidx.annotation.RequiresApi;
  32. import org.chromium.android_webview.ApkType;
  33. import org.chromium.android_webview.AwBrowserContext;
  34. import org.chromium.android_webview.AwBrowserProcess;
  35. import org.chromium.android_webview.AwContentsStatics;
  36. import org.chromium.android_webview.AwSettings;
  37. import org.chromium.android_webview.BrowserSafeModeActionList;
  38. import org.chromium.android_webview.ProductConfig;
  39. import org.chromium.android_webview.WebViewChromiumRunQueue;
  40. import org.chromium.android_webview.common.AwSwitches;
  41. import org.chromium.android_webview.common.CommandLineUtil;
  42. import org.chromium.android_webview.common.DeveloperModeUtils;
  43. import org.chromium.android_webview.common.FlagOverrideHelper;
  44. import org.chromium.android_webview.common.ProductionSupportedFlagList;
  45. import org.chromium.android_webview.common.SafeModeController;
  46. import org.chromium.base.BuildInfo;
  47. import org.chromium.base.CommandLine;
  48. import org.chromium.base.ContextUtils;
  49. import org.chromium.base.Log;
  50. import org.chromium.base.PackageUtils;
  51. import org.chromium.base.PathUtils;
  52. import org.chromium.base.StrictModeContext;
  53. import org.chromium.base.ThreadUtils;
  54. import org.chromium.base.metrics.RecordHistogram;
  55. import org.chromium.base.metrics.ScopedSysTraceEvent;
  56. import org.chromium.build.BuildConfig;
  57. import org.chromium.build.NativeLibraries;
  58. import org.chromium.components.embedder_support.application.ClassLoaderContextWrapperFactory;
  59. import org.chromium.components.embedder_support.application.FirebaseConfig;
  60. import org.chromium.components.version_info.VersionConstants;
  61. import org.chromium.content_public.browser.LGEmailActionModeWorkaround;
  62. import java.io.File;
  63. import java.util.List;
  64. import java.util.Map;
  65. import java.util.Set;
  66. import java.util.concurrent.Callable;
  67. import java.util.concurrent.FutureTask;
  68. /**
  69. * Entry point to the WebView. The system framework talks to this class to get instances of the
  70. * implementation classes.
  71. *
  72. * <p>The exact initialization process depends on the platform OS level:
  73. * <ul>
  74. *
  75. * <li>On API 21 (no longer supported), the platform invoked a parameterless constructor. Since we
  76. * didn't have a WebViewDelegate instance, this required us to invoke WebViewDelegate methods via
  77. * reflection. This constructor has been removed from the code as we no longer support Android
  78. * 21.</li>
  79. *
  80. * <li>From API 22 through API 25, the platform instead directly calls the constructor with a
  81. * WebViewDelegate parameter (See internal CL http://ag/577188 or the public AOSP cherrypick
  82. * https://r.android.com/114870). API 22 (no longer supported) would fallback to the
  83. * parameterless constructor if the first constructor call throws an exception, however this
  84. * fallback was removed in API 23.</li>
  85. *
  86. * <li>Starting in API 26, the platform calls {@link #create} instead of calling the constructor
  87. * directly (see internal CLs http://ag/1334128 and http://ag/1846560).</li>
  88. *
  89. * <li>From API 27 onward, the platform code is updated during each release to use the {@code
  90. * WebViewChromiumFactoryProviderForX} subclass, where "X" is replaced by the actual platform API
  91. * version (ex. "ForOMR1"). It still invokes the {@link #create} method on the subclass. While the
  92. * OS version is still under development, the "ForX" subclass implements the new platform APIs (in a
  93. * private codebase). Once the APIs for that version have been finalized, we eventually roll these
  94. * implementations into this class and the "ForX" subclass just calls directly into this
  95. * implementation.</li>
  96. *
  97. * </ul>
  98. */
  99. @SuppressWarnings("deprecation")
  100. public class WebViewChromiumFactoryProvider implements WebViewFactoryProvider {
  101. private static final String TAG = "WVCFactoryProvider";
  102. private static final String CHROMIUM_PREFS_NAME = "WebViewChromiumPrefs";
  103. private static final String VERSION_CODE_PREF = "lastVersionCodeUsed";
  104. private static final String SUPPORT_LIB_GLUE_AND_BOUNDARY_INTERFACE_PREFIX =
  105. "org.chromium.support_lib_";
  106. // This is an ID hardcoded by WebLayer for resources stored in locale splits. See
  107. // WebLayerImpl.java for more info.
  108. private static final int SHARED_LIBRARY_MAX_ID = 36;
  109. /**
  110. * This holds objects of classes that are defined in N and above to ensure that run-time class
  111. * verification does not occur until it is actually used for N and above.
  112. */
  113. @RequiresApi(Build.VERSION_CODES.N)
  114. private static class ObjectHolderForN {
  115. public ServiceWorkerController mServiceWorkerController;
  116. }
  117. /**
  118. * This holds objects of classes that are defined in P and above to ensure that run-time class
  119. * verification does not occur until it is actually used for P and above.
  120. */
  121. @RequiresApi(Build.VERSION_CODES.P)
  122. private static class ObjectHolderForP {
  123. public TracingController mTracingController;
  124. }
  125. private static final Object sSingletonLock = new Object();
  126. private static WebViewChromiumFactoryProvider sSingleton;
  127. // Used to indicate if WebLayer and WebView are running in the same process.
  128. private static boolean sWebLayerRunningInSameProcess;
  129. private final WebViewChromiumRunQueue mRunQueue = new WebViewChromiumRunQueue(
  130. () -> { return WebViewChromiumFactoryProvider.this.mAwInit.hasStarted(); });
  131. /* package */ WebViewChromiumRunQueue getRunQueue() {
  132. return mRunQueue;
  133. }
  134. // We have a 4 second timeout to try to detect deadlocks to detect and aid in debuggin
  135. // deadlocks.
  136. // Do not call this method while on the UI thread!
  137. /* package */ void runVoidTaskOnUiThreadBlocking(Runnable r) {
  138. mRunQueue.runVoidTaskOnUiThreadBlocking(r);
  139. }
  140. /* package */ <T> T runOnUiThreadBlocking(Callable<T> c) {
  141. return mRunQueue.runBlockingFuture(new FutureTask<T>(c));
  142. }
  143. /* package */ void addTask(Runnable task) {
  144. mRunQueue.addTask(task);
  145. }
  146. /**
  147. * Class that takes care of chromium lazy initialization.
  148. * This is package-public so that a downstream subclass can access it.
  149. */
  150. /* package */ WebViewChromiumAwInit mAwInit;
  151. private SharedPreferences mWebViewPrefs;
  152. private WebViewDelegate mWebViewDelegate;
  153. protected boolean mShouldDisableThreadChecking;
  154. // Initialization guarded by mAwInit.getLock()
  155. private Statics mStaticsAdapter;
  156. private boolean mIsSafeModeEnabled;
  157. @RequiresApi(Build.VERSION_CODES.N)
  158. private ObjectHolderForN mObjectHolderForN =
  159. Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ? new ObjectHolderForN() : null;
  160. @RequiresApi(Build.VERSION_CODES.P)
  161. private ObjectHolderForP mObjectHolderForP =
  162. Build.VERSION.SDK_INT >= Build.VERSION_CODES.P ? new ObjectHolderForP() : null;
  163. /**
  164. * Thread-safe way to set the one and only WebViewChromiumFactoryProvider.
  165. */
  166. private static void setSingleton(WebViewChromiumFactoryProvider provider) {
  167. synchronized (sSingletonLock) {
  168. if (sSingleton != null) {
  169. throw new RuntimeException(
  170. "WebViewChromiumFactoryProvider should only be set once!");
  171. }
  172. sSingleton = provider;
  173. }
  174. }
  175. /**
  176. * Thread-safe way to get the one and only WebViewChromiumFactoryProvider.
  177. */
  178. static WebViewChromiumFactoryProvider getSingleton() {
  179. synchronized (sSingletonLock) {
  180. if (sSingleton == null) {
  181. throw new RuntimeException("WebViewChromiumFactoryProvider has not been set!");
  182. }
  183. return sSingleton;
  184. }
  185. }
  186. /**
  187. * Entry point for Android 26 (Oreo) and above. See class docs for initialization details.
  188. */
  189. public static WebViewChromiumFactoryProvider create(WebViewDelegate delegate) {
  190. return new WebViewChromiumFactoryProvider(delegate);
  191. }
  192. /**
  193. * Entry point for Android 22 (LMR1) through Android 25 (NMR1). Although this is still invoked
  194. * by {@link #create}, this constructor was invoked directly before {@link #create} was defined.
  195. * See class docs for initialization details.
  196. */
  197. public WebViewChromiumFactoryProvider(WebViewDelegate delegate) {
  198. initialize(delegate);
  199. }
  200. // Protected to allow downstream to override.
  201. protected WebViewChromiumAwInit createAwInit() {
  202. try (ScopedSysTraceEvent e2 =
  203. ScopedSysTraceEvent.scoped("WebViewChromiumFactoryProvider.createAwInit")) {
  204. return new WebViewChromiumAwInit(this);
  205. }
  206. }
  207. // Protected to allow downstream to override.
  208. protected ContentSettingsAdapter createContentSettingsAdapter(AwSettings settings) {
  209. return new ContentSettingsAdapter(settings);
  210. }
  211. private void deleteContentsOnPackageDowngrade(PackageInfo packageInfo) {
  212. try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped(
  213. "WebViewChromiumFactoryProvider.deleteContentsOnPackageDowngrade")) {
  214. // Use shared preference to check for package downgrade.
  215. // Since N, getSharedPreferences creates the preference dir if it doesn't exist,
  216. // causing a disk write.
  217. mWebViewPrefs = ContextUtils.getApplicationContext().getSharedPreferences(
  218. CHROMIUM_PREFS_NAME, Context.MODE_PRIVATE);
  219. int lastVersion = mWebViewPrefs.getInt(VERSION_CODE_PREF, 0);
  220. int currentVersion = packageInfo.versionCode;
  221. if (!versionCodeGE(currentVersion, lastVersion)) {
  222. // The WebView package has been downgraded since we last ran in this
  223. // application. Delete the WebView data directory's contents.
  224. String dataDir = PathUtils.getDataDirectory();
  225. Log.i(TAG,
  226. "WebView package downgraded from " + lastVersion + " to "
  227. + currentVersion + "; deleting contents of " + dataDir);
  228. deleteContents(new File(dataDir));
  229. }
  230. if (lastVersion != currentVersion) {
  231. mWebViewPrefs.edit().putInt(VERSION_CODE_PREF, currentVersion).apply();
  232. }
  233. }
  234. }
  235. /**
  236. * This must not be called until {@link #initialize(WebViewDelegate)} has set mWebViewDelegate.
  237. */
  238. public void addWebViewAssetPath(Context ctx) {
  239. mWebViewDelegate.addWebViewAssetPath(new ContextWrapper(ctx) {
  240. // In the Android framework (<= API level 23)
  241. // ContextThemeWrapper provides an implementation of
  242. // getResources() that may proxy to either the wrapped
  243. // context or a newly constructed context, but it does not
  244. // provide an implementation of getAssets() that overrides
  245. // the ContextWrapper implementation that always proxies
  246. // to the wrapped context. This means that getAssets() and
  247. // getResources().getAssets() may potentially return
  248. // different AssetManagers, confusing WebView.
  249. //
  250. // To work around this problem, we provide an additional
  251. // wrapper here here to avoid calling the getAssets()
  252. // proxy chain (which we cannot change because it is in
  253. // WebView framework code).
  254. //
  255. // We should be able to remove this workaround once we
  256. // drop support for API 23.
  257. @Override
  258. public AssetManager getAssets() {
  259. return getResources().getAssets();
  260. }
  261. });
  262. }
  263. @SuppressWarnings("NoContextGetApplicationContext")
  264. private void initialize(WebViewDelegate webViewDelegate) {
  265. long startTime = SystemClock.uptimeMillis();
  266. try (ScopedSysTraceEvent e1 =
  267. ScopedSysTraceEvent.scoped("WebViewChromiumFactoryProvider.initialize")) {
  268. PackageInfo packageInfo;
  269. try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped(
  270. "WebViewChromiumFactoryProvider.getLoadedPackageInfo")) {
  271. // The package is used to locate the services for copying crash minidumps and
  272. // requesting variations seeds. So it must be set before initializing variations and
  273. // before a renderer has a chance to crash.
  274. packageInfo = WebViewFactory.getLoadedPackageInfo();
  275. }
  276. AwBrowserProcess.setWebViewPackageName(packageInfo.packageName);
  277. AwBrowserProcess.initializeApkType(packageInfo.applicationInfo);
  278. mAwInit = createAwInit();
  279. mWebViewDelegate = webViewDelegate;
  280. Context ctx = webViewDelegate.getApplication().getApplicationContext();
  281. // If the application context is DE, but we have credentials, use a CE context instead
  282. try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped(
  283. "WebViewChromiumFactoryProvider.checkStorage")) {
  284. checkStorageIsNotDeviceProtected(webViewDelegate.getApplication());
  285. } catch (IllegalArgumentException e) {
  286. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  287. if (!GlueApiHelperForN.isUserUnlocked(ctx)) {
  288. throw e;
  289. }
  290. ctx = GlueApiHelperForN.createCredentialProtectedStorageContext(ctx);
  291. } else {
  292. assert false;
  293. }
  294. }
  295. // WebView needs to make sure to always use the wrapped application context.
  296. ctx = ClassLoaderContextWrapperFactory.get(ctx);
  297. ContextUtils.initApplicationContext(ctx);
  298. // Find the package ID for the package that WebView's resources come from.
  299. // This will be the donor package if there is one, not our main package.
  300. String resourcePackage = packageInfo.packageName;
  301. if (packageInfo.applicationInfo.metaData != null) {
  302. resourcePackage = packageInfo.applicationInfo.metaData.getString(
  303. "com.android.webview.WebViewDonorPackage", resourcePackage);
  304. }
  305. int packageId;
  306. try {
  307. packageId = webViewDelegate.getPackageId(ctx.getResources(), resourcePackage);
  308. } catch (RuntimeException e) {
  309. // We failed to find the package ID, which likely means this context's AssetManager
  310. // doesn't have WebView loaded in it. This may be because WebViewFactory doesn't add
  311. // the package persistently to ResourcesManager and the app's AssetManager has been
  312. // recreated. Try adding it again using WebViewDelegate, which does add it
  313. // persistently.
  314. addWebViewAssetPath(ctx);
  315. packageId = webViewDelegate.getPackageId(ctx.getResources(), resourcePackage);
  316. }
  317. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q
  318. && AwBrowserProcess.getApkType() != ApkType.TRICHROME
  319. && packageId > SHARED_LIBRARY_MAX_ID) {
  320. throw new RuntimeException("Package ID too high for WebView: " + packageId);
  321. }
  322. mAwInit.setUpResourcesOnBackgroundThread(packageId, ctx);
  323. try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped(
  324. "WebViewChromiumFactoryProvider.initCommandLine")) {
  325. // This may take ~20 ms only on userdebug devices.
  326. CommandLineUtil.initCommandLine();
  327. }
  328. boolean multiProcess = false;
  329. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  330. // Ask the system if multiprocess should be enabled on O+.
  331. multiProcess = GlueApiHelperForO.isMultiProcessEnabled(webViewDelegate);
  332. } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
  333. // Check the multiprocess developer setting directly on N.
  334. multiProcess = Settings.Global.getInt(ctx.getContentResolver(),
  335. Settings.Global.WEBVIEW_MULTIPROCESS, 0)
  336. == 1;
  337. }
  338. if (multiProcess) {
  339. CommandLine cl = CommandLine.getInstance();
  340. cl.appendSwitch(AwSwitches.WEBVIEW_SANDBOXED_RENDERER);
  341. }
  342. // Using concatenation rather than %s to allow values to be inlined by R8.
  343. Log.i(TAG,
  344. "Loaded version=" + VersionConstants.PRODUCT_VERSION + " minSdkVersion="
  345. + BuildConfig.MIN_SDK_VERSION + " isBundle=" + ProductConfig.IS_BUNDLE
  346. + " multiprocess=%s packageId=%s",
  347. multiProcess, packageId);
  348. // Enable modern SameSite cookie behavior if the app targets at least S.
  349. if (ctx.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.S) {
  350. CommandLine cl = CommandLine.getInstance();
  351. cl.appendSwitch(AwSwitches.WEBVIEW_ENABLE_MODERN_COOKIE_SAME_SITE);
  352. }
  353. int applicationFlags = ctx.getApplicationInfo().flags;
  354. boolean isAppDebuggable = (applicationFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
  355. boolean isOsDebuggable = BuildInfo.isDebugAndroid();
  356. // Enable logging JS console messages in system logs only if the app is debuggable or
  357. // it's a debugable android build.
  358. if (isAppDebuggable || isOsDebuggable) {
  359. CommandLine cl = CommandLine.getInstance();
  360. cl.appendSwitch(AwSwitches.WEBVIEW_LOG_JS_CONSOLE_MESSAGES);
  361. }
  362. String webViewPackageName = AwBrowserProcess.getWebViewPackageName();
  363. long developerModeStart = SystemClock.elapsedRealtime();
  364. boolean isDeveloperModeEnabled =
  365. DeveloperModeUtils.isDeveloperModeEnabled(webViewPackageName);
  366. long developerModeEnd = SystemClock.elapsedRealtime();
  367. RecordHistogram.recordTimesHistogram("Android.WebView.DevUi.DeveloperModeBlockingTime",
  368. developerModeEnd - developerModeStart);
  369. RecordHistogram.recordBooleanHistogram(
  370. "Android.WebView.DevUi.DeveloperModeEnabled", isDeveloperModeEnabled);
  371. Map<String, Boolean> flagOverrides = null;
  372. if (isDeveloperModeEnabled) {
  373. long start = SystemClock.elapsedRealtime();
  374. try {
  375. FlagOverrideHelper helper =
  376. new FlagOverrideHelper(ProductionSupportedFlagList.sFlagList);
  377. flagOverrides = DeveloperModeUtils.getFlagOverrides(webViewPackageName);
  378. helper.applyFlagOverrides(flagOverrides);
  379. RecordHistogram.recordCount100Histogram(
  380. "Android.WebView.DevUi.ToggledFlagCount", flagOverrides.size());
  381. } finally {
  382. long end = SystemClock.elapsedRealtime();
  383. RecordHistogram.recordTimesHistogram(
  384. "Android.WebView.DevUi.FlagLoadingBlockingTime", end - start);
  385. }
  386. }
  387. ThreadUtils.setWillOverrideUiThread(true);
  388. BuildInfo.setBrowserPackageInfo(packageInfo);
  389. BuildInfo.setFirebaseAppId(
  390. FirebaseConfig.getFirebaseAppIdForPackage(packageInfo.packageName));
  391. try (StrictModeContext ignored = StrictModeContext.allowDiskWrites()) {
  392. try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped(
  393. "WebViewChromiumFactoryProvider.loadChromiumLibrary")) {
  394. String dataDirectorySuffix = null;
  395. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
  396. dataDirectorySuffix =
  397. GlueApiHelperForP.getDataDirectorySuffix(webViewDelegate);
  398. }
  399. AwBrowserProcess.loadLibrary(dataDirectorySuffix);
  400. }
  401. try (ScopedSysTraceEvent e2 = ScopedSysTraceEvent.scoped(
  402. "WebViewChromiumFactoryProvider.loadGlueLayerPlatSupportLibrary")) {
  403. System.loadLibrary("webviewchromium_plat_support");
  404. }
  405. deleteContentsOnPackageDowngrade(packageInfo);
  406. }
  407. // Now safe to use WebView data directory.
  408. if (flagOverrides != null) {
  409. AwContentsStatics.logFlagOverridesWithNative(flagOverrides);
  410. }
  411. SafeModeController controller = SafeModeController.getInstance();
  412. controller.registerActions(BrowserSafeModeActionList.sList);
  413. long safeModeStart = SystemClock.elapsedRealtime();
  414. mIsSafeModeEnabled = controller.isSafeModeEnabled(webViewPackageName);
  415. long safeModeEnd = SystemClock.elapsedRealtime();
  416. RecordHistogram.recordTimesHistogram(
  417. "Android.WebView.SafeMode.CheckStateBlockingTime", safeModeEnd - safeModeStart);
  418. RecordHistogram.recordBooleanHistogram(
  419. "Android.WebView.SafeMode.SafeModeEnabled", mIsSafeModeEnabled);
  420. if (mIsSafeModeEnabled) {
  421. try {
  422. long safeModeQueryExecuteStart = SystemClock.elapsedRealtime();
  423. Set<String> actions = controller.queryActions(webViewPackageName);
  424. Log.w(TAG, "WebViewSafeMode is enabled: received %d SafeModeActions",
  425. actions.size());
  426. RecordHistogram.recordCount100Histogram(
  427. "Android.WebView.SafeMode.ActionsCount", actions.size());
  428. boolean success = controller.executeActions(actions);
  429. long safeModeQueryExecuteEnd = SystemClock.elapsedRealtime();
  430. RecordHistogram.recordTimesHistogram(
  431. "Android.WebView.SafeMode.QueryAndExecuteBlockingTime",
  432. safeModeQueryExecuteEnd - safeModeQueryExecuteStart);
  433. if (success) {
  434. logSafeModeExecutionResult(SafeModeExecutionResult.SUCCESS);
  435. } else {
  436. logSafeModeExecutionResult(SafeModeExecutionResult.ACTION_FAILED);
  437. }
  438. } catch (Throwable t) {
  439. // Don't let SafeMode crash WebView. Instead just log the error.
  440. Log.e(TAG, "WebViewSafeMode threw exception: ", t);
  441. logSafeModeExecutionResult(SafeModeExecutionResult.UNKNOWN_ERROR);
  442. }
  443. }
  444. mAwInit.startVariationsInit();
  445. mShouldDisableThreadChecking = shouldDisableThreadChecking(ctx);
  446. setSingleton(this);
  447. // sWebLayerRunningInSameProcess may have been set before initialize().
  448. if (sWebLayerRunningInSameProcess) {
  449. addTask(() -> { getBrowserContextOnUiThread().setWebLayerRunningInSameProcess(); });
  450. }
  451. }
  452. RecordHistogram.recordTimesHistogram(
  453. "Android.WebView.Startup.CreationTime.Stage1.FactoryInit",
  454. SystemClock.uptimeMillis() - startTime);
  455. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
  456. final long webviewLoadStart =
  457. mWebViewDelegate.getStartupTimestamps().getWebViewLoadStart();
  458. RecordHistogram.recordTimesHistogram(
  459. "Android.WebView.Startup.CreationTime.TotalFactoryInitTime",
  460. SystemClock.uptimeMillis() - webviewLoadStart);
  461. }
  462. }
  463. // These values are persisted to logs. Entries should not be renumbered and
  464. // numeric values should never be reused.
  465. @IntDef({SafeModeExecutionResult.SUCCESS, SafeModeExecutionResult.UNKNOWN_ERROR,
  466. SafeModeExecutionResult.ACTION_FAILED})
  467. private @interface SafeModeExecutionResult {
  468. int SUCCESS = 0;
  469. int UNKNOWN_ERROR = 1;
  470. int ACTION_FAILED = 2;
  471. int COUNT = 3;
  472. }
  473. private static void logSafeModeExecutionResult(@SafeModeExecutionResult int result) {
  474. RecordHistogram.recordEnumeratedHistogram(
  475. "Android.WebView.SafeMode.ExecutionResult", result, SafeModeExecutionResult.COUNT);
  476. }
  477. /* package */ static void checkStorageIsNotDeviceProtected(Context context) {
  478. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N
  479. && GlueApiHelperForN.isDeviceProtectedStorage(context)) {
  480. throw new IllegalArgumentException(
  481. "WebView cannot be used with device protected storage");
  482. }
  483. }
  484. /**
  485. * Both versionCodes should be from a WebView provider package implemented by Chromium.
  486. * VersionCodes from other kinds of packages won't make any sense in this method.
  487. *
  488. * An introduction to Chromium versionCode scheme:
  489. * "BBBBPPPAX"
  490. * BBBB: 4 digit branch number. It monotonically increases over time.
  491. * PPP: patch number in the branch. It is padded with zeroes to the left. These three digits may
  492. * change their meaning in the future.
  493. * A: architecture digit.
  494. * X: A digit to differentiate APKs for other reasons.
  495. *
  496. * This method takes the "BBBB" of versionCodes and compare them.
  497. *
  498. * @return true if versionCode1 is higher than or equal to versionCode2.
  499. */
  500. private static boolean versionCodeGE(int versionCode1, int versionCode2) {
  501. int v1 = versionCode1 / 100000;
  502. int v2 = versionCode2 / 100000;
  503. return v1 >= v2;
  504. }
  505. private static void deleteContents(File dir) {
  506. File[] files = dir.listFiles();
  507. if (files != null) {
  508. for (File file : files) {
  509. if (file.isDirectory()) {
  510. deleteContents(file);
  511. }
  512. if (!file.delete()) {
  513. Log.w(TAG, "Failed to delete " + file);
  514. }
  515. }
  516. }
  517. }
  518. public static boolean preloadInZygote() {
  519. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O
  520. && Build.VERSION.SDK_INT < Build.VERSION_CODES.P && ProductConfig.IS_BUNDLE) {
  521. // Apply workaround if we're a bundle on O, where the split APK handling bug exists.
  522. SplitApkWorkaround.apply();
  523. }
  524. for (String library : NativeLibraries.LIBRARIES) {
  525. System.loadLibrary(library);
  526. }
  527. return true;
  528. }
  529. SharedPreferences getWebViewPrefs() {
  530. return mWebViewPrefs;
  531. }
  532. @Override
  533. public Statics getStatics() {
  534. synchronized (mAwInit.getLock()) {
  535. SharedStatics sharedStatics = mAwInit.getStatics();
  536. if (mStaticsAdapter == null) {
  537. mStaticsAdapter = new WebViewChromiumFactoryProvider.Statics() {
  538. @Override
  539. public String findAddress(String addr) {
  540. return sharedStatics.findAddress(addr);
  541. }
  542. @Override
  543. public String getDefaultUserAgent(Context context) {
  544. return sharedStatics.getDefaultUserAgent(context);
  545. }
  546. @Override
  547. public void setWebContentsDebuggingEnabled(boolean enable) {
  548. sharedStatics.setWebContentsDebuggingEnabled(enable);
  549. }
  550. @Override
  551. public void clearClientCertPreferences(Runnable onCleared) {
  552. sharedStatics.clearClientCertPreferences(onCleared);
  553. }
  554. @Override
  555. public void freeMemoryForTests() {
  556. sharedStatics.freeMemoryForTests();
  557. }
  558. @Override
  559. public void enableSlowWholeDocumentDraw() {
  560. sharedStatics.enableSlowWholeDocumentDraw();
  561. }
  562. @Override
  563. public Uri[] parseFileChooserResult(int resultCode, Intent intent) {
  564. return sharedStatics.parseFileChooserResult(resultCode, intent);
  565. }
  566. @Override
  567. public void initSafeBrowsing(Context context, ValueCallback<Boolean> callback) {
  568. sharedStatics.initSafeBrowsing(
  569. context, CallbackConverter.fromValueCallback(callback));
  570. }
  571. @Override
  572. public void setSafeBrowsingWhitelist(
  573. List<String> urls, ValueCallback<Boolean> callback) {
  574. sharedStatics.setSafeBrowsingAllowlist(
  575. urls, CallbackConverter.fromValueCallback(callback));
  576. }
  577. @Override
  578. public Uri getSafeBrowsingPrivacyPolicyUrl() {
  579. return sharedStatics.getSafeBrowsingPrivacyPolicyUrl();
  580. }
  581. public boolean isMultiProcessEnabled() {
  582. return sharedStatics.isMultiProcessEnabled();
  583. }
  584. public String getVariationsHeader() {
  585. return sharedStatics.getVariationsHeader();
  586. }
  587. };
  588. }
  589. }
  590. return mStaticsAdapter;
  591. }
  592. @Override
  593. public WebViewProvider createWebView(WebView webView, WebView.PrivateAccess privateAccess) {
  594. return new WebViewChromium(this, webView, privateAccess, mShouldDisableThreadChecking);
  595. }
  596. // Workaround for IME thread crashes on legacy OEM apps.
  597. private boolean shouldDisableThreadChecking(Context context) {
  598. String appName = context.getPackageName();
  599. int versionCode = PackageUtils.getPackageVersion(context, appName);
  600. int appTargetSdkVersion = context.getApplicationInfo().targetSdkVersion;
  601. if (versionCode == -1) return false;
  602. boolean shouldDisable = false;
  603. // crbug.com/651706
  604. final String lgeMailPackageId = "com.lge.email";
  605. if (lgeMailPackageId.equals(appName)) {
  606. if (appTargetSdkVersion > Build.VERSION_CODES.N) return false;
  607. if (LGEmailActionModeWorkaround.isSafeVersion(versionCode)) return false;
  608. shouldDisable = true;
  609. }
  610. // crbug.com/655759
  611. // Also want to cover ".att" variant suffix package name.
  612. final String yahooMailPackageId = "com.yahoo.mobile.client.android.mail";
  613. if (appName.startsWith(yahooMailPackageId)) {
  614. if (appTargetSdkVersion > Build.VERSION_CODES.M) return false;
  615. if (versionCode > 1315850) return false;
  616. shouldDisable = true;
  617. }
  618. // crbug.com/622151
  619. final String htcMailPackageId = "com.htc.android.mail";
  620. if (htcMailPackageId.equals(appName)) {
  621. if (appTargetSdkVersion > Build.VERSION_CODES.M) return false;
  622. // This value is provided by HTC.
  623. if (versionCode >= 866001861) return false;
  624. shouldDisable = true;
  625. }
  626. if (shouldDisable) {
  627. Log.w(TAG, "Disabling thread check in WebView. "
  628. + "APK name: " + appName + ", versionCode: " + versionCode
  629. + ", targetSdkVersion: " + appTargetSdkVersion);
  630. }
  631. return shouldDisable;
  632. }
  633. /**
  634. * Returns the cached SafeMode state. This must only be called after initialize(), which is when
  635. * the SafeMode state is cached.
  636. */
  637. public boolean isSafeModeEnabled() {
  638. return mIsSafeModeEnabled;
  639. }
  640. @Override
  641. public GeolocationPermissions getGeolocationPermissions() {
  642. return mAwInit.getGeolocationPermissions();
  643. }
  644. @Override
  645. public CookieManager getCookieManager() {
  646. return mAwInit.getCookieManager();
  647. }
  648. @RequiresApi(Build.VERSION_CODES.N)
  649. @Override
  650. public ServiceWorkerController getServiceWorkerController() {
  651. synchronized (mAwInit.getLock()) {
  652. if (mObjectHolderForN.mServiceWorkerController == null) {
  653. mObjectHolderForN.mServiceWorkerController =
  654. GlueApiHelperForN.createServiceWorkerControllerAdapter(mAwInit);
  655. }
  656. }
  657. return mObjectHolderForN.mServiceWorkerController;
  658. }
  659. @Override
  660. public TokenBindingService getTokenBindingService() {
  661. return null;
  662. }
  663. @Override
  664. public android.webkit.WebIconDatabase getWebIconDatabase() {
  665. return mAwInit.getWebIconDatabase();
  666. }
  667. @Override
  668. public WebStorage getWebStorage() {
  669. return mAwInit.getWebStorage();
  670. }
  671. @Override
  672. public WebViewDatabase getWebViewDatabase(final Context context) {
  673. return mAwInit.getWebViewDatabase(context);
  674. }
  675. WebViewDelegate getWebViewDelegate() {
  676. return mWebViewDelegate;
  677. }
  678. WebViewContentsClientAdapter createWebViewContentsClientAdapter(WebView webView,
  679. Context context) {
  680. try (ScopedSysTraceEvent e = ScopedSysTraceEvent.scoped(
  681. "WebViewChromiumFactoryProvider.insideCreateWebViewContentsClientAdapter")) {
  682. return new WebViewContentsClientAdapter(webView, context, mWebViewDelegate);
  683. }
  684. }
  685. void startYourEngines(boolean onMainThread) {
  686. try (ScopedSysTraceEvent e1 = ScopedSysTraceEvent.scoped(
  687. "WebViewChromiumFactoryProvider.startYourEngines")) {
  688. mAwInit.startYourEngines(onMainThread);
  689. }
  690. }
  691. boolean hasStarted() {
  692. return mAwInit.hasStarted();
  693. }
  694. // Only on UI thread.
  695. AwBrowserContext getBrowserContextOnUiThread() {
  696. return mAwInit.getBrowserContextOnUiThread();
  697. }
  698. WebViewChromiumAwInit getAwInit() {
  699. return mAwInit;
  700. }
  701. @RequiresApi(Build.VERSION_CODES.P)
  702. @Override
  703. public TracingController getTracingController() {
  704. synchronized (mAwInit.getLock()) {
  705. mAwInit.ensureChromiumStartedLocked(true);
  706. // ensureChromiumStartedLocked() can release the lock on first call while
  707. // waiting for startup. Hence check the mTracingController here to ensure
  708. // the singleton property.
  709. if (mObjectHolderForP.mTracingController == null) {
  710. mObjectHolderForP.mTracingController =
  711. GlueApiHelperForP.createTracingControllerAdapter(this, mAwInit);
  712. }
  713. }
  714. return mObjectHolderForP.mTracingController;
  715. }
  716. private static class FilteredClassLoader extends ClassLoader {
  717. FilteredClassLoader(ClassLoader delegate) {
  718. super(delegate);
  719. }
  720. @Override
  721. protected Class<?> findClass(String name) throws ClassNotFoundException {
  722. final String message =
  723. "This ClassLoader should only be used for the androidx.webkit support library";
  724. if (name == null) {
  725. throw new ClassNotFoundException(message);
  726. }
  727. // We only permit this ClassLoader to load classes required for support library
  728. // reflection, as applications should not use this for any other purpose. So, we permit
  729. // anything in the support_lib_glue and support_lib_boundary packages (and their
  730. // subpackages).
  731. if (name.startsWith(SUPPORT_LIB_GLUE_AND_BOUNDARY_INTERFACE_PREFIX)) {
  732. return super.findClass(name);
  733. }
  734. throw new ClassNotFoundException(message);
  735. }
  736. }
  737. @Override
  738. public ClassLoader getWebViewClassLoader() {
  739. return new FilteredClassLoader(WebViewChromiumFactoryProvider.class.getClassLoader());
  740. }
  741. // This is called from WebLayer when WebView and WebLayer are run in the same process. It's
  742. // used to set a crash key to help attribute crashes. It's entirely possible WebView has not
  743. // been initialized when this is called.
  744. public static void setWebLayerRunningInSameProcess() {
  745. // This may be called before initialize().
  746. synchronized (sSingletonLock) {
  747. sWebLayerRunningInSameProcess = true;
  748. if (sSingleton == null) {
  749. // initialize() hasn't been called yet. When initialize() is called
  750. // |sWebLayerRunningInSameProcess| will be checked.
  751. return;
  752. }
  753. }
  754. getSingleton().addTask(() -> {
  755. getSingleton().getBrowserContextOnUiThread().setWebLayerRunningInSameProcess();
  756. });
  757. }
  758. @RequiresApi(Build.VERSION_CODES.R)
  759. @Override
  760. public PacProcessor getPacProcessor() {
  761. return GlueApiHelperForR.getPacProcessor();
  762. }
  763. @RequiresApi(Build.VERSION_CODES.R)
  764. @Override
  765. public PacProcessor createPacProcessor() {
  766. return GlueApiHelperForR.createPacProcessor();
  767. }
  768. }