分享

WebViewProvider的创建

 wusiqi111 2019-09-27


private WebViewProvider mProvider

mProvider作为WebView中一个重要的成员变量,几乎大部分WebView的方法实际实现是在这个对象里的。那么这个对象究竟是如何创建的呢?

  1. private void ensureProviderCreated() {

  2. checkThread();

  3. if (mProvider == null) {

  4. // As this can get called during the base class constructor chain, pass the minimum

  5. // number of dependencies here; the rest are deferred to init().

  6. mProvider = getFactory().createWebView(this, new PrivateAccess());

  7. }

  8. }


这里的PrivateAccess是WebView的一个内部类 持有对WebView外部类的引用。它的功能是开放给mProvider对象访问WebView.super(也就是AbsoluteLayout)的部分功能的一个代理
  1. private static synchronized WebViewFactoryProvider getFactory() {

  2. return WebViewFactory.getProvider();

  3. }


WebViewFactory静态工厂方法 同步锁获取抽象工厂提供者 该方法的目的是最小化(通过代理)访问WebView内部
  1. static WebViewFactoryProvider getProvider() {

  2. synchronized (sProviderLock) {

  3. // For now the main purpose of this function (and the factory abstraction) is to keep

  4. // us honest and minimize usage of WebView internals when binding the proxy.

  5. if (sProviderInstance != null) return sProviderInstance;

  6. final int uid = android.os.Process.myUid();

  7. if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID) {

  8. throw new UnsupportedOperationException(

  9. "For security reasons, WebView is not allowed in privileged processes");

  10. //WebView 不可以在特权进程中 Root或者System

  11. }

  12. Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getProvider()");

  13. try {

  14. //通过这个方法获取到工厂提供者的类 用于下面的反射构造

  15. Class<WebViewFactoryProvider> providerClass = getProviderClass();

  16. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();

  17. Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()");

  18. try {

  19. //反射

  20. sProviderInstance = providerClass.getConstructor(WebViewDelegate.class)

  21. .newInstance(new WebViewDelegate());

  22. if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance);

  23. return sProviderInstance;

  24. } catch (Exception e) {

  25. Log.e(LOGTAG, "error instantiating provider", e);

  26. throw new AndroidRuntimeException(e);

  27. } finally {

  28. Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);

  29. StrictMode.setThreadPolicy(oldPolicy);

  30. }

  31. } finally {

  32. Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);

  33. }

  34. }

  35. }


getProvidedClass方法中先加载库 再创建工厂

方法中先调用了loadNativeLibrary(){

//做了三件事

//第一件:创建Relro只读

//Called in an unprivileged child process to create the relro file.在一个无特权的进程中创建relro文件

getUpdateService().waitForRelroCreationCompleted(VMRuntime.getRuntime().is64Bit()); 

//第二件:获取WebView的原生库所在路径 32位和64位的(依据cpu架构 )  

//getLoadFromApkPath的方法从Build.SUPPORTED_64(或32)_BIT_ABIS的abi列表拼接出可用apk路径,找到可以用来dlopen()挂载的那个zipEntry路径

//这里我们可以学到获取系统的WebView的PackageInfo信息是怎么获取的 getWebViewPackageName()->fetchPackageInfo()进一步可以通过getWebViewApplicationInfo()获取成员变量ApplicationInfo, WebViewLibrary的Path就是存在ApplicationInfo中的ai.metaData.getString("com.android.webview.WebViewLibrary") 

String[] args = getWebViewNativeLibraryPaths();

//第三件: 加载 这是一个jni的方法实现在C

int result = nativeLoadWithRelroFile(args[0] /* path32 */,
                                                     args[1] /* path64 */,
                                                     CHROMIUM_WEBVIEW_NATIVE_RELRO_32,
                                                     CHROMIUM_WEBVIEW_NATIVE_RELRO_64);

}

tips:

  1. RELRO

  2. 在Linux系统安全领域数据可以写的存储区就会是攻击的目标,尤其是存储函数指针的区域. 所以在安全防护的角度来说尽量减少可写的存储区域对安全会有极大的好处.

  3. GCC, GNU linker以及Glibc-dynamic linker一起配合实现了一种叫做relro的技术: read only relocation.大概实现就是由linker指定binary的一块经过dynamic linker处理过 relocation之后的区域为只读.

  4. RELRO设置符号重定向表格为只读或在程序启动时就解析并绑定所有动态符号,从而减少对GOT(Global Offset Table)攻击。

  5. 有关RELRO的技术细节 https://hardenedlinux.github.io/2016/11/25/RelRO.html。

  6. 有关GOT攻击的技术原理参考 http://blog.csdn.net/smalosnail/article/details/53247502。

继续来看工厂创建
  1. // throws MissingWebViewPackageException

  2. private static Class<WebViewFactoryProvider> getChromiumProviderClass()

  3. throws ClassNotFoundException {

  4. Application initialApplication = AppGlobals.getInitialApplication();

  5. //就是ActivityThread.currentApplication();

  6. try {

  7. // Construct a package context to load the Java code into the current app.

  8. //拿到webView的Package上下文

  9. Context webViewContext = initialApplication.createPackageContext(

  10. sPackageInfo.packageName,

  11. Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);

  12. //getAssets()是隐藏方法 你只能用反射哦 addAssetPath是AssetManager的native方法

  13. initialApplication.getAssets().addAssetPath(

  14. webViewContext.getApplicationInfo().sourceDir);

  15. //用webView的Package上下文拿到classLoader 保证能加载到

  16. ClassLoader clazzLoader = webViewContext.getClassLoader();

  17. Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "Class.forName()");

  18. try {

  19. //重点来了 最终的实现类 包名路径

  20. return (Class<WebViewFactoryProvider>) Class.forName(CHROMIUM_WEBVIEW_FACTORY, true,

  21. clazzLoader);

  22. } finally {

  23. Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);

  24. }

  25. } catch (PackageManager.NameNotFoundException e) {

  26. throw new MissingWebViewPackageException(e);

  27. }

  28. }


