LoadedApk.java revision 9484603c0fa738b67980c18b4abfd3505778ae74
1/*
2 * Copyright (C) 2010 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.app;
18
19import android.annotation.NonNull;
20import android.annotation.Nullable;
21import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.IIntentReceiver;
25import android.content.Intent;
26import android.content.ServiceConnection;
27import android.content.pm.ApplicationInfo;
28import android.content.pm.IPackageManager;
29import android.content.pm.PackageManager;
30import android.content.pm.PackageManager.NameNotFoundException;
31import android.content.pm.split.SplitDependencyLoader;
32import android.content.res.AssetManager;
33import android.content.res.CompatibilityInfo;
34import android.content.res.Resources;
35import android.os.Build;
36import android.os.Bundle;
37import android.os.Environment;
38import android.os.FileUtils;
39import android.os.Handler;
40import android.os.IBinder;
41import android.os.Process;
42import android.os.RemoteException;
43import android.os.StrictMode;
44import android.os.SystemProperties;
45import android.os.Trace;
46import android.os.UserHandle;
47import android.text.TextUtils;
48import android.util.AndroidRuntimeException;
49import android.util.ArrayMap;
50import android.util.Log;
51import android.util.Slog;
52import android.util.SparseArray;
53import android.view.Display;
54import android.view.DisplayAdjustments;
55
56import com.android.internal.util.ArrayUtils;
57
58import dalvik.system.VMRuntime;
59
60import java.io.File;
61import java.io.IOException;
62import java.io.InputStream;
63import java.lang.ref.WeakReference;
64import java.lang.reflect.InvocationTargetException;
65import java.lang.reflect.Method;
66import java.net.URL;
67import java.util.ArrayList;
68import java.util.Arrays;
69import java.util.Collections;
70import java.util.Enumeration;
71import java.util.List;
72import java.util.Objects;
73
74final class IntentReceiverLeaked extends AndroidRuntimeException {
75    public IntentReceiverLeaked(String msg) {
76        super(msg);
77    }
78}
79
80final class ServiceConnectionLeaked extends AndroidRuntimeException {
81    public ServiceConnectionLeaked(String msg) {
82        super(msg);
83    }
84}
85
86/**
87 * Local state maintained about a currently loaded .apk.
88 * @hide
89 */
90public final class LoadedApk {
91    static final String TAG = "LoadedApk";
92    static final boolean DEBUG = false;
93
94    private final ActivityThread mActivityThread;
95    final String mPackageName;
96    private ApplicationInfo mApplicationInfo;
97    private String mAppDir;
98    private String mResDir;
99    private String[] mOverlayDirs;
100    private String[] mSharedLibraries;
101    private String mDataDir;
102    private String mLibDir;
103    private File mDataDirFile;
104    private File mDeviceProtectedDataDirFile;
105    private File mCredentialProtectedDataDirFile;
106    private final ClassLoader mBaseClassLoader;
107    private final boolean mSecurityViolation;
108    private final boolean mIncludeCode;
109    private final boolean mRegisterPackage;
110    private final DisplayAdjustments mDisplayAdjustments = new DisplayAdjustments();
111    /** WARNING: This may change. Don't hold external references to it. */
112    Resources mResources;
113    private ClassLoader mClassLoader;
114    private Application mApplication;
115
116    private String[] mSplitNames;
117    private String[] mSplitAppDirs;
118    private String[] mSplitResDirs;
119
120    private final ArrayMap<Context, ArrayMap<BroadcastReceiver, ReceiverDispatcher>> mReceivers
121        = new ArrayMap<>();
122    private final ArrayMap<Context, ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>> mUnregisteredReceivers
123        = new ArrayMap<>();
124    private final ArrayMap<Context, ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>> mServices
125        = new ArrayMap<>();
126    private final ArrayMap<Context, ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>> mUnboundServices
127        = new ArrayMap<>();
128
129    int mClientCount = 0;
130
131    Application getApplication() {
132        return mApplication;
133    }
134
135    /**
136     * Create information about a new .apk
137     *
138     * NOTE: This constructor is called with ActivityThread's lock held,
139     * so MUST NOT call back out to the activity manager.
140     */
141    public LoadedApk(ActivityThread activityThread, ApplicationInfo aInfo,
142            CompatibilityInfo compatInfo, ClassLoader baseLoader,
143            boolean securityViolation, boolean includeCode, boolean registerPackage) {
144
145        mActivityThread = activityThread;
146        setApplicationInfo(aInfo);
147        mPackageName = aInfo.packageName;
148        mBaseClassLoader = baseLoader;
149        mSecurityViolation = securityViolation;
150        mIncludeCode = includeCode;
151        mRegisterPackage = registerPackage;
152        mDisplayAdjustments.setCompatibilityInfo(compatInfo);
153    }
154
155    private static ApplicationInfo adjustNativeLibraryPaths(ApplicationInfo info) {
156        // If we're dealing with a multi-arch application that has both
157        // 32 and 64 bit shared libraries, we might need to choose the secondary
158        // depending on what the current runtime's instruction set is.
159        if (info.primaryCpuAbi != null && info.secondaryCpuAbi != null) {
160            final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
161
162            // Get the instruction set that the libraries of secondary Abi is supported.
163            // In presence of a native bridge this might be different than the one secondary Abi used.
164            String secondaryIsa = VMRuntime.getInstructionSet(info.secondaryCpuAbi);
165            final String secondaryDexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
166            secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
167
168            // If the runtimeIsa is the same as the primary isa, then we do nothing.
169            // Everything will be set up correctly because info.nativeLibraryDir will
170            // correspond to the right ISA.
171            if (runtimeIsa.equals(secondaryIsa)) {
172                final ApplicationInfo modified = new ApplicationInfo(info);
173                modified.nativeLibraryDir = modified.secondaryNativeLibraryDir;
174                modified.primaryCpuAbi = modified.secondaryCpuAbi;
175                return modified;
176            }
177        }
178
179        return info;
180    }
181
182    /**
183     * Create information about the system package.
184     * Must call {@link #installSystemApplicationInfo} later.
185     */
186    LoadedApk(ActivityThread activityThread) {
187        mActivityThread = activityThread;
188        mApplicationInfo = new ApplicationInfo();
189        mApplicationInfo.packageName = "android";
190        mPackageName = "android";
191        mAppDir = null;
192        mResDir = null;
193        mSplitAppDirs = null;
194        mSplitResDirs = null;
195        mOverlayDirs = null;
196        mSharedLibraries = null;
197        mDataDir = null;
198        mDataDirFile = null;
199        mDeviceProtectedDataDirFile = null;
200        mCredentialProtectedDataDirFile = null;
201        mLibDir = null;
202        mBaseClassLoader = null;
203        mSecurityViolation = false;
204        mIncludeCode = true;
205        mRegisterPackage = false;
206        mClassLoader = ClassLoader.getSystemClassLoader();
207        mResources = Resources.getSystem();
208    }
209
210    /**
211     * Sets application info about the system package.
212     */
213    void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
214        assert info.packageName.equals("android");
215        mApplicationInfo = info;
216        mClassLoader = classLoader;
217    }
218
219    public String getPackageName() {
220        return mPackageName;
221    }
222
223    public ApplicationInfo getApplicationInfo() {
224        return mApplicationInfo;
225    }
226
227    public int getTargetSdkVersion() {
228        return mApplicationInfo.targetSdkVersion;
229    }
230
231    public boolean isSecurityViolation() {
232        return mSecurityViolation;
233    }
234
235    public CompatibilityInfo getCompatibilityInfo() {
236        return mDisplayAdjustments.getCompatibilityInfo();
237    }
238
239    public void setCompatibilityInfo(CompatibilityInfo compatInfo) {
240        mDisplayAdjustments.setCompatibilityInfo(compatInfo);
241    }
242
243    /**
244     * Gets the array of shared libraries that are listed as
245     * used by the given package.
246     *
247     * @param packageName the name of the package (note: not its
248     * file name)
249     * @return null-ok; the array of shared libraries, each one
250     * a fully-qualified path
251     */
252    private static String[] getLibrariesFor(String packageName) {
253        ApplicationInfo ai = null;
254        try {
255            ai = ActivityThread.getPackageManager().getApplicationInfo(packageName,
256                    PackageManager.GET_SHARED_LIBRARY_FILES, UserHandle.myUserId());
257        } catch (RemoteException e) {
258            throw e.rethrowFromSystemServer();
259        }
260
261        if (ai == null) {
262            return null;
263        }
264
265        return ai.sharedLibraryFiles;
266    }
267
268    /**
269     * Update the ApplicationInfo for an app. If oldPaths is null, all the paths are considered
270     * new.
271     * @param aInfo The new ApplicationInfo to use for this LoadedApk
272     * @param oldPaths The code paths for the old ApplicationInfo object. null means no paths can
273     *                 be reused.
274     */
275    public void updateApplicationInfo(@NonNull ApplicationInfo aInfo,
276            @Nullable List<String> oldPaths) {
277        setApplicationInfo(aInfo);
278
279        final List<String> newPaths = new ArrayList<>();
280        makePaths(mActivityThread, aInfo, newPaths);
281        final List<String> addedPaths = new ArrayList<>(newPaths.size());
282
283        if (oldPaths != null) {
284            for (String path : newPaths) {
285                final String apkName = path.substring(path.lastIndexOf(File.separator));
286                boolean match = false;
287                for (String oldPath : oldPaths) {
288                    final String oldApkName = oldPath.substring(oldPath.lastIndexOf(File.separator));
289                    if (apkName.equals(oldApkName)) {
290                        match = true;
291                        break;
292                    }
293                }
294                if (!match) {
295                    addedPaths.add(path);
296                }
297            }
298        } else {
299            addedPaths.addAll(newPaths);
300        }
301        synchronized (this) {
302            createOrUpdateClassLoaderLocked(addedPaths);
303            if (mResources != null) {
304                final String[] splitPaths;
305                try {
306                    splitPaths = getSplitPaths(null);
307                } catch (NameNotFoundException e) {
308                    // This should NEVER fail.
309                    throw new AssertionError("null split not found");
310                }
311
312                mResources = ResourcesManager.getInstance().getResources(null, mResDir,
313                        splitPaths, mOverlayDirs, mApplicationInfo.sharedLibraryFiles,
314                        Display.DEFAULT_DISPLAY, null, getCompatibilityInfo(),
315                        getClassLoader());
316            }
317        }
318    }
319
320    private void setApplicationInfo(ApplicationInfo aInfo) {
321        final int myUid = Process.myUid();
322        aInfo = adjustNativeLibraryPaths(aInfo);
323        mApplicationInfo = aInfo;
324        mAppDir = aInfo.sourceDir;
325        mResDir = aInfo.uid == myUid ? aInfo.sourceDir : aInfo.publicSourceDir;
326        mOverlayDirs = aInfo.resourceDirs;
327        mSharedLibraries = aInfo.sharedLibraryFiles;
328        mDataDir = aInfo.dataDir;
329        mLibDir = aInfo.nativeLibraryDir;
330        mDataDirFile = FileUtils.newFileOrNull(aInfo.dataDir);
331        mDeviceProtectedDataDirFile = FileUtils.newFileOrNull(aInfo.deviceProtectedDataDir);
332        mCredentialProtectedDataDirFile = FileUtils.newFileOrNull(aInfo.credentialProtectedDataDir);
333
334        mSplitNames = aInfo.splitNames;
335        mSplitAppDirs = aInfo.splitSourceDirs;
336        mSplitResDirs = aInfo.uid == myUid ? aInfo.splitSourceDirs : aInfo.splitPublicSourceDirs;
337
338        if (aInfo.requestsIsolatedSplitLoading() && !ArrayUtils.isEmpty(mSplitNames)) {
339            mSplitLoader = new SplitDependencyLoaderImpl(aInfo.splitDependencies);
340        }
341    }
342
343    public static void makePaths(ActivityThread activityThread,
344                                 ApplicationInfo aInfo,
345                                 List<String> outZipPaths) {
346        makePaths(activityThread, false, aInfo, outZipPaths, null);
347    }
348
349    public static void makePaths(ActivityThread activityThread,
350                                 boolean isBundledApp,
351                                 ApplicationInfo aInfo,
352                                 List<String> outZipPaths,
353                                 List<String> outLibPaths) {
354        final String appDir = aInfo.sourceDir;
355        final String libDir = aInfo.nativeLibraryDir;
356        final String[] sharedLibraries = aInfo.sharedLibraryFiles;
357
358        outZipPaths.clear();
359        outZipPaths.add(appDir);
360
361        // Do not load all available splits if the app requested isolated split loading.
362        if (aInfo.splitSourceDirs != null && !aInfo.requestsIsolatedSplitLoading()) {
363            Collections.addAll(outZipPaths, aInfo.splitSourceDirs);
364        }
365
366        if (outLibPaths != null) {
367            outLibPaths.clear();
368        }
369
370        /*
371         * The following is a bit of a hack to inject
372         * instrumentation into the system: If the app
373         * being started matches one of the instrumentation names,
374         * then we combine both the "instrumentation" and
375         * "instrumented" app into the path, along with the
376         * concatenation of both apps' shared library lists.
377         */
378
379        String[] instrumentationLibs = null;
380        // activityThread will be null when called from the WebView zygote; just assume
381        // no instrumentation applies in this case.
382        if (activityThread != null) {
383            String instrumentationPackageName = activityThread.mInstrumentationPackageName;
384            String instrumentationAppDir = activityThread.mInstrumentationAppDir;
385            String[] instrumentationSplitAppDirs = activityThread.mInstrumentationSplitAppDirs;
386            String instrumentationLibDir = activityThread.mInstrumentationLibDir;
387
388            String instrumentedAppDir = activityThread.mInstrumentedAppDir;
389            String[] instrumentedSplitAppDirs = activityThread.mInstrumentedSplitAppDirs;
390            String instrumentedLibDir = activityThread.mInstrumentedLibDir;
391
392            if (appDir.equals(instrumentationAppDir)
393                    || appDir.equals(instrumentedAppDir)) {
394                outZipPaths.clear();
395                outZipPaths.add(instrumentationAppDir);
396
397                // Only add splits if the app did not request isolated split loading.
398                if (!aInfo.requestsIsolatedSplitLoading()) {
399                    if (instrumentationSplitAppDirs != null) {
400                        Collections.addAll(outZipPaths, instrumentationSplitAppDirs);
401                    }
402
403                    if (!instrumentationAppDir.equals(instrumentedAppDir)) {
404                        outZipPaths.add(instrumentedAppDir);
405                        if (instrumentedSplitAppDirs != null) {
406                            Collections.addAll(outZipPaths, instrumentedSplitAppDirs);
407                        }
408                    }
409                }
410
411                if (outLibPaths != null) {
412                    outLibPaths.add(instrumentationLibDir);
413                    if (!instrumentationLibDir.equals(instrumentedLibDir)) {
414                        outLibPaths.add(instrumentedLibDir);
415                    }
416                }
417
418                if (!instrumentedAppDir.equals(instrumentationAppDir)) {
419                    instrumentationLibs = getLibrariesFor(instrumentationPackageName);
420                }
421            }
422        }
423
424        if (outLibPaths != null) {
425            if (outLibPaths.isEmpty()) {
426                outLibPaths.add(libDir);
427            }
428
429            // Add path to libraries in apk for current abi. Do this now because more entries
430            // will be added to zipPaths that shouldn't be part of the library path.
431            if (aInfo.primaryCpuAbi != null) {
432                // Add fake libs into the library search path if we target prior to N.
433                if (aInfo.targetSdkVersion < Build.VERSION_CODES.N) {
434                    outLibPaths.add("/system/fake-libs" +
435                        (VMRuntime.is64BitAbi(aInfo.primaryCpuAbi) ? "64" : ""));
436                }
437                for (String apk : outZipPaths) {
438                    outLibPaths.add(apk + "!/lib/" + aInfo.primaryCpuAbi);
439                }
440            }
441
442            if (isBundledApp) {
443                // Add path to system libraries to libPaths;
444                // Access to system libs should be limited
445                // to bundled applications; this is why updated
446                // system apps are not included.
447                outLibPaths.add(System.getProperty("java.library.path"));
448            }
449        }
450
451        if (sharedLibraries != null) {
452            for (String lib : sharedLibraries) {
453                if (!outZipPaths.contains(lib)) {
454                    outZipPaths.add(0, lib);
455                }
456            }
457        }
458
459        if (instrumentationLibs != null) {
460            for (String lib : instrumentationLibs) {
461                if (!outZipPaths.contains(lib)) {
462                    outZipPaths.add(0, lib);
463                }
464            }
465        }
466    }
467
468    /*
469     * All indices received by the super class should be shifted by 1 when accessing mSplitNames,
470     * etc. The super class assumes the base APK is index 0, while the PackageManager APIs don't
471     * include the base APK in the list of splits.
472     */
473    private class SplitDependencyLoaderImpl extends SplitDependencyLoader<NameNotFoundException> {
474        private final String[][] mCachedResourcePaths;
475        private final ClassLoader[] mCachedClassLoaders;
476
477        SplitDependencyLoaderImpl(@NonNull SparseArray<int[]> dependencies) {
478            super(dependencies);
479            mCachedResourcePaths = new String[mSplitNames.length + 1][];
480            mCachedClassLoaders = new ClassLoader[mSplitNames.length + 1];
481        }
482
483        @Override
484        protected boolean isSplitCached(int splitIdx) {
485            return mCachedClassLoaders[splitIdx] != null;
486        }
487
488        @Override
489        protected void constructSplit(int splitIdx, @NonNull int[] configSplitIndices,
490                int parentSplitIdx) throws NameNotFoundException {
491            final ArrayList<String> splitPaths = new ArrayList<>();
492            if (splitIdx == 0) {
493                createOrUpdateClassLoaderLocked(null);
494                mCachedClassLoaders[0] = mClassLoader;
495
496                // Never add the base resources here, they always get added no matter what.
497                for (int configSplitIdx : configSplitIndices) {
498                    splitPaths.add(mSplitResDirs[configSplitIdx - 1]);
499                }
500                mCachedResourcePaths[0] = splitPaths.toArray(new String[splitPaths.size()]);
501                return;
502            }
503
504            // Since we handled the special base case above, parentSplitIdx is always valid.
505            final ClassLoader parent = mCachedClassLoaders[parentSplitIdx];
506            mCachedClassLoaders[splitIdx] = ApplicationLoaders.getDefault().getClassLoader(
507                    mSplitAppDirs[splitIdx - 1], getTargetSdkVersion(), false, null, null, parent);
508
509            Collections.addAll(splitPaths, mCachedResourcePaths[parentSplitIdx]);
510            splitPaths.add(mSplitResDirs[splitIdx - 1]);
511            for (int configSplitIdx : configSplitIndices) {
512                splitPaths.add(mSplitResDirs[configSplitIdx - 1]);
513            }
514            mCachedResourcePaths[splitIdx] = splitPaths.toArray(new String[splitPaths.size()]);
515        }
516
517        private int ensureSplitLoaded(String splitName) throws NameNotFoundException {
518            int idx = 0;
519            if (splitName != null) {
520                idx = Arrays.binarySearch(mSplitNames, splitName);
521                if (idx < 0) {
522                    throw new PackageManager.NameNotFoundException(
523                            "Split name '" + splitName + "' is not installed");
524                }
525                idx += 1;
526            }
527            loadDependenciesForSplit(idx);
528            return idx;
529        }
530
531        ClassLoader getClassLoaderForSplit(String splitName) throws NameNotFoundException {
532            return mCachedClassLoaders[ensureSplitLoaded(splitName)];
533        }
534
535        String[] getSplitPathsForSplit(String splitName) throws NameNotFoundException {
536            return mCachedResourcePaths[ensureSplitLoaded(splitName)];
537        }
538    }
539
540    private SplitDependencyLoaderImpl mSplitLoader;
541
542    ClassLoader getSplitClassLoader(String splitName) throws NameNotFoundException {
543        if (mSplitLoader == null) {
544            return mClassLoader;
545        }
546        return mSplitLoader.getClassLoaderForSplit(splitName);
547    }
548
549    String[] getSplitPaths(String splitName) throws NameNotFoundException {
550        if (mSplitLoader == null) {
551            return mSplitResDirs;
552        }
553        return mSplitLoader.getSplitPathsForSplit(splitName);
554    }
555
556    private void createOrUpdateClassLoaderLocked(List<String> addedPaths) {
557        if (mPackageName.equals("android")) {
558            // Note: This branch is taken for system server and we don't need to setup
559            // jit profiling support.
560            if (mClassLoader != null) {
561                // nothing to update
562                return;
563            }
564
565            if (mBaseClassLoader != null) {
566                mClassLoader = mBaseClassLoader;
567            } else {
568                mClassLoader = ClassLoader.getSystemClassLoader();
569            }
570
571            return;
572        }
573
574        // Avoid the binder call when the package is the current application package.
575        // The activity manager will perform ensure that dexopt is performed before
576        // spinning up the process.
577        if (!Objects.equals(mPackageName, ActivityThread.currentPackageName()) && mIncludeCode) {
578            try {
579                ActivityThread.getPackageManager().notifyPackageUse(mPackageName,
580                        PackageManager.NOTIFY_PACKAGE_USE_CROSS_PACKAGE);
581            } catch (RemoteException re) {
582                throw re.rethrowFromSystemServer();
583            }
584        }
585
586        if (mRegisterPackage) {
587            try {
588                ActivityManager.getService().addPackageDependency(mPackageName);
589            } catch (RemoteException e) {
590                throw e.rethrowFromSystemServer();
591            }
592        }
593
594        // Lists for the elements of zip/code and native libraries.
595        //
596        // Both lists are usually not empty. We expect on average one APK for the zip component,
597        // but shared libraries and splits are not uncommon. We expect at least three elements
598        // for native libraries (app-based, system, vendor). As such, give both some breathing
599        // space and initialize to a small value (instead of incurring growth code).
600        final List<String> zipPaths = new ArrayList<>(10);
601        final List<String> libPaths = new ArrayList<>(10);
602
603        final boolean isBundledApp = mApplicationInfo.isSystemApp()
604                && !mApplicationInfo.isUpdatedSystemApp();
605
606        makePaths(mActivityThread, isBundledApp, mApplicationInfo, zipPaths, libPaths);
607
608        String libraryPermittedPath = mDataDir;
609        if (isBundledApp) {
610            // This is necessary to grant bundled apps access to
611            // libraries located in subdirectories of /system/lib
612            libraryPermittedPath += File.pathSeparator +
613                                    System.getProperty("java.library.path");
614        }
615
616        final String librarySearchPath = TextUtils.join(File.pathSeparator, libPaths);
617
618        // If we're not asked to include code, we construct a classloader that has
619        // no code path included. We still need to set up the library search paths
620        // and permitted path because NativeActivity relies on it (it attempts to
621        // call System.loadLibrary() on a classloader from a LoadedApk with
622        // mIncludeCode == false).
623        if (!mIncludeCode) {
624            if (mClassLoader == null) {
625                StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
626                mClassLoader = ApplicationLoaders.getDefault().getClassLoader(
627                    "" /* codePath */, mApplicationInfo.targetSdkVersion, isBundledApp,
628                    librarySearchPath, libraryPermittedPath, mBaseClassLoader);
629                StrictMode.setThreadPolicy(oldPolicy);
630            }
631
632            return;
633        }
634
635        /*
636         * With all the combination done (if necessary, actually create the java class
637         * loader and set up JIT profiling support if necessary.
638         *
639         * In many cases this is a single APK, so try to avoid the StringBuilder in TextUtils.
640         */
641        final String zip = (zipPaths.size() == 1) ? zipPaths.get(0) :
642                TextUtils.join(File.pathSeparator, zipPaths);
643
644        if (DEBUG) Slog.v(ActivityThread.TAG, "Class path: " + zip +
645                    ", JNI path: " + librarySearchPath);
646
647        boolean needToSetupJitProfiles = false;
648        if (mClassLoader == null) {
649            // Temporarily disable logging of disk reads on the Looper thread
650            // as this is early and necessary.
651            StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
652
653            mClassLoader = ApplicationLoaders.getDefault().getClassLoader(zip,
654                    mApplicationInfo.targetSdkVersion, isBundledApp, librarySearchPath,
655                    libraryPermittedPath, mBaseClassLoader);
656
657            StrictMode.setThreadPolicy(oldPolicy);
658            // Setup the class loader paths for profiling.
659            needToSetupJitProfiles = true;
660        }
661
662        if (addedPaths != null && addedPaths.size() > 0) {
663            final String add = TextUtils.join(File.pathSeparator, addedPaths);
664            ApplicationLoaders.getDefault().addPath(mClassLoader, add);
665            // Setup the new code paths for profiling.
666            needToSetupJitProfiles = true;
667        }
668
669        // Setup jit profile support.
670        //
671        // It is ok to call this multiple times if the application gets updated with new splits.
672        // The runtime only keeps track of unique code paths and can handle re-registration of
673        // the same code path. There's no need to pass `addedPaths` since any new code paths
674        // are already in `mApplicationInfo`.
675        //
676        // It is NOT ok to call this function from the system_server (for any of the packages it
677        // loads code from) so we explicitly disallow it there.
678        if (needToSetupJitProfiles && !ActivityThread.isSystem()) {
679            setupJitProfileSupport();
680        }
681    }
682
683    public ClassLoader getClassLoader() {
684        synchronized (this) {
685            if (mClassLoader == null) {
686                createOrUpdateClassLoaderLocked(null /*addedPaths*/);
687            }
688            return mClassLoader;
689        }
690    }
691
692    // Keep in sync with installd (frameworks/native/cmds/installd/commands.cpp).
693    private static File getPrimaryProfileFile(String packageName) {
694        File profileDir = Environment.getDataProfilesDePackageDirectory(
695                UserHandle.myUserId(), packageName);
696        return new File(profileDir, "primary.prof");
697    }
698
699    private void setupJitProfileSupport() {
700        if (!SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
701            return;
702        }
703        // Only set up profile support if the loaded apk has the same uid as the
704        // current process.
705        // Currently, we do not support profiling across different apps.
706        // (e.g. application's uid might be different when the code is
707        // loaded by another app via createApplicationContext)
708        if (mApplicationInfo.uid != Process.myUid()) {
709            return;
710        }
711
712        final List<String> codePaths = new ArrayList<>();
713        if ((mApplicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
714            codePaths.add(mApplicationInfo.sourceDir);
715        }
716        if (mApplicationInfo.splitSourceDirs != null) {
717            Collections.addAll(codePaths, mApplicationInfo.splitSourceDirs);
718        }
719
720        if (codePaths.isEmpty()) {
721            // If there are no code paths there's no need to setup a profile file and register with
722            // the runtime,
723            return;
724        }
725
726        final File profileFile = getPrimaryProfileFile(mPackageName);
727
728        VMRuntime.registerAppInfo(profileFile.getPath(),
729                codePaths.toArray(new String[codePaths.size()]));
730
731        // Register the app data directory with the reporter. It will
732        // help deciding whether or not a dex file is the primary apk or a
733        // secondary dex.
734        DexLoadReporter.getInstance().registerAppDataDir(mPackageName, mDataDir);
735    }
736
737    /**
738     * Setup value for Thread.getContextClassLoader(). If the
739     * package will not run in in a VM with other packages, we set
740     * the Java context ClassLoader to the
741     * PackageInfo.getClassLoader value. However, if this VM can
742     * contain multiple packages, we intead set the Java context
743     * ClassLoader to a proxy that will warn about the use of Java
744     * context ClassLoaders and then fall through to use the
745     * system ClassLoader.
746     *
747     * <p> Note that this is similar to but not the same as the
748     * android.content.Context.getClassLoader(). While both
749     * context class loaders are typically set to the
750     * PathClassLoader used to load the package archive in the
751     * single application per VM case, a single Android process
752     * may contain several Contexts executing on one thread with
753     * their own logical ClassLoaders while the Java context
754     * ClassLoader is a thread local. This is why in the case when
755     * we have multiple packages per VM we do not set the Java
756     * context ClassLoader to an arbitrary but instead warn the
757     * user to set their own if we detect that they are using a
758     * Java library that expects it to be set.
759     */
760    private void initializeJavaContextClassLoader() {
761        IPackageManager pm = ActivityThread.getPackageManager();
762        android.content.pm.PackageInfo pi;
763        try {
764            pi = pm.getPackageInfo(mPackageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
765                    UserHandle.myUserId());
766        } catch (RemoteException e) {
767            throw e.rethrowFromSystemServer();
768        }
769        if (pi == null) {
770            throw new IllegalStateException("Unable to get package info for "
771                    + mPackageName + "; is package not installed?");
772        }
773        /*
774         * Two possible indications that this package could be
775         * sharing its virtual machine with other packages:
776         *
777         * 1.) the sharedUserId attribute is set in the manifest,
778         *     indicating a request to share a VM with other
779         *     packages with the same sharedUserId.
780         *
781         * 2.) the application element of the manifest has an
782         *     attribute specifying a non-default process name,
783         *     indicating the desire to run in another packages VM.
784         */
785        boolean sharedUserIdSet = (pi.sharedUserId != null);
786        boolean processNameNotDefault =
787            (pi.applicationInfo != null &&
788             !mPackageName.equals(pi.applicationInfo.processName));
789        boolean sharable = (sharedUserIdSet || processNameNotDefault);
790        ClassLoader contextClassLoader =
791            (sharable)
792            ? new WarningContextClassLoader()
793            : mClassLoader;
794        Thread.currentThread().setContextClassLoader(contextClassLoader);
795    }
796
797    private static class WarningContextClassLoader extends ClassLoader {
798
799        private static boolean warned = false;
800
801        private void warn(String methodName) {
802            if (warned) {
803                return;
804            }
805            warned = true;
806            Thread.currentThread().setContextClassLoader(getParent());
807            Slog.w(ActivityThread.TAG, "ClassLoader." + methodName + ": " +
808                  "The class loader returned by " +
809                  "Thread.getContextClassLoader() may fail for processes " +
810                  "that host multiple applications. You should explicitly " +
811                  "specify a context class loader. For example: " +
812                  "Thread.setContextClassLoader(getClass().getClassLoader());");
813        }
814
815        @Override public URL getResource(String resName) {
816            warn("getResource");
817            return getParent().getResource(resName);
818        }
819
820        @Override public Enumeration<URL> getResources(String resName) throws IOException {
821            warn("getResources");
822            return getParent().getResources(resName);
823        }
824
825        @Override public InputStream getResourceAsStream(String resName) {
826            warn("getResourceAsStream");
827            return getParent().getResourceAsStream(resName);
828        }
829
830        @Override public Class<?> loadClass(String className) throws ClassNotFoundException {
831            warn("loadClass");
832            return getParent().loadClass(className);
833        }
834
835        @Override public void setClassAssertionStatus(String cname, boolean enable) {
836            warn("setClassAssertionStatus");
837            getParent().setClassAssertionStatus(cname, enable);
838        }
839
840        @Override public void setPackageAssertionStatus(String pname, boolean enable) {
841            warn("setPackageAssertionStatus");
842            getParent().setPackageAssertionStatus(pname, enable);
843        }
844
845        @Override public void setDefaultAssertionStatus(boolean enable) {
846            warn("setDefaultAssertionStatus");
847            getParent().setDefaultAssertionStatus(enable);
848        }
849
850        @Override public void clearAssertionStatus() {
851            warn("clearAssertionStatus");
852            getParent().clearAssertionStatus();
853        }
854    }
855
856    public String getAppDir() {
857        return mAppDir;
858    }
859
860    public String getLibDir() {
861        return mLibDir;
862    }
863
864    public String getResDir() {
865        return mResDir;
866    }
867
868    public String[] getSplitAppDirs() {
869        return mSplitAppDirs;
870    }
871
872    public String[] getSplitResDirs() {
873        return mSplitResDirs;
874    }
875
876    public String[] getOverlayDirs() {
877        return mOverlayDirs;
878    }
879
880    public String getDataDir() {
881        return mDataDir;
882    }
883
884    public File getDataDirFile() {
885        return mDataDirFile;
886    }
887
888    public File getDeviceProtectedDataDirFile() {
889        return mDeviceProtectedDataDirFile;
890    }
891
892    public File getCredentialProtectedDataDirFile() {
893        return mCredentialProtectedDataDirFile;
894    }
895
896    public AssetManager getAssets() {
897        return getResources().getAssets();
898    }
899
900    public Resources getResources() {
901        if (mResources == null) {
902            final String[] splitPaths;
903            try {
904                splitPaths = getSplitPaths(null);
905            } catch (NameNotFoundException e) {
906                // This should never fail.
907                throw new AssertionError("null split not found");
908            }
909
910            mResources = ResourcesManager.getInstance().getResources(null, mResDir,
911                    splitPaths, mOverlayDirs, mApplicationInfo.sharedLibraryFiles,
912                    Display.DEFAULT_DISPLAY, null, getCompatibilityInfo(),
913                    getClassLoader());
914        }
915        return mResources;
916    }
917
918    public Application makeApplication(boolean forceDefaultAppClass,
919            Instrumentation instrumentation) {
920        if (mApplication != null) {
921            return mApplication;
922        }
923
924        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");
925
926        Application app = null;
927
928        String appClass = mApplicationInfo.className;
929        if (forceDefaultAppClass || (appClass == null)) {
930            appClass = "android.app.Application";
931        }
932
933        try {
934            java.lang.ClassLoader cl = getClassLoader();
935            if (!mPackageName.equals("android")) {
936                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
937                        "initializeJavaContextClassLoader");
938                initializeJavaContextClassLoader();
939                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
940            }
941            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
942            app = mActivityThread.mInstrumentation.newApplication(
943                    cl, appClass, appContext);
944            appContext.setOuterContext(app);
945        } catch (Exception e) {
946            if (!mActivityThread.mInstrumentation.onException(app, e)) {
947                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
948                throw new RuntimeException(
949                    "Unable to instantiate application " + appClass
950                    + ": " + e.toString(), e);
951            }
952        }
953        mActivityThread.mAllApplications.add(app);
954        mApplication = app;
955
956        if (instrumentation != null) {
957            try {
958                instrumentation.callApplicationOnCreate(app);
959            } catch (Exception e) {
960                if (!instrumentation.onException(app, e)) {
961                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
962                    throw new RuntimeException(
963                        "Unable to create application " + app.getClass().getName()
964                        + ": " + e.toString(), e);
965                }
966            }
967        }
968
969        // Rewrite the R 'constants' for all library apks.
970        SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifiers();
971        final int N = packageIdentifiers.size();
972        for (int i = 0; i < N; i++) {
973            final int id = packageIdentifiers.keyAt(i);
974            if (id == 0x01 || id == 0x7f) {
975                continue;
976            }
977
978            rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
979        }
980
981        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
982
983        return app;
984    }
985
986    private void rewriteRValues(ClassLoader cl, String packageName, int id) {
987        final Class<?> rClazz;
988        try {
989            rClazz = cl.loadClass(packageName + ".R");
990        } catch (ClassNotFoundException e) {
991            // This is not necessarily an error, as some packages do not ship with resources
992            // (or they do not need rewriting).
993            Log.i(TAG, "No resource references to update in package " + packageName);
994            return;
995        }
996
997        final Method callback;
998        try {
999            callback = rClazz.getMethod("onResourcesLoaded", int.class);
1000        } catch (NoSuchMethodException e) {
1001            // No rewriting to be done.
1002            return;
1003        }
1004
1005        Throwable cause;
1006        try {
1007            callback.invoke(null, id);
1008            return;
1009        } catch (IllegalAccessException e) {
1010            cause = e;
1011        } catch (InvocationTargetException e) {
1012            cause = e.getCause();
1013        }
1014
1015        throw new RuntimeException("Failed to rewrite resource references for " + packageName,
1016                cause);
1017    }
1018
1019    public void removeContextRegistrations(Context context,
1020            String who, String what) {
1021        final boolean reportRegistrationLeaks = StrictMode.vmRegistrationLeaksEnabled();
1022        synchronized (mReceivers) {
1023            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> rmap =
1024                    mReceivers.remove(context);
1025            if (rmap != null) {
1026                for (int i = 0; i < rmap.size(); i++) {
1027                    LoadedApk.ReceiverDispatcher rd = rmap.valueAt(i);
1028                    IntentReceiverLeaked leak = new IntentReceiverLeaked(
1029                            what + " " + who + " has leaked IntentReceiver "
1030                            + rd.getIntentReceiver() + " that was " +
1031                            "originally registered here. Are you missing a " +
1032                            "call to unregisterReceiver()?");
1033                    leak.setStackTrace(rd.getLocation().getStackTrace());
1034                    Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
1035                    if (reportRegistrationLeaks) {
1036                        StrictMode.onIntentReceiverLeaked(leak);
1037                    }
1038                    try {
1039                        ActivityManager.getService().unregisterReceiver(
1040                                rd.getIIntentReceiver());
1041                    } catch (RemoteException e) {
1042                        throw e.rethrowFromSystemServer();
1043                    }
1044                }
1045            }
1046            mUnregisteredReceivers.remove(context);
1047        }
1048
1049        synchronized (mServices) {
1050            //Slog.i(TAG, "Receiver registrations: " + mReceivers);
1051            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> smap =
1052                    mServices.remove(context);
1053            if (smap != null) {
1054                for (int i = 0; i < smap.size(); i++) {
1055                    LoadedApk.ServiceDispatcher sd = smap.valueAt(i);
1056                    ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
1057                            what + " " + who + " has leaked ServiceConnection "
1058                            + sd.getServiceConnection() + " that was originally bound here");
1059                    leak.setStackTrace(sd.getLocation().getStackTrace());
1060                    Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
1061                    if (reportRegistrationLeaks) {
1062                        StrictMode.onServiceConnectionLeaked(leak);
1063                    }
1064                    try {
1065                        ActivityManager.getService().unbindService(
1066                                sd.getIServiceConnection());
1067                    } catch (RemoteException e) {
1068                        throw e.rethrowFromSystemServer();
1069                    }
1070                    sd.doForget();
1071                }
1072            }
1073            mUnboundServices.remove(context);
1074            //Slog.i(TAG, "Service registrations: " + mServices);
1075        }
1076    }
1077
1078    public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
1079            Context context, Handler handler,
1080            Instrumentation instrumentation, boolean registered) {
1081        synchronized (mReceivers) {
1082            LoadedApk.ReceiverDispatcher rd = null;
1083            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = null;
1084            if (registered) {
1085                map = mReceivers.get(context);
1086                if (map != null) {
1087                    rd = map.get(r);
1088                }
1089            }
1090            if (rd == null) {
1091                rd = new ReceiverDispatcher(r, context, handler,
1092                        instrumentation, registered);
1093                if (registered) {
1094                    if (map == null) {
1095                        map = new ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();
1096                        mReceivers.put(context, map);
1097                    }
1098                    map.put(r, rd);
1099                }
1100            } else {
1101                rd.validate(context, handler);
1102            }
1103            rd.mForgotten = false;
1104            return rd.getIIntentReceiver();
1105        }
1106    }
1107
1108    public IIntentReceiver forgetReceiverDispatcher(Context context,
1109            BroadcastReceiver r) {
1110        synchronized (mReceivers) {
1111            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = mReceivers.get(context);
1112            LoadedApk.ReceiverDispatcher rd = null;
1113            if (map != null) {
1114                rd = map.get(r);
1115                if (rd != null) {
1116                    map.remove(r);
1117                    if (map.size() == 0) {
1118                        mReceivers.remove(context);
1119                    }
1120                    if (r.getDebugUnregister()) {
1121                        ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> holder
1122                                = mUnregisteredReceivers.get(context);
1123                        if (holder == null) {
1124                            holder = new ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();
1125                            mUnregisteredReceivers.put(context, holder);
1126                        }
1127                        RuntimeException ex = new IllegalArgumentException(
1128                                "Originally unregistered here:");
1129                        ex.fillInStackTrace();
1130                        rd.setUnregisterLocation(ex);
1131                        holder.put(r, rd);
1132                    }
1133                    rd.mForgotten = true;
1134                    return rd.getIIntentReceiver();
1135                }
1136            }
1137            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> holder
1138                    = mUnregisteredReceivers.get(context);
1139            if (holder != null) {
1140                rd = holder.get(r);
1141                if (rd != null) {
1142                    RuntimeException ex = rd.getUnregisterLocation();
1143                    throw new IllegalArgumentException(
1144                            "Unregistering Receiver " + r
1145                            + " that was already unregistered", ex);
1146                }
1147            }
1148            if (context == null) {
1149                throw new IllegalStateException("Unbinding Receiver " + r
1150                        + " from Context that is no longer in use: " + context);
1151            } else {
1152                throw new IllegalArgumentException("Receiver not registered: " + r);
1153            }
1154
1155        }
1156    }
1157
1158    static final class ReceiverDispatcher {
1159
1160        final static class InnerReceiver extends IIntentReceiver.Stub {
1161            final WeakReference<LoadedApk.ReceiverDispatcher> mDispatcher;
1162            final LoadedApk.ReceiverDispatcher mStrongRef;
1163
1164            InnerReceiver(LoadedApk.ReceiverDispatcher rd, boolean strong) {
1165                mDispatcher = new WeakReference<LoadedApk.ReceiverDispatcher>(rd);
1166                mStrongRef = strong ? rd : null;
1167            }
1168
1169            @Override
1170            public void performReceive(Intent intent, int resultCode, String data,
1171                    Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1172                final LoadedApk.ReceiverDispatcher rd;
1173                if (intent == null) {
1174                    Log.wtf(TAG, "Null intent received");
1175                    rd = null;
1176                } else {
1177                    rd = mDispatcher.get();
1178                }
1179                if (ActivityThread.DEBUG_BROADCAST) {
1180                    int seq = intent.getIntExtra("seq", -1);
1181                    Slog.i(ActivityThread.TAG, "Receiving broadcast " + intent.getAction()
1182                            + " seq=" + seq + " to " + (rd != null ? rd.mReceiver : null));
1183                }
1184                if (rd != null) {
1185                    rd.performReceive(intent, resultCode, data, extras,
1186                            ordered, sticky, sendingUser);
1187                } else {
1188                    // The activity manager dispatched a broadcast to a registered
1189                    // receiver in this process, but before it could be delivered the
1190                    // receiver was unregistered.  Acknowledge the broadcast on its
1191                    // behalf so that the system's broadcast sequence can continue.
1192                    if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1193                            "Finishing broadcast to unregistered receiver");
1194                    IActivityManager mgr = ActivityManager.getService();
1195                    try {
1196                        if (extras != null) {
1197                            extras.setAllowFds(false);
1198                        }
1199                        mgr.finishReceiver(this, resultCode, data, extras, false, intent.getFlags());
1200                    } catch (RemoteException e) {
1201                        throw e.rethrowFromSystemServer();
1202                    }
1203                }
1204            }
1205        }
1206
1207        final IIntentReceiver.Stub mIIntentReceiver;
1208        final BroadcastReceiver mReceiver;
1209        final Context mContext;
1210        final Handler mActivityThread;
1211        final Instrumentation mInstrumentation;
1212        final boolean mRegistered;
1213        final IntentReceiverLeaked mLocation;
1214        RuntimeException mUnregisterLocation;
1215        boolean mForgotten;
1216
1217        final class Args extends BroadcastReceiver.PendingResult implements Runnable {
1218            private Intent mCurIntent;
1219            private final boolean mOrdered;
1220            private boolean mDispatched;
1221
1222            public Args(Intent intent, int resultCode, String resultData, Bundle resultExtras,
1223                    boolean ordered, boolean sticky, int sendingUser) {
1224                super(resultCode, resultData, resultExtras,
1225                        mRegistered ? TYPE_REGISTERED : TYPE_UNREGISTERED, ordered,
1226                        sticky, mIIntentReceiver.asBinder(), sendingUser, intent.getFlags());
1227                mCurIntent = intent;
1228                mOrdered = ordered;
1229            }
1230
1231            public void run() {
1232                final BroadcastReceiver receiver = mReceiver;
1233                final boolean ordered = mOrdered;
1234
1235                if (ActivityThread.DEBUG_BROADCAST) {
1236                    int seq = mCurIntent.getIntExtra("seq", -1);
1237                    Slog.i(ActivityThread.TAG, "Dispatching broadcast " + mCurIntent.getAction()
1238                            + " seq=" + seq + " to " + mReceiver);
1239                    Slog.i(ActivityThread.TAG, "  mRegistered=" + mRegistered
1240                            + " mOrderedHint=" + ordered);
1241                }
1242
1243                final IActivityManager mgr = ActivityManager.getService();
1244                final Intent intent = mCurIntent;
1245                if (intent == null) {
1246                    Log.wtf(TAG, "Null intent being dispatched, mDispatched=" + mDispatched);
1247                }
1248
1249                mCurIntent = null;
1250                mDispatched = true;
1251                if (receiver == null || intent == null || mForgotten) {
1252                    if (mRegistered && ordered) {
1253                        if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1254                                "Finishing null broadcast to " + mReceiver);
1255                        sendFinished(mgr);
1256                    }
1257                    return;
1258                }
1259
1260                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveReg");
1261                try {
1262                    ClassLoader cl =  mReceiver.getClass().getClassLoader();
1263                    intent.setExtrasClassLoader(cl);
1264                    intent.prepareToEnterProcess();
1265                    setExtrasClassLoader(cl);
1266                    receiver.setPendingResult(this);
1267                    receiver.onReceive(mContext, intent);
1268                } catch (Exception e) {
1269                    if (mRegistered && ordered) {
1270                        if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1271                                "Finishing failed broadcast to " + mReceiver);
1272                        sendFinished(mgr);
1273                    }
1274                    if (mInstrumentation == null ||
1275                            !mInstrumentation.onException(mReceiver, e)) {
1276                        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1277                        throw new RuntimeException(
1278                            "Error receiving broadcast " + intent
1279                            + " in " + mReceiver, e);
1280                    }
1281                }
1282
1283                if (receiver.getPendingResult() != null) {
1284                    finish();
1285                }
1286                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1287            }
1288        }
1289
1290        ReceiverDispatcher(BroadcastReceiver receiver, Context context,
1291                Handler activityThread, Instrumentation instrumentation,
1292                boolean registered) {
1293            if (activityThread == null) {
1294                throw new NullPointerException("Handler must not be null");
1295            }
1296
1297            mIIntentReceiver = new InnerReceiver(this, !registered);
1298            mReceiver = receiver;
1299            mContext = context;
1300            mActivityThread = activityThread;
1301            mInstrumentation = instrumentation;
1302            mRegistered = registered;
1303            mLocation = new IntentReceiverLeaked(null);
1304            mLocation.fillInStackTrace();
1305        }
1306
1307        void validate(Context context, Handler activityThread) {
1308            if (mContext != context) {
1309                throw new IllegalStateException(
1310                    "Receiver " + mReceiver +
1311                    " registered with differing Context (was " +
1312                    mContext + " now " + context + ")");
1313            }
1314            if (mActivityThread != activityThread) {
1315                throw new IllegalStateException(
1316                    "Receiver " + mReceiver +
1317                    " registered with differing handler (was " +
1318                    mActivityThread + " now " + activityThread + ")");
1319            }
1320        }
1321
1322        IntentReceiverLeaked getLocation() {
1323            return mLocation;
1324        }
1325
1326        BroadcastReceiver getIntentReceiver() {
1327            return mReceiver;
1328        }
1329
1330        IIntentReceiver getIIntentReceiver() {
1331            return mIIntentReceiver;
1332        }
1333
1334        void setUnregisterLocation(RuntimeException ex) {
1335            mUnregisterLocation = ex;
1336        }
1337
1338        RuntimeException getUnregisterLocation() {
1339            return mUnregisterLocation;
1340        }
1341
1342        public void performReceive(Intent intent, int resultCode, String data,
1343                Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1344            final Args args = new Args(intent, resultCode, data, extras, ordered,
1345                    sticky, sendingUser);
1346            if (intent == null) {
1347                Log.wtf(TAG, "Null intent received");
1348            } else {
1349                if (ActivityThread.DEBUG_BROADCAST) {
1350                    int seq = intent.getIntExtra("seq", -1);
1351                    Slog.i(ActivityThread.TAG, "Enqueueing broadcast " + intent.getAction()
1352                            + " seq=" + seq + " to " + mReceiver);
1353                }
1354            }
1355            if (intent == null || !mActivityThread.post(args)) {
1356                if (mRegistered && ordered) {
1357                    IActivityManager mgr = ActivityManager.getService();
1358                    if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1359                            "Finishing sync broadcast to " + mReceiver);
1360                    args.sendFinished(mgr);
1361                }
1362            }
1363        }
1364
1365    }
1366
1367    public final IServiceConnection getServiceDispatcher(ServiceConnection c,
1368            Context context, Handler handler, int flags) {
1369        synchronized (mServices) {
1370            LoadedApk.ServiceDispatcher sd = null;
1371            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
1372            if (map != null) {
1373                if (DEBUG) Slog.d(TAG, "Returning existing dispatcher " + sd + " for conn " + c);
1374                sd = map.get(c);
1375            }
1376            if (sd == null) {
1377                sd = new ServiceDispatcher(c, context, handler, flags);
1378                if (DEBUG) Slog.d(TAG, "Creating new dispatcher " + sd + " for conn " + c);
1379                if (map == null) {
1380                    map = new ArrayMap<>();
1381                    mServices.put(context, map);
1382                }
1383                map.put(c, sd);
1384            } else {
1385                sd.validate(context, handler);
1386            }
1387            return sd.getIServiceConnection();
1388        }
1389    }
1390
1391    public final IServiceConnection forgetServiceDispatcher(Context context,
1392            ServiceConnection c) {
1393        synchronized (mServices) {
1394            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map
1395                    = mServices.get(context);
1396            LoadedApk.ServiceDispatcher sd = null;
1397            if (map != null) {
1398                sd = map.get(c);
1399                if (sd != null) {
1400                    if (DEBUG) Slog.d(TAG, "Removing dispatcher " + sd + " for conn " + c);
1401                    map.remove(c);
1402                    sd.doForget();
1403                    if (map.size() == 0) {
1404                        mServices.remove(context);
1405                    }
1406                    if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
1407                        ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder
1408                                = mUnboundServices.get(context);
1409                        if (holder == null) {
1410                            holder = new ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>();
1411                            mUnboundServices.put(context, holder);
1412                        }
1413                        RuntimeException ex = new IllegalArgumentException(
1414                                "Originally unbound here:");
1415                        ex.fillInStackTrace();
1416                        sd.setUnbindLocation(ex);
1417                        holder.put(c, sd);
1418                    }
1419                    return sd.getIServiceConnection();
1420                }
1421            }
1422            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder
1423                    = mUnboundServices.get(context);
1424            if (holder != null) {
1425                sd = holder.get(c);
1426                if (sd != null) {
1427                    RuntimeException ex = sd.getUnbindLocation();
1428                    throw new IllegalArgumentException(
1429                            "Unbinding Service " + c
1430                            + " that was already unbound", ex);
1431                }
1432            }
1433            if (context == null) {
1434                throw new IllegalStateException("Unbinding Service " + c
1435                        + " from Context that is no longer in use: " + context);
1436            } else {
1437                throw new IllegalArgumentException("Service not registered: " + c);
1438            }
1439        }
1440    }
1441
1442    static final class ServiceDispatcher {
1443        private final ServiceDispatcher.InnerConnection mIServiceConnection;
1444        private final ServiceConnection mConnection;
1445        private final Context mContext;
1446        private final Handler mActivityThread;
1447        private final ServiceConnectionLeaked mLocation;
1448        private final int mFlags;
1449
1450        private RuntimeException mUnbindLocation;
1451
1452        private boolean mForgotten;
1453
1454        private static class ConnectionInfo {
1455            IBinder binder;
1456            IBinder.DeathRecipient deathMonitor;
1457        }
1458
1459        private static class InnerConnection extends IServiceConnection.Stub {
1460            final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
1461
1462            InnerConnection(LoadedApk.ServiceDispatcher sd) {
1463                mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
1464            }
1465
1466            public void connected(ComponentName name, IBinder service, boolean dead)
1467                    throws RemoteException {
1468                LoadedApk.ServiceDispatcher sd = mDispatcher.get();
1469                if (sd != null) {
1470                    sd.connected(name, service, dead);
1471                }
1472            }
1473        }
1474
1475        private final ArrayMap<ComponentName, ServiceDispatcher.ConnectionInfo> mActiveConnections
1476            = new ArrayMap<ComponentName, ServiceDispatcher.ConnectionInfo>();
1477
1478        ServiceDispatcher(ServiceConnection conn,
1479                Context context, Handler activityThread, int flags) {
1480            mIServiceConnection = new InnerConnection(this);
1481            mConnection = conn;
1482            mContext = context;
1483            mActivityThread = activityThread;
1484            mLocation = new ServiceConnectionLeaked(null);
1485            mLocation.fillInStackTrace();
1486            mFlags = flags;
1487        }
1488
1489        void validate(Context context, Handler activityThread) {
1490            if (mContext != context) {
1491                throw new RuntimeException(
1492                    "ServiceConnection " + mConnection +
1493                    " registered with differing Context (was " +
1494                    mContext + " now " + context + ")");
1495            }
1496            if (mActivityThread != activityThread) {
1497                throw new RuntimeException(
1498                    "ServiceConnection " + mConnection +
1499                    " registered with differing handler (was " +
1500                    mActivityThread + " now " + activityThread + ")");
1501            }
1502        }
1503
1504        void doForget() {
1505            synchronized(this) {
1506                for (int i=0; i<mActiveConnections.size(); i++) {
1507                    ServiceDispatcher.ConnectionInfo ci = mActiveConnections.valueAt(i);
1508                    ci.binder.unlinkToDeath(ci.deathMonitor, 0);
1509                }
1510                mActiveConnections.clear();
1511                mForgotten = true;
1512            }
1513        }
1514
1515        ServiceConnectionLeaked getLocation() {
1516            return mLocation;
1517        }
1518
1519        ServiceConnection getServiceConnection() {
1520            return mConnection;
1521        }
1522
1523        IServiceConnection getIServiceConnection() {
1524            return mIServiceConnection;
1525        }
1526
1527        int getFlags() {
1528            return mFlags;
1529        }
1530
1531        void setUnbindLocation(RuntimeException ex) {
1532            mUnbindLocation = ex;
1533        }
1534
1535        RuntimeException getUnbindLocation() {
1536            return mUnbindLocation;
1537        }
1538
1539        public void connected(ComponentName name, IBinder service, boolean dead) {
1540            if (mActivityThread != null) {
1541                mActivityThread.post(new RunConnection(name, service, 0, dead));
1542            } else {
1543                doConnected(name, service, dead);
1544            }
1545        }
1546
1547        public void death(ComponentName name, IBinder service) {
1548            if (mActivityThread != null) {
1549                mActivityThread.post(new RunConnection(name, service, 1, false));
1550            } else {
1551                doDeath(name, service);
1552            }
1553        }
1554
1555        public void doConnected(ComponentName name, IBinder service, boolean dead) {
1556            ServiceDispatcher.ConnectionInfo old;
1557            ServiceDispatcher.ConnectionInfo info;
1558
1559            synchronized (this) {
1560                if (mForgotten) {
1561                    // We unbound before receiving the connection; ignore
1562                    // any connection received.
1563                    return;
1564                }
1565                old = mActiveConnections.get(name);
1566                if (old != null && old.binder == service) {
1567                    // Huh, already have this one.  Oh well!
1568                    return;
1569                }
1570
1571                if (service != null) {
1572                    // A new service is being connected... set it all up.
1573                    info = new ConnectionInfo();
1574                    info.binder = service;
1575                    info.deathMonitor = new DeathMonitor(name, service);
1576                    try {
1577                        service.linkToDeath(info.deathMonitor, 0);
1578                        mActiveConnections.put(name, info);
1579                    } catch (RemoteException e) {
1580                        // This service was dead before we got it...  just
1581                        // don't do anything with it.
1582                        mActiveConnections.remove(name);
1583                        return;
1584                    }
1585
1586                } else {
1587                    // The named service is being disconnected... clean up.
1588                    mActiveConnections.remove(name);
1589                }
1590
1591                if (old != null) {
1592                    old.binder.unlinkToDeath(old.deathMonitor, 0);
1593                }
1594            }
1595
1596            // If there was an old service, it is now disconnected.
1597            if (old != null) {
1598                mConnection.onServiceDisconnected(name);
1599            }
1600            if (dead) {
1601                mConnection.onBindingDead(name);
1602            }
1603            // If there is a new service, it is now connected.
1604            if (service != null) {
1605                mConnection.onServiceConnected(name, service);
1606            }
1607        }
1608
1609        public void doDeath(ComponentName name, IBinder service) {
1610            synchronized (this) {
1611                ConnectionInfo old = mActiveConnections.get(name);
1612                if (old == null || old.binder != service) {
1613                    // Death for someone different than who we last
1614                    // reported...  just ignore it.
1615                    return;
1616                }
1617                mActiveConnections.remove(name);
1618                old.binder.unlinkToDeath(old.deathMonitor, 0);
1619            }
1620
1621            mConnection.onServiceDisconnected(name);
1622        }
1623
1624        private final class RunConnection implements Runnable {
1625            RunConnection(ComponentName name, IBinder service, int command, boolean dead) {
1626                mName = name;
1627                mService = service;
1628                mCommand = command;
1629                mDead = dead;
1630            }
1631
1632            public void run() {
1633                if (mCommand == 0) {
1634                    doConnected(mName, mService, mDead);
1635                } else if (mCommand == 1) {
1636                    doDeath(mName, mService);
1637                }
1638            }
1639
1640            final ComponentName mName;
1641            final IBinder mService;
1642            final int mCommand;
1643            final boolean mDead;
1644        }
1645
1646        private final class DeathMonitor implements IBinder.DeathRecipient
1647        {
1648            DeathMonitor(ComponentName name, IBinder service) {
1649                mName = name;
1650                mService = service;
1651            }
1652
1653            public void binderDied() {
1654                death(mName, mService);
1655            }
1656
1657            final ComponentName mName;
1658            final IBinder mService;
1659        }
1660    }
1661}
1662