WebViewFactory.java revision 26c82fff095ad551301111fb0cfca3719f8c3d67
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.Intent;
25import android.content.pm.ApplicationInfo;
26import android.content.pm.PackageInfo;
27import android.content.pm.PackageManager;
28import android.content.res.XmlResourceParser;
29import android.os.Build;
30import android.os.Process;
31import android.os.RemoteException;
32import android.os.ServiceManager;
33import android.os.StrictMode;
34import android.os.SystemProperties;
35import android.os.Trace;
36import android.provider.Settings;
37import android.provider.Settings.Secure;
38import android.text.TextUtils;
39import android.util.AndroidRuntimeException;
40import android.util.Log;
41
42import com.android.internal.util.XmlUtils;
43import com.android.server.LocalServices;
44
45import dalvik.system.VMRuntime;
46
47import java.io.File;
48import java.io.IOException;
49import java.util.ArrayList;
50import java.util.Arrays;
51import java.util.List;
52import java.util.zip.ZipEntry;
53import java.util.zip.ZipFile;
54
55import org.xmlpull.v1.XmlPullParserException;
56
57/**
58 * Top level factory, used creating all the main WebView implementation classes.
59 *
60 * @hide
61 */
62@SystemApi
63public final class WebViewFactory {
64
65    private static final String CHROMIUM_WEBVIEW_FACTORY =
66            "com.android.webview.chromium.WebViewChromiumFactoryProvider";
67
68    private static final String NULL_WEBVIEW_FACTORY =
69            "com.android.webview.nullwebview.NullWebViewFactoryProvider";
70
71    private static final String CHROMIUM_WEBVIEW_NATIVE_RELRO_32 =
72            "/data/misc/shared_relro/libwebviewchromium32.relro";
73    private static final String CHROMIUM_WEBVIEW_NATIVE_RELRO_64 =
74            "/data/misc/shared_relro/libwebviewchromium64.relro";
75
76    public static final String CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY =
77            "persist.sys.webview.vmsize";
78    private static final long CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES = 100 * 1024 * 1024;
79
80    private static final String LOGTAG = "WebViewFactory";
81
82    private static final boolean DEBUG = false;
83
84    // Cache the factory both for efficiency, and ensure any one process gets all webviews from the
85    // same provider.
86    private static WebViewFactoryProvider sProviderInstance;
87    private static final Object sProviderLock = new Object();
88    private static boolean sAddressSpaceReserved = false;
89    private static PackageInfo sPackageInfo;
90
91    // Error codes for loadWebViewNativeLibraryFromPackage
92    public static final int LIBLOAD_SUCCESS = 0;
93    public static final int LIBLOAD_WRONG_PACKAGE_NAME = 1;
94    public static final int LIBLOAD_ADDRESS_SPACE_NOT_RESERVED = 2;
95
96    // error codes for waiting for WebView preparation
97    public static final int LIBLOAD_FAILED_WAITING_FOR_RELRO = 3;
98    public static final int LIBLOAD_FAILED_LISTING_WEBVIEW_PACKAGES = 4;
99
100    // native relro loading error codes
101    public static final int LIBLOAD_FAILED_TO_OPEN_RELRO_FILE = 5;
102    public static final int LIBLOAD_FAILED_TO_LOAD_LIBRARY = 6;
103    public static final int LIBLOAD_FAILED_JNI_CALL = 7;
104
105    // more error codes for waiting for WebView preparation
106    public static final int LIBLOAD_FAILED_WAITING_FOR_WEBVIEW_REASON_UNKNOWN = 8;
107
108    // error for namespace lookup
109    public static final int LIBLOAD_FAILED_TO_FIND_NAMESPACE = 10;
110
111    private static String getWebViewPreparationErrorReason(int error) {
112        switch (error) {
113            case LIBLOAD_FAILED_WAITING_FOR_RELRO:
114                return "Time out waiting for Relro files being created";
115            case LIBLOAD_FAILED_LISTING_WEBVIEW_PACKAGES:
116                return "No WebView installed";
117            case LIBLOAD_FAILED_WAITING_FOR_WEBVIEW_REASON_UNKNOWN:
118                return "Crashed for unknown reason";
119        }
120        return "Unknown";
121    }
122
123    /**
124     * @hide
125     */
126    public static class MissingWebViewPackageException extends AndroidRuntimeException {
127        public MissingWebViewPackageException(String message) { super(message); }
128        public MissingWebViewPackageException(Exception e) { super(e); }
129    }
130
131    private static String TAG_START = "webviewproviders";
132    private static String TAG_WEBVIEW_PROVIDER = "webviewprovider";
133    private static String TAG_PACKAGE_NAME = "packageName";
134    private static String TAG_DESCRIPTION = "description";
135    // Whether or not the provider must be explicitly chosen by the user to be used.
136    private static String TAG_AVAILABILITY = "availableByDefault";
137    private static String TAG_SIGNATURE = "signature";
138    private static String TAG_FALLBACK = "isFallback";
139
140    /**
141     * Reads all signatures at the current depth (within the current provider) from the XML parser.
142     */
143    private static String[] readSignatures(XmlResourceParser parser) throws IOException,
144            XmlPullParserException {
145        List<String> signatures = new ArrayList<String>();
146        int outerDepth = parser.getDepth();
147        while(XmlUtils.nextElementWithin(parser, outerDepth)) {
148            if (parser.getName().equals(TAG_SIGNATURE)) {
149                // Parse the value within the signature tag
150                String signature = parser.nextText();
151                signatures.add(signature);
152            } else {
153                Log.e(LOGTAG, "Found an element in a webview provider that is not a signature");
154            }
155        }
156        return signatures.toArray(new String[signatures.size()]);
157    }
158
159    /**
160     * Returns all packages declared in the framework resources as potential WebView providers.
161     * @hide
162     * */
163    public static WebViewProviderInfo[] getWebViewPackages() {
164        int numFallbackPackages = 0;
165        XmlResourceParser parser = null;
166        List<WebViewProviderInfo> webViewProviders = new ArrayList<WebViewProviderInfo>();
167        try {
168            parser = AppGlobals.getInitialApplication().getResources().getXml(
169                    com.android.internal.R.xml.config_webview_packages);
170            XmlUtils.beginDocument(parser, TAG_START);
171            while(true) {
172                XmlUtils.nextElement(parser);
173                String element = parser.getName();
174                if (element == null) {
175                    break;
176                }
177                if (element.equals(TAG_WEBVIEW_PROVIDER)) {
178                    String packageName = parser.getAttributeValue(null, TAG_PACKAGE_NAME);
179                    if (packageName == null) {
180                        throw new MissingWebViewPackageException(
181                                "WebView provider in framework resources missing package name");
182                    }
183                    String description = parser.getAttributeValue(null, TAG_DESCRIPTION);
184                    if (description == null) {
185                        throw new MissingWebViewPackageException(
186                                "WebView provider in framework resources missing description");
187                    }
188                    boolean availableByDefault = "true".equals(
189                            parser.getAttributeValue(null, TAG_AVAILABILITY));
190                    boolean isFallback = "true".equals(
191                            parser.getAttributeValue(null, TAG_FALLBACK));
192                    WebViewProviderInfo currentProvider =
193                            new WebViewProviderInfo(packageName, description, availableByDefault,
194                                isFallback, readSignatures(parser));
195                    if (currentProvider.isFallbackPackage()) {
196                        numFallbackPackages++;
197                        if (numFallbackPackages > 1) {
198                            throw new AndroidRuntimeException(
199                                    "There can be at most one webview fallback package.");
200                        }
201                    }
202                    webViewProviders.add(currentProvider);
203                }
204                else {
205                    Log.e(LOGTAG, "Found an element that is not a webview provider");
206                }
207            }
208        } catch(XmlPullParserException e) {
209            throw new MissingWebViewPackageException("Error when parsing WebView meta data " + e);
210        } catch(IOException e) {
211            throw new MissingWebViewPackageException("Error when parsing WebView meta data " + e);
212        } finally {
213            if (parser != null) parser.close();
214        }
215        return webViewProviders.toArray(new WebViewProviderInfo[webViewProviders.size()]);
216    }
217
218
219    // TODO (gsennton) remove when committing webview xts test change
220    public static String getWebViewPackageName() {
221        WebViewProviderInfo[] providers = getWebViewPackages();
222        return providers[0].packageName;
223    }
224
225    /**
226     * @hide
227     */
228    public static String getWebViewLibrary(ApplicationInfo ai) {
229        if (ai.metaData != null)
230            return ai.metaData.getString("com.android.webview.WebViewLibrary");
231        return null;
232    }
233
234    public static PackageInfo getLoadedPackageInfo() {
235        return sPackageInfo;
236    }
237
238    /**
239     * Load the native library for the given package name iff that package
240     * name is the same as the one providing the webview.
241     */
242    public static int loadWebViewNativeLibraryFromPackage(String packageName,
243                                                          ClassLoader clazzLoader) {
244        int ret = waitForProviderAndSetPackageInfo();
245        if (ret != LIBLOAD_SUCCESS) {
246            return ret;
247        }
248        if (!sPackageInfo.packageName.equals(packageName))
249            return LIBLOAD_WRONG_PACKAGE_NAME;
250
251        return loadNativeLibrary(clazzLoader);
252    }
253
254    static WebViewFactoryProvider getProvider() {
255        synchronized (sProviderLock) {
256            // For now the main purpose of this function (and the factory abstraction) is to keep
257            // us honest and minimize usage of WebView internals when binding the proxy.
258            if (sProviderInstance != null) return sProviderInstance;
259
260            final int uid = android.os.Process.myUid();
261            if (uid == android.os.Process.ROOT_UID || uid == android.os.Process.SYSTEM_UID) {
262                throw new UnsupportedOperationException(
263                        "For security reasons, WebView is not allowed in privileged processes");
264            }
265
266            StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
267            Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getProvider()");
268            try {
269                Class<WebViewFactoryProvider> providerClass = getProviderClass();
270
271                Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "providerClass.newInstance()");
272                try {
273                    sProviderInstance = providerClass.getConstructor(WebViewDelegate.class)
274                            .newInstance(new WebViewDelegate());
275                    if (DEBUG) Log.v(LOGTAG, "Loaded provider: " + sProviderInstance);
276                    return sProviderInstance;
277                } catch (Exception e) {
278                    Log.e(LOGTAG, "error instantiating provider", e);
279                    throw new AndroidRuntimeException(e);
280                } finally {
281                    Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
282                }
283            } finally {
284                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
285                StrictMode.setThreadPolicy(oldPolicy);
286            }
287        }
288    }
289
290    private static Class<WebViewFactoryProvider> getProviderClass() {
291        try {
292            Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW,
293                    "WebViewFactory.waitForProviderAndSetPackageInfo()");
294            try {
295                // First fetch the package info so we can log the webview package version.
296                int res = waitForProviderAndSetPackageInfo();
297                if (res != LIBLOAD_SUCCESS) {
298                    throw new MissingWebViewPackageException(
299                            "Failed to load WebView provider, error: "
300                            + getWebViewPreparationErrorReason(res));
301                }
302            } finally {
303                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
304            }
305            Log.i(LOGTAG, "Loading " + sPackageInfo.packageName + " version " +
306                sPackageInfo.versionName + " (code " + sPackageInfo.versionCode + ")");
307
308            Application initialApplication = AppGlobals.getInitialApplication();
309            Context webViewContext = null;
310            Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "PackageManager.getApplicationInfo()");
311            try {
312                // Construct a package context to load the Java code into the current app.
313                // This is done as early as possible since by constructing a package context we
314                // register the WebView package as a dependency for the current application so that
315                // when the WebView package is updated this application will be killed.
316                ApplicationInfo applicationInfo =
317                    initialApplication.getPackageManager().getApplicationInfo(
318                        sPackageInfo.packageName, PackageManager.GET_SHARED_LIBRARY_FILES
319                        | PackageManager.MATCH_DEBUG_TRIAGED_MISSING
320                        // make sure that we fetch the current provider even if its not installed
321                        // for the current user
322                        | PackageManager.MATCH_UNINSTALLED_PACKAGES);
323                Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW,
324                        "initialApplication.createApplicationContext");
325                try {
326                    webViewContext = initialApplication.createApplicationContext(applicationInfo,
327                            Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
328                } finally {
329                    Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
330                }
331            } catch (PackageManager.NameNotFoundException e) {
332                throw new MissingWebViewPackageException(e);
333            } finally {
334                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
335            }
336
337            Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.getChromiumProviderClass()");
338            try {
339                initialApplication.getAssets().addAssetPathAsSharedLibrary(
340                        webViewContext.getApplicationInfo().sourceDir);
341                ClassLoader clazzLoader = webViewContext.getClassLoader();
342
343                Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "WebViewFactory.loadNativeLibrary()");
344                loadNativeLibrary(clazzLoader);
345                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
346
347                Trace.traceBegin(Trace.TRACE_TAG_WEBVIEW, "Class.forName()");
348                try {
349                    return (Class<WebViewFactoryProvider>) Class.forName(CHROMIUM_WEBVIEW_FACTORY,
350                            true, clazzLoader);
351                } finally {
352                    Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
353                }
354            } catch (ClassNotFoundException e) {
355                Log.e(LOGTAG, "error loading provider", e);
356                throw new AndroidRuntimeException(e);
357            } finally {
358                Trace.traceEnd(Trace.TRACE_TAG_WEBVIEW);
359            }
360        } catch (MissingWebViewPackageException e) {
361            // If the package doesn't exist, then try loading the null WebView instead.
362            // If that succeeds, then this is a device without WebView support; if it fails then
363            // swallow the failure, complain that the real WebView is missing and rethrow the
364            // original exception.
365            try {
366                return (Class<WebViewFactoryProvider>) Class.forName(NULL_WEBVIEW_FACTORY);
367            } catch (ClassNotFoundException e2) {
368                // Ignore.
369            }
370            Log.e(LOGTAG, "Chromium WebView package does not exist", e);
371            throw new AndroidRuntimeException(e);
372        }
373    }
374
375    /**
376     * Perform any WebView loading preparations that must happen in the zygote.
377     * Currently, this means allocating address space to load the real JNI library later.
378     */
379    public static void prepareWebViewInZygote() {
380        try {
381            System.loadLibrary("webviewchromium_loader");
382            long addressSpaceToReserve =
383                    SystemProperties.getLong(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY,
384                    CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES);
385            sAddressSpaceReserved = nativeReserveAddressSpace(addressSpaceToReserve);
386
387            if (sAddressSpaceReserved) {
388                if (DEBUG) {
389                    Log.v(LOGTAG, "address space reserved: " + addressSpaceToReserve + " bytes");
390                }
391            } else {
392                Log.e(LOGTAG, "reserving " + addressSpaceToReserve +
393                        " bytes of address space failed");
394            }
395        } catch (Throwable t) {
396            // Log and discard errors at this stage as we must not crash the zygote.
397            Log.e(LOGTAG, "error preparing native loader", t);
398        }
399    }
400
401    private static int prepareWebViewInSystemServer(String[] nativeLibraryPaths) {
402        if (DEBUG) Log.v(LOGTAG, "creating relro files");
403        int numRelros = 0;
404
405        // We must always trigger createRelRo regardless of the value of nativeLibraryPaths. Any
406        // unexpected values will be handled there to ensure that we trigger notifying any process
407        // waiting on relro creation.
408        if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
409            if (DEBUG) Log.v(LOGTAG, "Create 32 bit relro");
410            createRelroFile(false /* is64Bit */, nativeLibraryPaths);
411            numRelros++;
412        }
413
414        if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
415            if (DEBUG) Log.v(LOGTAG, "Create 64 bit relro");
416            createRelroFile(true /* is64Bit */, nativeLibraryPaths);
417            numRelros++;
418        }
419        return numRelros;
420    }
421
422    /**
423     * @hide
424     */
425    public static int onWebViewProviderChanged(PackageInfo packageInfo) {
426        String[] nativeLibs = null;
427        try {
428            nativeLibs = WebViewFactory.getWebViewNativeLibraryPaths(packageInfo);
429            if (nativeLibs != null) {
430                long newVmSize = 0L;
431
432                for (String path : nativeLibs) {
433                    if (path == null || TextUtils.isEmpty(path)) continue;
434                    if (DEBUG) Log.d(LOGTAG, "Checking file size of " + path);
435                    File f = new File(path);
436                    if (f.exists()) {
437                        newVmSize = Math.max(newVmSize, f.length());
438                        continue;
439                    }
440                    if (path.contains("!/")) {
441                        String[] split = TextUtils.split(path, "!/");
442                        if (split.length == 2) {
443                            try (ZipFile z = new ZipFile(split[0])) {
444                                ZipEntry e = z.getEntry(split[1]);
445                                if (e != null && e.getMethod() == ZipEntry.STORED) {
446                                    newVmSize = Math.max(newVmSize, e.getSize());
447                                    continue;
448                                }
449                            }
450                            catch (IOException e) {
451                                Log.e(LOGTAG, "error reading APK file " + split[0] + ", ", e);
452                            }
453                        }
454                    }
455                    Log.e(LOGTAG, "error sizing load for " + path);
456                }
457
458                if (DEBUG) {
459                    Log.v(LOGTAG, "Based on library size, need " + newVmSize +
460                            " bytes of address space.");
461                }
462                // The required memory can be larger than the file on disk (due to .bss), and an
463                // upgraded version of the library will likely be larger, so always attempt to
464                // reserve twice as much as we think to allow for the library to grow during this
465                // boot cycle.
466                newVmSize = Math.max(2 * newVmSize, CHROMIUM_WEBVIEW_DEFAULT_VMSIZE_BYTES);
467                Log.d(LOGTAG, "Setting new address space to " + newVmSize);
468                SystemProperties.set(CHROMIUM_WEBVIEW_VMSIZE_SIZE_PROPERTY,
469                        Long.toString(newVmSize));
470            }
471        } catch (Throwable t) {
472            // Log and discard errors at this stage as we must not crash the system server.
473            Log.e(LOGTAG, "error preparing webview native library", t);
474        }
475        return prepareWebViewInSystemServer(nativeLibs);
476    }
477
478    // throws MissingWebViewPackageException
479    private static String getLoadFromApkPath(String apkPath,
480                                             String[] abiList,
481                                             String nativeLibFileName) {
482        // Search the APK for a native library conforming to a listed ABI.
483        try (ZipFile z = new ZipFile(apkPath)) {
484            for (String abi : abiList) {
485                final String entry = "lib/" + abi + "/" + nativeLibFileName;
486                ZipEntry e = z.getEntry(entry);
487                if (e != null && e.getMethod() == ZipEntry.STORED) {
488                    // Return a path formatted for dlopen() load from APK.
489                    return apkPath + "!/" + entry;
490                }
491            }
492        } catch (IOException e) {
493            throw new MissingWebViewPackageException(e);
494        }
495        return "";
496    }
497
498    // throws MissingWebViewPackageException
499    private static String[] getWebViewNativeLibraryPaths(PackageInfo packageInfo) {
500        ApplicationInfo ai = packageInfo.applicationInfo;
501        final String NATIVE_LIB_FILE_NAME = getWebViewLibrary(ai);
502
503        String path32;
504        String path64;
505        boolean primaryArchIs64bit = VMRuntime.is64BitAbi(ai.primaryCpuAbi);
506        if (!TextUtils.isEmpty(ai.secondaryCpuAbi)) {
507            // Multi-arch case.
508            if (primaryArchIs64bit) {
509                // Primary arch: 64-bit, secondary: 32-bit.
510                path64 = ai.nativeLibraryDir;
511                path32 = ai.secondaryNativeLibraryDir;
512            } else {
513                // Primary arch: 32-bit, secondary: 64-bit.
514                path64 = ai.secondaryNativeLibraryDir;
515                path32 = ai.nativeLibraryDir;
516            }
517        } else if (primaryArchIs64bit) {
518            // Single-arch 64-bit.
519            path64 = ai.nativeLibraryDir;
520            path32 = "";
521        } else {
522            // Single-arch 32-bit.
523            path32 = ai.nativeLibraryDir;
524            path64 = "";
525        }
526
527        // Form the full paths to the extracted native libraries.
528        // If libraries were not extracted, try load from APK paths instead.
529        if (!TextUtils.isEmpty(path32)) {
530            path32 += "/" + NATIVE_LIB_FILE_NAME;
531            File f = new File(path32);
532            if (!f.exists()) {
533                path32 = getLoadFromApkPath(ai.sourceDir,
534                                            Build.SUPPORTED_32_BIT_ABIS,
535                                            NATIVE_LIB_FILE_NAME);
536            }
537        }
538        if (!TextUtils.isEmpty(path64)) {
539            path64 += "/" + NATIVE_LIB_FILE_NAME;
540            File f = new File(path64);
541            if (!f.exists()) {
542                path64 = getLoadFromApkPath(ai.sourceDir,
543                                            Build.SUPPORTED_64_BIT_ABIS,
544                                            NATIVE_LIB_FILE_NAME);
545            }
546        }
547
548        if (DEBUG) Log.v(LOGTAG, "Native 32-bit lib: " + path32 + ", 64-bit lib: " + path64);
549        return new String[] { path32, path64 };
550    }
551
552    private static void createRelroFile(final boolean is64Bit, String[] nativeLibraryPaths) {
553        final String abi =
554                is64Bit ? Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
555
556        // crashHandler is invoked by the ActivityManagerService when the isolated process crashes.
557        Runnable crashHandler = new Runnable() {
558            @Override
559            public void run() {
560                try {
561                    Log.e(LOGTAG, "relro file creator for " + abi + " crashed. Proceeding without");
562                    getUpdateService().notifyRelroCreationCompleted();
563                } catch (RemoteException e) {
564                    Log.e(LOGTAG, "Cannot reach WebViewUpdateService. " + e.getMessage());
565                }
566            }
567        };
568
569        try {
570            if (nativeLibraryPaths == null
571                    || nativeLibraryPaths[0] == null || nativeLibraryPaths[1] == null) {
572                throw new IllegalArgumentException(
573                        "Native library paths to the WebView RelRo process must not be null!");
574            }
575            int pid = LocalServices.getService(ActivityManagerInternal.class).startIsolatedProcess(
576                    RelroFileCreator.class.getName(), nativeLibraryPaths, "WebViewLoader-" + abi, abi,
577                    Process.SHARED_RELRO_UID, crashHandler);
578            if (pid <= 0) throw new Exception("Failed to start the relro file creator process");
579        } catch (Throwable t) {
580            // Log and discard errors as we must not crash the system server.
581            Log.e(LOGTAG, "error starting relro file creator for abi " + abi, t);
582            crashHandler.run();
583        }
584    }
585
586    private static class RelroFileCreator {
587        // Called in an unprivileged child process to create the relro file.
588        public static void main(String[] args) {
589            boolean result = false;
590            boolean is64Bit = VMRuntime.getRuntime().is64Bit();
591            try{
592                if (args.length != 2 || args[0] == null || args[1] == null) {
593                    Log.e(LOGTAG, "Invalid RelroFileCreator args: " + Arrays.toString(args));
594                    return;
595                }
596                Log.v(LOGTAG, "RelroFileCreator (64bit = " + is64Bit + "), " +
597                        " 32-bit lib: " + args[0] + ", 64-bit lib: " + args[1]);
598                if (!sAddressSpaceReserved) {
599                    Log.e(LOGTAG, "can't create relro file; address space not reserved");
600                    return;
601                }
602                result = nativeCreateRelroFile(args[0] /* path32 */,
603                                               args[1] /* path64 */,
604                                               CHROMIUM_WEBVIEW_NATIVE_RELRO_32,
605                                               CHROMIUM_WEBVIEW_NATIVE_RELRO_64);
606                if (result && DEBUG) Log.v(LOGTAG, "created relro file");
607            } finally {
608                // We must do our best to always notify the update service, even if something fails.
609                try {
610                    getUpdateService().notifyRelroCreationCompleted();
611                } catch (RemoteException e) {
612                    Log.e(LOGTAG, "error notifying update service", e);
613                }
614
615                if (!result) Log.e(LOGTAG, "failed to create relro file");
616
617                // Must explicitly exit or else this process will just sit around after we return.
618                System.exit(0);
619            }
620        }
621    }
622
623    private static int waitForProviderAndSetPackageInfo() {
624        WebViewProviderResponse response = null;
625        try {
626            response =
627                getUpdateService().waitForAndGetProvider();
628            if (response.status == WebViewFactory.LIBLOAD_SUCCESS)
629                sPackageInfo = response.packageInfo;
630        } catch (RemoteException e) {
631            Log.e(LOGTAG, "error waiting for relro creation", e);
632            return LIBLOAD_FAILED_WAITING_FOR_WEBVIEW_REASON_UNKNOWN;
633        }
634        return response.status;
635    }
636
637    // Assumes that we have waited for relro creation and set sPackageInfo
638    private static int loadNativeLibrary(ClassLoader clazzLoader) {
639        if (!sAddressSpaceReserved) {
640            Log.e(LOGTAG, "can't load with relro file; address space not reserved");
641            return LIBLOAD_ADDRESS_SPACE_NOT_RESERVED;
642        }
643
644        String[] args = getWebViewNativeLibraryPaths(sPackageInfo);
645        int result = nativeLoadWithRelroFile(args[0] /* path32 */,
646                                             args[1] /* path64 */,
647                                             CHROMIUM_WEBVIEW_NATIVE_RELRO_32,
648                                             CHROMIUM_WEBVIEW_NATIVE_RELRO_64,
649                                             clazzLoader);
650        if (result != LIBLOAD_SUCCESS) {
651            Log.w(LOGTAG, "failed to load with relro file, proceeding without");
652        } else if (DEBUG) {
653            Log.v(LOGTAG, "loaded with relro file");
654        }
655        return result;
656    }
657
658    /**
659     * Returns whether the entire package from an ACTION_PACKAGE_CHANGED intent was changed (rather
660     * than just one of its components).
661     * @hide
662     */
663    public static boolean entirePackageChanged(Intent intent) {
664        String[] componentList =
665            intent.getStringArrayExtra(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST);
666        return Arrays.asList(componentList).contains(
667                intent.getDataString().substring("package:".length()));
668    }
669
670    private static IWebViewUpdateService getUpdateService() {
671        return IWebViewUpdateService.Stub.asInterface(ServiceManager.getService("webviewupdate"));
672    }
673
674    private static native boolean nativeReserveAddressSpace(long addressSpaceToReserve);
675    private static native boolean nativeCreateRelroFile(String lib32, String lib64,
676                                                        String relro32, String relro64);
677    private static native int nativeLoadWithRelroFile(String lib32, String lib64,
678                                                      String relro32, String relro64,
679                                                      ClassLoader clazzLoader);
680}
681