那么就来看看面纱下的CHROMIUM_WEBVIEW_FACTORY到底是啥 "com.android.webview.chromium.WebViewChromiumFactoryProvider" 

这个类在sdk 25 26中都找不到 最终在22下找到了对应的文件

sources\android-22\com\android\webview\chromium\WebViewChromiumFactoryProvider.java

记得前面反射的时候嘛 我们用的是有参的构造方法

  1. /**

  2. * Constructor called by the API 22 version of {@link WebViewFactory} and later.

  3. */

  4. public WebViewChromiumFactoryProvider(android.webkit.WebViewDelegate delegate) {

  5. initialize(WebViewDelegateFactory.createProxyDelegate(delegate));

  6. }

  7. private void initialize(WebViewDelegate webViewDelegate) {

  8. mWebViewDelegate = webViewDelegate;

  9. if (isBuildDebuggable()) {

  10. // Suppress the StrictMode violation as this codepath is only hit on debugglable builds.

  11. StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();

  12. CommandLine.initFromFile(COMMAND_LINE_FILE);

  13. StrictMode.setThreadPolicy(oldPolicy);

  14. } else {

  15. CommandLine.init(null);

  16. }

  17. CommandLine cl = CommandLine.getInstance();

  18. // TODO: currently in a relase build the DCHECKs only log. We either need to insall

  19. // a report handler with SetLogReportHandler to make them assert, or else compile

  20. // them out of the build altogether (b/8284203). Either way, so long they're

  21. // compiled in, we may as unconditionally enable them here.

  22. cl.appendSwitch("enable-dcheck");

  23. ThreadUtils.setWillOverrideUiThread();

  24. // Load chromium library.

  25. AwBrowserProcess.loadLibrary();

  26. // Load glue-layer support library.

  27. System.loadLibrary("webviewchromium_plat_support");

  28. // Use shared preference to check for package downgrade.

  29. mWebViewPrefs = mWebViewDelegate.getApplication().getSharedPreferences(

  30. CHROMIUM_PREFS_NAME, Context.MODE_PRIVATE);

  31. int lastVersion = mWebViewPrefs.getInt(VERSION_CODE_PREF, 0);

  32. int currentVersion = WebViewFactory.getLoadedPackageInfo().versionCode;

  33. if (lastVersion > currentVersion) {

  34. // The WebView package has been downgraded since we last ran in this application.

  35. // Delete the WebView data directory's contents.

  36. String dataDir = PathUtils.getDataDirectory(mWebViewDelegate.getApplication());

  37. Log.i(TAG, "WebView package downgraded from " + lastVersion + " to " + currentVersion +

  38. "; deleting contents of " + dataDir);

  39. deleteContents(new File(dataDir));

  40. }

  41. if (lastVersion != currentVersion) {

  42. mWebViewPrefs.edit().putInt(VERSION_CODE_PREF, currentVersion).apply();

  43. }

  44. // Now safe to use WebView data directory.

  45. }

用命令行加载库

这里我们要看的最重要方法就是createWebView

  1. @Override

  2. public WebViewProvider createWebView(WebView webView, WebView.PrivateAccess privateAccess) {

  3. WebViewChromium wvc = new WebViewChromium(this, webView, privateAccess);

  4. synchronized (mLock) {

  5. if (mWebViewsToStart != null) {

  6. mWebViewsToStart.add(new WeakReference<WebViewChromium>(wvc));

  7. }

  8. }

  9. return wvc;

  10. }

同样我们在22的源码中才能找到WebViewChromium.java
  1. // This does not touch any global / non-threadsafe state, but note that

  2. // init is ofter called right after and is NOT threadsafe.

  3. public WebViewChromium(WebViewChromiumFactoryProvider factory, WebView webView,

  4. WebView.PrivateAccess webViewPrivate) {

  5. mWebView = webView;

  6. mWebViewPrivate = webViewPrivate;

  7. mHitTestResult = new WebView.HitTestResult();

  8. mAppTargetSdkVersion = mWebView.getContext().getApplicationInfo().targetSdkVersion;

  9. mFactory = factory;

  10. mRunQueue = new WebViewChromiumRunQueue();

  11. factory.getWebViewDelegate().addWebViewAssetPath(mWebView.getContext());

  12. }

至此大功告成

接下来多问一句这里就是浏览器的实现嘛?我们都知道4.4以前的WebKit for Android已经被移除(external/WebKit目录),取代为chromium(chromium_org)。然而WebViewProvider的目的就是用接口实现实现隔离达到兼容的效果。以上我们看到的都是AOSP层的android源码,WebViewChromium实现类中的实际功能还是由 AwContents  或 ContentViewCore 实现的而这部分的代码是在Chromium Project层中(源码不可见)

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多