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