WebViewFactory.java revision 03c76e2b55e25fc22b8024124470e486b932c283
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    public static String getWebViewPackageName() {
80        return AppGlobals.getInitialApplication().getString(
81                com.android.internal.R.string.config_webViewPackageName);
82    }
83
84    public static PackageInfo getLoadedPackageInfo() {
85        return sPackageInfo;
86    }
87
88    static WebViewFactoryProvider getProvider() {
89        synchronized (sProviderLock) {
90            // For now the main purpose of this function (and the factory abstraction) is to keep
91            // us honest and minimize usage of WebView internals when binding the proxy.
92            if (sProviderInstance != null) return sProviderInstance;
93
94            final int uid = android.os.Process.myUid();
95            if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID) {
96                throw new UnsupportedOperationException(
97                        "For security reasons, WebView is not allowed in privileged processes");
98            }
99
100            Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getProvider()");
101            try {
102                Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.loadNativeLibrary()");
103                loadNativeLibrary();
104                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
105
106                Class<WebViewFactoryProvider> providerClass;
107                Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getFactoryClass()");
108                try {
109                    providerClass = getFactoryClass();
110                } catch (ClassNotFoundException e) {
111                    Log.e(LOGTAG, "error loading provider", e);
112                    throw new AndroidRuntimeException(e);
113                } finally {
114                    Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
115                }
116
117                StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
118                Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()");
119                try {
120                    sProviderInstance = providerClass.getConstructor(WebViewDelegate.class)
121                            .newInstance(new WebViewDelegate());
122                    if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance);
123                    return sProviderInstance;
124                } catch (Exception e) {
125                    Log.e(LOGTAG, "error instantiating provider", e);
126                    throw new AndroidRuntimeException(e);
127                } finally {
128                    Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
129                    StrictMode.setThreadPolicy(oldPolicy);
130                }
131            } finally {
132                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
133            }
134        }
135    }
136
137    private static Class<WebViewFactoryProvider> getFactoryClass() throws ClassNotFoundException {
138        Application initialApplication = AppGlobals.getInitialApplication();
139        try {
140            // First fetch the package info so we can log the webview package version.
141            String packageName = getWebViewPackageName();
142            sPackageInfo = initialApplication.getPackageManager().getPackageInfo(packageName, 0);
143            Log.i(LOGTAG, "Loading " + packageName + " version " + sPackageInfo.versionName +
144                          " (code " + sPackageInfo.versionCode + ")");
145
146            // Construct a package context to load the Java code into the current app.
147            Context webViewContext = initialApplication.createPackageContext(packageName,
148                    Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
149            initialApplication.getAssets().addAssetPath(
150                    webViewContext.getApplicationInfo().sourceDir);
151            ClassLoader clazzLoader = webViewContext.getClassLoader();
152            Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "Class.forName()");
153            try {
154                return (Class<WebViewFactoryProvider>) Class.forName(CHROMIUM_WEBVIEW_FACTORY, true,
155                                                                     clazzLoader);
156            } finally {
157                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
158            }
159        } catch (PackageManager.NameNotFoundException e) {
160            // If the package doesn't exist, then try loading the null WebView instead.
161            // If that succeeds, then this is a device without WebView support; if it fails then
162            // swallow the failure, complain that the real WebView is missing and rethrow the
163            // original exception.
164            try {
165                return (Class<WebViewFactoryProvider>) Class.forName(NULL_WEBVIEW_FACTORY);
166            } catch (ClassNotFoundException e2) {
167                // Ignore.
168            }
169            Log.e(LOGTAG, "Chromium WebView package does not exist", e);
170            throw new AndroidRuntimeException(e);
171        }
172    }
173
174    /**
175     * Perform any WebView loading preparations that must happen in the zygote.
176     * Currently, this means allocating address space to load the real JNI library later.
177     */
178    public static void prepareWebViewInZygote() {
179        try {
180            System.loadLibrary("webviewchromium_loader");
181            long addressSpaceToReserve =
182                    SystemProperties.getLong(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY,
183                    CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES);
184            sAddressSpaceReserved = nativeReserveAddressSpace(addressSpaceToReserve);
185
186            if (sAddressSpaceReserved) {
187                if (DEBUG) {
188                    Log.v(LOGTAG, "address space reserved: " + addressSpaceToReserve + " bytes");
189                }
190            } else {
191                Log.e(LOGTAG, "reserving " + addressSpaceToReserve +
192                        " bytes of address space failed");
193            }
194        } catch (Throwable t) {
195            // Log and discard errors at this stage as we must not crash the zygote.
196            Log.e(LOGTAG, "error preparing native loader", t);
197        }
198    }
199
200    /**
201     * Perform any WebView loading preparations that must happen at boot from the system server,
202     * after the package manager has started or after an update to the webview is installed.
203     * This must be called in the system server.
204     * Currently, this means spawning the child processes which will create the relro files.
205     */
206    public static void prepareWebViewInSystemServer() {
207        String[] nativePaths = null;
208        try {
209            nativePaths = getWebViewNativeLibraryPaths();
210        } catch (Throwable t) {
211            // Log and discard errors at this stage as we must not crash the system server.
212            Log.e(LOGTAG, "error preparing webview native library", t);
213        }
214        prepareWebViewInSystemServer(nativePaths);
215    }
216
217    private static void prepareWebViewInSystemServer(String[] nativeLibraryPaths) {
218        if (DEBUG) Log.v(LOGTAG, "creating relro files");
219
220        // We must always trigger createRelRo regardless of the value of nativeLibraryPaths. Any
221        // unexpected values will be handled there to ensure that we trigger notifying any process
222        // waiting on relreo creation.
223        if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
224            if (DEBUG) Log.v(LOGTAG, "Create 32 bit relro");
225            createRelroFile(false /* is64Bit */, nativeLibraryPaths);
226        }
227
228        if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
229            if (DEBUG) Log.v(LOGTAG, "Create 64 bit relro");
230            createRelroFile(true /* is64Bit */, nativeLibraryPaths);
231        }
232    }
233
234    public static void onWebViewUpdateInstalled() {
235        String[] nativeLibs = null;
236        try {
237            nativeLibs = WebViewFactory.getWebViewNativeLibraryPaths();
238            if (nativeLibs != null) {
239                long newVmSize = 0L;
240
241                for (String path : nativeLibs) {
242                    if (DEBUG) Log.d(LOGTAG, "Checking file size of " + path);
243                    if (path == null) continue;
244                    File f = new File(path);
245                    if (f.exists()) {
246                        long length = f.length();
247                        if (length > newVmSize) {
248                            newVmSize = length;
249                        }
250                    }
251                }
252
253                if (DEBUG) {
254                    Log.v(LOGTAG, "Based on library size, need " + newVmSize +
255                            " bytes of address space.");
256                }
257                // The required memory can be larger than the file on disk (due to .bss), and an
258                // upgraded version of the library will likely be larger, so always attempt to
259                // reserve twice as much as we think to allow for the library to grow during this
260                // boot cycle.
261                newVmSize = Math.max(2 * newVmSize, CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES);
262                Log.d(LOGTAG, "Setting new address space to " + newVmSize);
263                SystemProperties.set(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY,
264                        Long.toString(newVmSize));
265            }
266        } catch (Throwable t) {
267            // Log and discard errors at this stage as we must not crash the system server.
268            Log.e(LOGTAG, "error preparing webview native library", t);
269        }
270        prepareWebViewInSystemServer(nativeLibs);
271    }
272
273    private static String[] getWebViewNativeLibraryPaths()
274            throws PackageManager.NameNotFoundException {
275        final String NATIVE_LIB_FILE_NAME = "libwebviewchromium.so";
276
277        PackageManager pm = AppGlobals.getInitialApplication().getPackageManager();
278        ApplicationInfo ai = pm.getApplicationInfo(getWebViewPackageName(), 0);
279
280        String path32;
281        String path64;
282        boolean primaryArchIs64bit = VMRuntime.is64BitAbi(ai.primaryCpuAbi);
283        if (!TextUtils.isEmpty(ai.secondaryCpuAbi)) {
284            // Multi-arch case.
285            if (primaryArchIs64bit) {
286                // Primary arch: 64-bit, secondary: 32-bit.
287                path64 = ai.nativeLibraryDir;
288                path32 = ai.secondaryNativeLibraryDir;
289            } else {
290                // Primary arch: 32-bit, secondary: 64-bit.
291                path64 = ai.secondaryNativeLibraryDir;
292                path32 = ai.nativeLibraryDir;
293            }
294        } else if (primaryArchIs64bit) {
295            // Single-arch 64-bit.
296            path64 = ai.nativeLibraryDir;
297            path32 = "";
298        } else {
299            // Single-arch 32-bit.
300            path32 = ai.nativeLibraryDir;
301            path64 = "";
302        }
303        if (!TextUtils.isEmpty(path32)) path32 += "/" + NATIVE_LIB_FILE_NAME;
304        if (!TextUtils.isEmpty(path64)) path64 += "/" + NATIVE_LIB_FILE_NAME;
305        return new String[] { path32, path64 };
306    }
307
308    private static void createRelroFile(final boolean is64Bit, String[] nativeLibraryPaths) {
309        final String abi =
310                is64Bit ? Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
311
312        // crashHandler is invoked by the ActivityManagerService when the isolated process crashes.
313        Runnable crashHandler = new Runnable() {
314            @Override
315            public void run() {
316                try {
317                    Log.e(LOGTAG, "relro file creator for " + abi + " crashed. Proceeding without");
318                    getUpdateService().notifyRelroCreationCompleted(is64Bit, false);
319                } catch (RemoteException e) {
320                    Log.e(LOGTAG, "Cannot reach WebViewUpdateService. " + e.getMessage());
321                }
322            }
323        };
324
325        try {
326            if (nativeLibraryPaths == null
327                    || nativeLibraryPaths[0] == null || nativeLibraryPaths[1] == null) {
328                throw new IllegalArgumentException(
329                        "Native library paths to the WebView RelRo process must not be null!");
330            }
331            int pid = LocalServices.getService(ActivityManagerInternal.class).startIsolatedProcess(
332                    RelroFileCreator.class.getName(), nativeLibraryPaths, "WebViewLoader-" + abi, abi,
333                    Process.SHARED_RELRO_UID, crashHandler);
334            if (pid <= 0) throw new Exception("Failed to start the relro file creator process");
335        } catch (Throwable t) {
336            // Log and discard errors as we must not crash the system server.
337            Log.e(LOGTAG, "error starting relro file creator for abi " + abi, t);
338            crashHandler.run();
339        }
340    }
341
342    private static class RelroFileCreator {
343        // Called in an unprivileged child process to create the relro file.
344        public static void main(String[] args) {
345            boolean result = false;
346            boolean is64Bit = VMRuntime.getRuntime().is64Bit();
347            try{
348                if (args.length != 2 || args[0] == null || args[1] == null) {
349                    Log.e(LOGTAG, "Invalid RelroFileCreator args: " + Arrays.toString(args));
350                    return;
351                }
352                Log.v(LOGTAG, "RelroFileCreator (64bit = " + is64Bit + "), " +
353                        " 32-bit lib: " + args[0] + ", 64-bit lib: " + args[1]);
354                if (!sAddressSpaceReserved) {
355                    Log.e(LOGTAG, "can't create relro file; address space not reserved");
356                    return;
357                }
358                result = nativeCreateRelroFile(args[0] /* path32 */,
359                                               args[1] /* path64 */,
360                                               CHROMIUM_WEBVIEW_NATIVE_RELRO_32,
361                                               CHROMIUM_WEBVIEW_NATIVE_RELRO_64);
362                if (result && DEBUG) Log.v(LOGTAG, "created relro file");
363            } finally {
364                // We must do our best to always notify the update service, even if something fails.
365                try {
366                    getUpdateService().notifyRelroCreationCompleted(is64Bit, result);
367                } catch (RemoteException e) {
368                    Log.e(LOGTAG, "error notifying update service", e);
369                }
370
371                if (!result) Log.e(LOGTAG, "failed to create relro file");
372
373                // Must explicitly exit or else this process will just sit around after we return.
374                System.exit(0);
375            }
376        }
377    }
378
379    private static void loadNativeLibrary() {
380        if (!sAddressSpaceReserved) {
381            Log.e(LOGTAG, "can't load with relro file; address space not reserved");
382            return;
383        }
384
385        try {
386            getUpdateService().waitForRelroCreationCompleted(VMRuntime.getRuntime().is64Bit());
387        } catch (RemoteException e) {
388            Log.e(LOGTAG, "error waiting for relro creation, proceeding without", e);
389            return;
390        }
391
392        try {
393            String[] args = getWebViewNativeLibraryPaths();
394            boolean result = nativeLoadWithRelroFile(args[0] /* path32 */,
395                                                     args[1] /* path64 */,
396                                                     CHROMIUM_WEBVIEW_NATIVE_RELRO_32,
397                                                     CHROMIUM_WEBVIEW_NATIVE_RELRO_64);
398            if (!result) {
399                Log.w(LOGTAG, "failed to load with relro file, proceeding without");
400            } else if (DEBUG) {
401                Log.v(LOGTAG, "loaded with relro file");
402            }
403        } catch (PackageManager.NameNotFoundException e) {
404            Log.e(LOGTAG, "Failed to list WebView package libraries for loadNativeLibrary", e);
405        }
406    }
407
408    private static IWebViewUpdateService getUpdateService() {
409        return IWebViewUpdateService.Stub.asInterface(ServiceManager.getService("webviewupdate"));
410    }
411
412    private static native boolean nativeReserveAddressSpace(long addressSpaceToReserve);
413    private static native boolean nativeCreateRelroFile(String lib32, String lib64,
414                                                        String relro32, String relro64);
415    private static native boolean nativeLoadWithRelroFile(String lib32, String lib64,
416                                                          String relro32, String relro64);
417}
418