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