LoadedApk.java revision d7a168e11a896ef5915d7c0e7aa3eb8c1b5a1b7d
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        // Prepend the shared libraries, maintaining their original order where possible.
452        if (sharedLibraries != null) {
453            int index = 0;
454            for (String lib : sharedLibraries) {
455                if (!outZipPaths.contains(lib)) {
456                    outZipPaths.add(index, lib);
457                    index++;
458                }
459            }
460        }
461
462        if (instrumentationLibs != null) {
463            for (String lib : instrumentationLibs) {
464                if (!outZipPaths.contains(lib)) {
465                    outZipPaths.add(0, lib);
466                }
467            }
468        }
469    }
470
471    /*
472     * All indices received by the super class should be shifted by 1 when accessing mSplitNames,
473     * etc. The super class assumes the base APK is index 0, while the PackageManager APIs don't
474     * include the base APK in the list of splits.
475     */
476    private class SplitDependencyLoaderImpl extends SplitDependencyLoader<NameNotFoundException> {
477        private final String[][] mCachedResourcePaths;
478        private final ClassLoader[] mCachedClassLoaders;
479
480        SplitDependencyLoaderImpl(@NonNull SparseArray<int[]> dependencies) {
481            super(dependencies);
482            mCachedResourcePaths = new String[mSplitNames.length + 1][];
483            mCachedClassLoaders = new ClassLoader[mSplitNames.length + 1];
484        }
485
486        @Override
487        protected boolean isSplitCached(int splitIdx) {
488            return mCachedClassLoaders[splitIdx] != null;
489        }
490
491        @Override
492        protected void constructSplit(int splitIdx, @NonNull int[] configSplitIndices,
493                int parentSplitIdx) throws NameNotFoundException {
494            final ArrayList<String> splitPaths = new ArrayList<>();
495            if (splitIdx == 0) {
496                createOrUpdateClassLoaderLocked(null);
497                mCachedClassLoaders[0] = mClassLoader;
498
499                // Never add the base resources here, they always get added no matter what.
500                for (int configSplitIdx : configSplitIndices) {
501                    splitPaths.add(mSplitResDirs[configSplitIdx - 1]);
502                }
503                mCachedResourcePaths[0] = splitPaths.toArray(new String[splitPaths.size()]);
504                return;
505            }
506
507            // Since we handled the special base case above, parentSplitIdx is always valid.
508            final ClassLoader parent = mCachedClassLoaders[parentSplitIdx];
509            mCachedClassLoaders[splitIdx] = ApplicationLoaders.getDefault().getClassLoader(
510                    mSplitAppDirs[splitIdx - 1], getTargetSdkVersion(), false, null, null, parent);
511
512            Collections.addAll(splitPaths, mCachedResourcePaths[parentSplitIdx]);
513            splitPaths.add(mSplitResDirs[splitIdx - 1]);
514            for (int configSplitIdx : configSplitIndices) {
515                splitPaths.add(mSplitResDirs[configSplitIdx - 1]);
516            }
517            mCachedResourcePaths[splitIdx] = splitPaths.toArray(new String[splitPaths.size()]);
518        }
519
520        private int ensureSplitLoaded(String splitName) throws NameNotFoundException {
521            int idx = 0;
522            if (splitName != null) {
523                idx = Arrays.binarySearch(mSplitNames, splitName);
524                if (idx < 0) {
525                    throw new PackageManager.NameNotFoundException(
526                            "Split name '" + splitName + "' is not installed");
527                }
528                idx += 1;
529            }
530            loadDependenciesForSplit(idx);
531            return idx;
532        }
533
534        ClassLoader getClassLoaderForSplit(String splitName) throws NameNotFoundException {
535            return mCachedClassLoaders[ensureSplitLoaded(splitName)];
536        }
537
538        String[] getSplitPathsForSplit(String splitName) throws NameNotFoundException {
539            return mCachedResourcePaths[ensureSplitLoaded(splitName)];
540        }
541    }
542
543    private SplitDependencyLoaderImpl mSplitLoader;
544
545    ClassLoader getSplitClassLoader(String splitName) throws NameNotFoundException {
546        if (mSplitLoader == null) {
547            return mClassLoader;
548        }
549        return mSplitLoader.getClassLoaderForSplit(splitName);
550    }
551
552    String[] getSplitPaths(String splitName) throws NameNotFoundException {
553        if (mSplitLoader == null) {
554            return mSplitResDirs;
555        }
556        return mSplitLoader.getSplitPathsForSplit(splitName);
557    }
558
559    private void createOrUpdateClassLoaderLocked(List<String> addedPaths) {
560        if (mPackageName.equals("android")) {
561            // Note: This branch is taken for system server and we don't need to setup
562            // jit profiling support.
563            if (mClassLoader != null) {
564                // nothing to update
565                return;
566            }
567
568            if (mBaseClassLoader != null) {
569                mClassLoader = mBaseClassLoader;
570            } else {
571                mClassLoader = ClassLoader.getSystemClassLoader();
572            }
573
574            return;
575        }
576
577        // Avoid the binder call when the package is the current application package.
578        // The activity manager will perform ensure that dexopt is performed before
579        // spinning up the process.
580        if (!Objects.equals(mPackageName, ActivityThread.currentPackageName()) && mIncludeCode) {
581            try {
582                ActivityThread.getPackageManager().notifyPackageUse(mPackageName,
583                        PackageManager.NOTIFY_PACKAGE_USE_CROSS_PACKAGE);
584            } catch (RemoteException re) {
585                throw re.rethrowFromSystemServer();
586            }
587        }
588
589        if (mRegisterPackage) {
590            try {
591                ActivityManager.getService().addPackageDependency(mPackageName);
592            } catch (RemoteException e) {
593                throw e.rethrowFromSystemServer();
594            }
595        }
596
597        // Lists for the elements of zip/code and native libraries.
598        //
599        // Both lists are usually not empty. We expect on average one APK for the zip component,
600        // but shared libraries and splits are not uncommon. We expect at least three elements
601        // for native libraries (app-based, system, vendor). As such, give both some breathing
602        // space and initialize to a small value (instead of incurring growth code).
603        final List<String> zipPaths = new ArrayList<>(10);
604        final List<String> libPaths = new ArrayList<>(10);
605
606        final boolean isBundledApp = mApplicationInfo.isSystemApp()
607                && !mApplicationInfo.isUpdatedSystemApp();
608
609        makePaths(mActivityThread, isBundledApp, mApplicationInfo, zipPaths, libPaths);
610
611        String libraryPermittedPath = mDataDir;
612        if (isBundledApp) {
613            // This is necessary to grant bundled apps access to
614            // libraries located in subdirectories of /system/lib
615            libraryPermittedPath += File.pathSeparator +
616                                    System.getProperty("java.library.path");
617        }
618
619        final String librarySearchPath = TextUtils.join(File.pathSeparator, libPaths);
620
621        // If we're not asked to include code, we construct a classloader that has
622        // no code path included. We still need to set up the library search paths
623        // and permitted path because NativeActivity relies on it (it attempts to
624        // call System.loadLibrary() on a classloader from a LoadedApk with
625        // mIncludeCode == false).
626        if (!mIncludeCode) {
627            if (mClassLoader == null) {
628                StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
629                mClassLoader = ApplicationLoaders.getDefault().getClassLoader(
630                    "" /* codePath */, mApplicationInfo.targetSdkVersion, isBundledApp,
631                    librarySearchPath, libraryPermittedPath, mBaseClassLoader);
632                StrictMode.setThreadPolicy(oldPolicy);
633            }
634
635            return;
636        }
637
638        /*
639         * With all the combination done (if necessary, actually create the java class
640         * loader and set up JIT profiling support if necessary.
641         *
642         * In many cases this is a single APK, so try to avoid the StringBuilder in TextUtils.
643         */
644        final String zip = (zipPaths.size() == 1) ? zipPaths.get(0) :
645                TextUtils.join(File.pathSeparator, zipPaths);
646
647        if (DEBUG) Slog.v(ActivityThread.TAG, "Class path: " + zip +
648                    ", JNI path: " + librarySearchPath);
649
650        boolean needToSetupJitProfiles = false;
651        if (mClassLoader == null) {
652            // Temporarily disable logging of disk reads on the Looper thread
653            // as this is early and necessary.
654            StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
655
656            mClassLoader = ApplicationLoaders.getDefault().getClassLoader(zip,
657                    mApplicationInfo.targetSdkVersion, isBundledApp, librarySearchPath,
658                    libraryPermittedPath, mBaseClassLoader);
659
660            StrictMode.setThreadPolicy(oldPolicy);
661            // Setup the class loader paths for profiling.
662            needToSetupJitProfiles = true;
663        }
664
665        if (addedPaths != null && addedPaths.size() > 0) {
666            final String add = TextUtils.join(File.pathSeparator, addedPaths);
667            ApplicationLoaders.getDefault().addPath(mClassLoader, add);
668            // Setup the new code paths for profiling.
669            needToSetupJitProfiles = true;
670        }
671
672        // Setup jit profile support.
673        //
674        // It is ok to call this multiple times if the application gets updated with new splits.
675        // The runtime only keeps track of unique code paths and can handle re-registration of
676        // the same code path. There's no need to pass `addedPaths` since any new code paths
677        // are already in `mApplicationInfo`.
678        //
679        // It is NOT ok to call this function from the system_server (for any of the packages it
680        // loads code from) so we explicitly disallow it there.
681        if (needToSetupJitProfiles && !ActivityThread.isSystem()) {
682            setupJitProfileSupport();
683        }
684    }
685
686    public ClassLoader getClassLoader() {
687        synchronized (this) {
688            if (mClassLoader == null) {
689                createOrUpdateClassLoaderLocked(null /*addedPaths*/);
690            }
691            return mClassLoader;
692        }
693    }
694
695    // Keep in sync with installd (frameworks/native/cmds/installd/commands.cpp).
696    private static File getPrimaryProfileFile(String packageName) {
697        File profileDir = Environment.getDataProfilesDePackageDirectory(
698                UserHandle.myUserId(), packageName);
699        return new File(profileDir, "primary.prof");
700    }
701
702    private void setupJitProfileSupport() {
703        if (!SystemProperties.getBoolean("dalvik.vm.usejitprofiles", false)) {
704            return;
705        }
706        // Only set up profile support if the loaded apk has the same uid as the
707        // current process.
708        // Currently, we do not support profiling across different apps.
709        // (e.g. application's uid might be different when the code is
710        // loaded by another app via createApplicationContext)
711        if (mApplicationInfo.uid != Process.myUid()) {
712            return;
713        }
714
715        final List<String> codePaths = new ArrayList<>();
716        if ((mApplicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
717            codePaths.add(mApplicationInfo.sourceDir);
718        }
719        if (mApplicationInfo.splitSourceDirs != null) {
720            Collections.addAll(codePaths, mApplicationInfo.splitSourceDirs);
721        }
722
723        if (codePaths.isEmpty()) {
724            // If there are no code paths there's no need to setup a profile file and register with
725            // the runtime,
726            return;
727        }
728
729        final File profileFile = getPrimaryProfileFile(mPackageName);
730
731        VMRuntime.registerAppInfo(profileFile.getPath(),
732                codePaths.toArray(new String[codePaths.size()]));
733
734        // Register the app data directory with the reporter. It will
735        // help deciding whether or not a dex file is the primary apk or a
736        // secondary dex.
737        DexLoadReporter.getInstance().registerAppDataDir(mPackageName, mDataDir);
738    }
739
740    /**
741     * Setup value for Thread.getContextClassLoader(). If the
742     * package will not run in in a VM with other packages, we set
743     * the Java context ClassLoader to the
744     * PackageInfo.getClassLoader value. However, if this VM can
745     * contain multiple packages, we intead set the Java context
746     * ClassLoader to a proxy that will warn about the use of Java
747     * context ClassLoaders and then fall through to use the
748     * system ClassLoader.
749     *
750     * <p> Note that this is similar to but not the same as the
751     * android.content.Context.getClassLoader(). While both
752     * context class loaders are typically set to the
753     * PathClassLoader used to load the package archive in the
754     * single application per VM case, a single Android process
755     * may contain several Contexts executing on one thread with
756     * their own logical ClassLoaders while the Java context
757     * ClassLoader is a thread local. This is why in the case when
758     * we have multiple packages per VM we do not set the Java
759     * context ClassLoader to an arbitrary but instead warn the
760     * user to set their own if we detect that they are using a
761     * Java library that expects it to be set.
762     */
763    private void initializeJavaContextClassLoader() {
764        IPackageManager pm = ActivityThread.getPackageManager();
765        android.content.pm.PackageInfo pi;
766        try {
767            pi = pm.getPackageInfo(mPackageName, PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
768                    UserHandle.myUserId());
769        } catch (RemoteException e) {
770            throw e.rethrowFromSystemServer();
771        }
772        if (pi == null) {
773            throw new IllegalStateException("Unable to get package info for "
774                    + mPackageName + "; is package not installed?");
775        }
776        /*
777         * Two possible indications that this package could be
778         * sharing its virtual machine with other packages:
779         *
780         * 1.) the sharedUserId attribute is set in the manifest,
781         *     indicating a request to share a VM with other
782         *     packages with the same sharedUserId.
783         *
784         * 2.) the application element of the manifest has an
785         *     attribute specifying a non-default process name,
786         *     indicating the desire to run in another packages VM.
787         */
788        boolean sharedUserIdSet = (pi.sharedUserId != null);
789        boolean processNameNotDefault =
790            (pi.applicationInfo != null &&
791             !mPackageName.equals(pi.applicationInfo.processName));
792        boolean sharable = (sharedUserIdSet || processNameNotDefault);
793        ClassLoader contextClassLoader =
794            (sharable)
795            ? new WarningContextClassLoader()
796            : mClassLoader;
797        Thread.currentThread().setContextClassLoader(contextClassLoader);
798    }
799
800    private static class WarningContextClassLoader extends ClassLoader {
801
802        private static boolean warned = false;
803
804        private void warn(String methodName) {
805            if (warned) {
806                return;
807            }
808            warned = true;
809            Thread.currentThread().setContextClassLoader(getParent());
810            Slog.w(ActivityThread.TAG, "ClassLoader." + methodName + ": " +
811                  "The class loader returned by " +
812                  "Thread.getContextClassLoader() may fail for processes " +
813                  "that host multiple applications. You should explicitly " +
814                  "specify a context class loader. For example: " +
815                  "Thread.setContextClassLoader(getClass().getClassLoader());");
816        }
817
818        @Override public URL getResource(String resName) {
819            warn("getResource");
820            return getParent().getResource(resName);
821        }
822
823        @Override public Enumeration<URL> getResources(String resName) throws IOException {
824            warn("getResources");
825            return getParent().getResources(resName);
826        }
827
828        @Override public InputStream getResourceAsStream(String resName) {
829            warn("getResourceAsStream");
830            return getParent().getResourceAsStream(resName);
831        }
832
833        @Override public Class<?> loadClass(String className) throws ClassNotFoundException {
834            warn("loadClass");
835            return getParent().loadClass(className);
836        }
837
838        @Override public void setClassAssertionStatus(String cname, boolean enable) {
839            warn("setClassAssertionStatus");
840            getParent().setClassAssertionStatus(cname, enable);
841        }
842
843        @Override public void setPackageAssertionStatus(String pname, boolean enable) {
844            warn("setPackageAssertionStatus");
845            getParent().setPackageAssertionStatus(pname, enable);
846        }
847
848        @Override public void setDefaultAssertionStatus(boolean enable) {
849            warn("setDefaultAssertionStatus");
850            getParent().setDefaultAssertionStatus(enable);
851        }
852
853        @Override public void clearAssertionStatus() {
854            warn("clearAssertionStatus");
855            getParent().clearAssertionStatus();
856        }
857    }
858
859    public String getAppDir() {
860        return mAppDir;
861    }
862
863    public String getLibDir() {
864        return mLibDir;
865    }
866
867    public String getResDir() {
868        return mResDir;
869    }
870
871    public String[] getSplitAppDirs() {
872        return mSplitAppDirs;
873    }
874
875    public String[] getSplitResDirs() {
876        return mSplitResDirs;
877    }
878
879    public String[] getOverlayDirs() {
880        return mOverlayDirs;
881    }
882
883    public String getDataDir() {
884        return mDataDir;
885    }
886
887    public File getDataDirFile() {
888        return mDataDirFile;
889    }
890
891    public File getDeviceProtectedDataDirFile() {
892        return mDeviceProtectedDataDirFile;
893    }
894
895    public File getCredentialProtectedDataDirFile() {
896        return mCredentialProtectedDataDirFile;
897    }
898
899    public AssetManager getAssets() {
900        return getResources().getAssets();
901    }
902
903    public Resources getResources() {
904        if (mResources == null) {
905            final String[] splitPaths;
906            try {
907                splitPaths = getSplitPaths(null);
908            } catch (NameNotFoundException e) {
909                // This should never fail.
910                throw new AssertionError("null split not found");
911            }
912
913            mResources = ResourcesManager.getInstance().getResources(null, mResDir,
914                    splitPaths, mOverlayDirs, mApplicationInfo.sharedLibraryFiles,
915                    Display.DEFAULT_DISPLAY, null, getCompatibilityInfo(),
916                    getClassLoader());
917        }
918        return mResources;
919    }
920
921    public Application makeApplication(boolean forceDefaultAppClass,
922            Instrumentation instrumentation) {
923        if (mApplication != null) {
924            return mApplication;
925        }
926
927        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "makeApplication");
928
929        Application app = null;
930
931        String appClass = mApplicationInfo.className;
932        if (forceDefaultAppClass || (appClass == null)) {
933            appClass = "android.app.Application";
934        }
935
936        try {
937            java.lang.ClassLoader cl = getClassLoader();
938            if (!mPackageName.equals("android")) {
939                Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
940                        "initializeJavaContextClassLoader");
941                initializeJavaContextClassLoader();
942                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
943            }
944            ContextImpl appContext = ContextImpl.createAppContext(mActivityThread, this);
945            app = mActivityThread.mInstrumentation.newApplication(
946                    cl, appClass, appContext);
947            appContext.setOuterContext(app);
948        } catch (Exception e) {
949            if (!mActivityThread.mInstrumentation.onException(app, e)) {
950                Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
951                throw new RuntimeException(
952                    "Unable to instantiate application " + appClass
953                    + ": " + e.toString(), e);
954            }
955        }
956        mActivityThread.mAllApplications.add(app);
957        mApplication = app;
958
959        if (instrumentation != null) {
960            try {
961                instrumentation.callApplicationOnCreate(app);
962            } catch (Exception e) {
963                if (!instrumentation.onException(app, e)) {
964                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
965                    throw new RuntimeException(
966                        "Unable to create application " + app.getClass().getName()
967                        + ": " + e.toString(), e);
968                }
969            }
970        }
971
972        // Rewrite the R 'constants' for all library apks.
973        SparseArray<String> packageIdentifiers = getAssets().getAssignedPackageIdentifiers();
974        final int N = packageIdentifiers.size();
975        for (int i = 0; i < N; i++) {
976            final int id = packageIdentifiers.keyAt(i);
977            if (id == 0x01 || id == 0x7f) {
978                continue;
979            }
980
981            rewriteRValues(getClassLoader(), packageIdentifiers.valueAt(i), id);
982        }
983
984        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
985
986        return app;
987    }
988
989    private void rewriteRValues(ClassLoader cl, String packageName, int id) {
990        final Class<?> rClazz;
991        try {
992            rClazz = cl.loadClass(packageName + ".R");
993        } catch (ClassNotFoundException e) {
994            // This is not necessarily an error, as some packages do not ship with resources
995            // (or they do not need rewriting).
996            Log.i(TAG, "No resource references to update in package " + packageName);
997            return;
998        }
999
1000        final Method callback;
1001        try {
1002            callback = rClazz.getMethod("onResourcesLoaded", int.class);
1003        } catch (NoSuchMethodException e) {
1004            // No rewriting to be done.
1005            return;
1006        }
1007
1008        Throwable cause;
1009        try {
1010            callback.invoke(null, id);
1011            return;
1012        } catch (IllegalAccessException e) {
1013            cause = e;
1014        } catch (InvocationTargetException e) {
1015            cause = e.getCause();
1016        }
1017
1018        throw new RuntimeException("Failed to rewrite resource references for " + packageName,
1019                cause);
1020    }
1021
1022    public void removeContextRegistrations(Context context,
1023            String who, String what) {
1024        final boolean reportRegistrationLeaks = StrictMode.vmRegistrationLeaksEnabled();
1025        synchronized (mReceivers) {
1026            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> rmap =
1027                    mReceivers.remove(context);
1028            if (rmap != null) {
1029                for (int i = 0; i < rmap.size(); i++) {
1030                    LoadedApk.ReceiverDispatcher rd = rmap.valueAt(i);
1031                    IntentReceiverLeaked leak = new IntentReceiverLeaked(
1032                            what + " " + who + " has leaked IntentReceiver "
1033                            + rd.getIntentReceiver() + " that was " +
1034                            "originally registered here. Are you missing a " +
1035                            "call to unregisterReceiver()?");
1036                    leak.setStackTrace(rd.getLocation().getStackTrace());
1037                    Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
1038                    if (reportRegistrationLeaks) {
1039                        StrictMode.onIntentReceiverLeaked(leak);
1040                    }
1041                    try {
1042                        ActivityManager.getService().unregisterReceiver(
1043                                rd.getIIntentReceiver());
1044                    } catch (RemoteException e) {
1045                        throw e.rethrowFromSystemServer();
1046                    }
1047                }
1048            }
1049            mUnregisteredReceivers.remove(context);
1050        }
1051
1052        synchronized (mServices) {
1053            //Slog.i(TAG, "Receiver registrations: " + mReceivers);
1054            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> smap =
1055                    mServices.remove(context);
1056            if (smap != null) {
1057                for (int i = 0; i < smap.size(); i++) {
1058                    LoadedApk.ServiceDispatcher sd = smap.valueAt(i);
1059                    ServiceConnectionLeaked leak = new ServiceConnectionLeaked(
1060                            what + " " + who + " has leaked ServiceConnection "
1061                            + sd.getServiceConnection() + " that was originally bound here");
1062                    leak.setStackTrace(sd.getLocation().getStackTrace());
1063                    Slog.e(ActivityThread.TAG, leak.getMessage(), leak);
1064                    if (reportRegistrationLeaks) {
1065                        StrictMode.onServiceConnectionLeaked(leak);
1066                    }
1067                    try {
1068                        ActivityManager.getService().unbindService(
1069                                sd.getIServiceConnection());
1070                    } catch (RemoteException e) {
1071                        throw e.rethrowFromSystemServer();
1072                    }
1073                    sd.doForget();
1074                }
1075            }
1076            mUnboundServices.remove(context);
1077            //Slog.i(TAG, "Service registrations: " + mServices);
1078        }
1079    }
1080
1081    public IIntentReceiver getReceiverDispatcher(BroadcastReceiver r,
1082            Context context, Handler handler,
1083            Instrumentation instrumentation, boolean registered) {
1084        synchronized (mReceivers) {
1085            LoadedApk.ReceiverDispatcher rd = null;
1086            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = null;
1087            if (registered) {
1088                map = mReceivers.get(context);
1089                if (map != null) {
1090                    rd = map.get(r);
1091                }
1092            }
1093            if (rd == null) {
1094                rd = new ReceiverDispatcher(r, context, handler,
1095                        instrumentation, registered);
1096                if (registered) {
1097                    if (map == null) {
1098                        map = new ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();
1099                        mReceivers.put(context, map);
1100                    }
1101                    map.put(r, rd);
1102                }
1103            } else {
1104                rd.validate(context, handler);
1105            }
1106            rd.mForgotten = false;
1107            return rd.getIIntentReceiver();
1108        }
1109    }
1110
1111    public IIntentReceiver forgetReceiverDispatcher(Context context,
1112            BroadcastReceiver r) {
1113        synchronized (mReceivers) {
1114            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> map = mReceivers.get(context);
1115            LoadedApk.ReceiverDispatcher rd = null;
1116            if (map != null) {
1117                rd = map.get(r);
1118                if (rd != null) {
1119                    map.remove(r);
1120                    if (map.size() == 0) {
1121                        mReceivers.remove(context);
1122                    }
1123                    if (r.getDebugUnregister()) {
1124                        ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> holder
1125                                = mUnregisteredReceivers.get(context);
1126                        if (holder == null) {
1127                            holder = new ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher>();
1128                            mUnregisteredReceivers.put(context, holder);
1129                        }
1130                        RuntimeException ex = new IllegalArgumentException(
1131                                "Originally unregistered here:");
1132                        ex.fillInStackTrace();
1133                        rd.setUnregisterLocation(ex);
1134                        holder.put(r, rd);
1135                    }
1136                    rd.mForgotten = true;
1137                    return rd.getIIntentReceiver();
1138                }
1139            }
1140            ArrayMap<BroadcastReceiver, LoadedApk.ReceiverDispatcher> holder
1141                    = mUnregisteredReceivers.get(context);
1142            if (holder != null) {
1143                rd = holder.get(r);
1144                if (rd != null) {
1145                    RuntimeException ex = rd.getUnregisterLocation();
1146                    throw new IllegalArgumentException(
1147                            "Unregistering Receiver " + r
1148                            + " that was already unregistered", ex);
1149                }
1150            }
1151            if (context == null) {
1152                throw new IllegalStateException("Unbinding Receiver " + r
1153                        + " from Context that is no longer in use: " + context);
1154            } else {
1155                throw new IllegalArgumentException("Receiver not registered: " + r);
1156            }
1157
1158        }
1159    }
1160
1161    static final class ReceiverDispatcher {
1162
1163        final static class InnerReceiver extends IIntentReceiver.Stub {
1164            final WeakReference<LoadedApk.ReceiverDispatcher> mDispatcher;
1165            final LoadedApk.ReceiverDispatcher mStrongRef;
1166
1167            InnerReceiver(LoadedApk.ReceiverDispatcher rd, boolean strong) {
1168                mDispatcher = new WeakReference<LoadedApk.ReceiverDispatcher>(rd);
1169                mStrongRef = strong ? rd : null;
1170            }
1171
1172            @Override
1173            public void performReceive(Intent intent, int resultCode, String data,
1174                    Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1175                final LoadedApk.ReceiverDispatcher rd;
1176                if (intent == null) {
1177                    Log.wtf(TAG, "Null intent received");
1178                    rd = null;
1179                } else {
1180                    rd = mDispatcher.get();
1181                }
1182                if (ActivityThread.DEBUG_BROADCAST) {
1183                    int seq = intent.getIntExtra("seq", -1);
1184                    Slog.i(ActivityThread.TAG, "Receiving broadcast " + intent.getAction()
1185                            + " seq=" + seq + " to " + (rd != null ? rd.mReceiver : null));
1186                }
1187                if (rd != null) {
1188                    rd.performReceive(intent, resultCode, data, extras,
1189                            ordered, sticky, sendingUser);
1190                } else {
1191                    // The activity manager dispatched a broadcast to a registered
1192                    // receiver in this process, but before it could be delivered the
1193                    // receiver was unregistered.  Acknowledge the broadcast on its
1194                    // behalf so that the system's broadcast sequence can continue.
1195                    if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1196                            "Finishing broadcast to unregistered receiver");
1197                    IActivityManager mgr = ActivityManager.getService();
1198                    try {
1199                        if (extras != null) {
1200                            extras.setAllowFds(false);
1201                        }
1202                        mgr.finishReceiver(this, resultCode, data, extras, false, intent.getFlags());
1203                    } catch (RemoteException e) {
1204                        throw e.rethrowFromSystemServer();
1205                    }
1206                }
1207            }
1208        }
1209
1210        final IIntentReceiver.Stub mIIntentReceiver;
1211        final BroadcastReceiver mReceiver;
1212        final Context mContext;
1213        final Handler mActivityThread;
1214        final Instrumentation mInstrumentation;
1215        final boolean mRegistered;
1216        final IntentReceiverLeaked mLocation;
1217        RuntimeException mUnregisterLocation;
1218        boolean mForgotten;
1219
1220        final class Args extends BroadcastReceiver.PendingResult {
1221            private Intent mCurIntent;
1222            private final boolean mOrdered;
1223            private boolean mDispatched;
1224            private Throwable mPreviousRunStacktrace; // To investigate b/37809561. STOPSHIP remove.
1225
1226            public Args(Intent intent, int resultCode, String resultData, Bundle resultExtras,
1227                    boolean ordered, boolean sticky, int sendingUser) {
1228                super(resultCode, resultData, resultExtras,
1229                        mRegistered ? TYPE_REGISTERED : TYPE_UNREGISTERED, ordered,
1230                        sticky, mIIntentReceiver.asBinder(), sendingUser, intent.getFlags());
1231                mCurIntent = intent;
1232                mOrdered = ordered;
1233            }
1234
1235            public final Runnable getRunnable() {
1236                return () -> {
1237                    final BroadcastReceiver receiver = mReceiver;
1238                    final boolean ordered = mOrdered;
1239
1240                    if (ActivityThread.DEBUG_BROADCAST) {
1241                        int seq = mCurIntent.getIntExtra("seq", -1);
1242                        Slog.i(ActivityThread.TAG, "Dispatching broadcast " + mCurIntent.getAction()
1243                                + " seq=" + seq + " to " + mReceiver);
1244                        Slog.i(ActivityThread.TAG, "  mRegistered=" + mRegistered
1245                                + " mOrderedHint=" + ordered);
1246                    }
1247
1248                    final IActivityManager mgr = ActivityManager.getService();
1249                    final Intent intent = mCurIntent;
1250                    if (intent == null) {
1251                        Log.wtf(TAG, "Null intent being dispatched, mDispatched=" + mDispatched
1252                                + ": run() previously called at "
1253                                + Log.getStackTraceString(mPreviousRunStacktrace));
1254                    }
1255
1256                    mCurIntent = null;
1257                    mDispatched = true;
1258                    mPreviousRunStacktrace = new Throwable("Previous stacktrace");
1259                    if (receiver == null || intent == null || mForgotten) {
1260                        if (mRegistered && ordered) {
1261                            if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1262                                    "Finishing null broadcast to " + mReceiver);
1263                            sendFinished(mgr);
1264                        }
1265                        return;
1266                    }
1267
1268                    Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastReceiveReg");
1269                    try {
1270                        ClassLoader cl = mReceiver.getClass().getClassLoader();
1271                        intent.setExtrasClassLoader(cl);
1272                        intent.prepareToEnterProcess();
1273                        setExtrasClassLoader(cl);
1274                        receiver.setPendingResult(this);
1275                        receiver.onReceive(mContext, intent);
1276                    } catch (Exception e) {
1277                        if (mRegistered && ordered) {
1278                            if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1279                                    "Finishing failed broadcast to " + mReceiver);
1280                            sendFinished(mgr);
1281                        }
1282                        if (mInstrumentation == null ||
1283                                !mInstrumentation.onException(mReceiver, e)) {
1284                            Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1285                            throw new RuntimeException(
1286                                    "Error receiving broadcast " + intent
1287                                            + " in " + mReceiver, e);
1288                        }
1289                    }
1290
1291                    if (receiver.getPendingResult() != null) {
1292                        finish();
1293                    }
1294                    Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
1295                };
1296            }
1297        }
1298
1299        ReceiverDispatcher(BroadcastReceiver receiver, Context context,
1300                Handler activityThread, Instrumentation instrumentation,
1301                boolean registered) {
1302            if (activityThread == null) {
1303                throw new NullPointerException("Handler must not be null");
1304            }
1305
1306            mIIntentReceiver = new InnerReceiver(this, !registered);
1307            mReceiver = receiver;
1308            mContext = context;
1309            mActivityThread = activityThread;
1310            mInstrumentation = instrumentation;
1311            mRegistered = registered;
1312            mLocation = new IntentReceiverLeaked(null);
1313            mLocation.fillInStackTrace();
1314        }
1315
1316        void validate(Context context, Handler activityThread) {
1317            if (mContext != context) {
1318                throw new IllegalStateException(
1319                    "Receiver " + mReceiver +
1320                    " registered with differing Context (was " +
1321                    mContext + " now " + context + ")");
1322            }
1323            if (mActivityThread != activityThread) {
1324                throw new IllegalStateException(
1325                    "Receiver " + mReceiver +
1326                    " registered with differing handler (was " +
1327                    mActivityThread + " now " + activityThread + ")");
1328            }
1329        }
1330
1331        IntentReceiverLeaked getLocation() {
1332            return mLocation;
1333        }
1334
1335        BroadcastReceiver getIntentReceiver() {
1336            return mReceiver;
1337        }
1338
1339        IIntentReceiver getIIntentReceiver() {
1340            return mIIntentReceiver;
1341        }
1342
1343        void setUnregisterLocation(RuntimeException ex) {
1344            mUnregisterLocation = ex;
1345        }
1346
1347        RuntimeException getUnregisterLocation() {
1348            return mUnregisterLocation;
1349        }
1350
1351        public void performReceive(Intent intent, int resultCode, String data,
1352                Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1353            final Args args = new Args(intent, resultCode, data, extras, ordered,
1354                    sticky, sendingUser);
1355            if (intent == null) {
1356                Log.wtf(TAG, "Null intent received");
1357            } else {
1358                if (ActivityThread.DEBUG_BROADCAST) {
1359                    int seq = intent.getIntExtra("seq", -1);
1360                    Slog.i(ActivityThread.TAG, "Enqueueing broadcast " + intent.getAction()
1361                            + " seq=" + seq + " to " + mReceiver);
1362                }
1363            }
1364            if (intent == null || !mActivityThread.post(args.getRunnable())) {
1365                if (mRegistered && ordered) {
1366                    IActivityManager mgr = ActivityManager.getService();
1367                    if (ActivityThread.DEBUG_BROADCAST) Slog.i(ActivityThread.TAG,
1368                            "Finishing sync broadcast to " + mReceiver);
1369                    args.sendFinished(mgr);
1370                }
1371            }
1372        }
1373
1374    }
1375
1376    public final IServiceConnection getServiceDispatcher(ServiceConnection c,
1377            Context context, Handler handler, int flags) {
1378        synchronized (mServices) {
1379            LoadedApk.ServiceDispatcher sd = null;
1380            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map = mServices.get(context);
1381            if (map != null) {
1382                if (DEBUG) Slog.d(TAG, "Returning existing dispatcher " + sd + " for conn " + c);
1383                sd = map.get(c);
1384            }
1385            if (sd == null) {
1386                sd = new ServiceDispatcher(c, context, handler, flags);
1387                if (DEBUG) Slog.d(TAG, "Creating new dispatcher " + sd + " for conn " + c);
1388                if (map == null) {
1389                    map = new ArrayMap<>();
1390                    mServices.put(context, map);
1391                }
1392                map.put(c, sd);
1393            } else {
1394                sd.validate(context, handler);
1395            }
1396            return sd.getIServiceConnection();
1397        }
1398    }
1399
1400    public final IServiceConnection forgetServiceDispatcher(Context context,
1401            ServiceConnection c) {
1402        synchronized (mServices) {
1403            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> map
1404                    = mServices.get(context);
1405            LoadedApk.ServiceDispatcher sd = null;
1406            if (map != null) {
1407                sd = map.get(c);
1408                if (sd != null) {
1409                    if (DEBUG) Slog.d(TAG, "Removing dispatcher " + sd + " for conn " + c);
1410                    map.remove(c);
1411                    sd.doForget();
1412                    if (map.size() == 0) {
1413                        mServices.remove(context);
1414                    }
1415                    if ((sd.getFlags()&Context.BIND_DEBUG_UNBIND) != 0) {
1416                        ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder
1417                                = mUnboundServices.get(context);
1418                        if (holder == null) {
1419                            holder = new ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher>();
1420                            mUnboundServices.put(context, holder);
1421                        }
1422                        RuntimeException ex = new IllegalArgumentException(
1423                                "Originally unbound here:");
1424                        ex.fillInStackTrace();
1425                        sd.setUnbindLocation(ex);
1426                        holder.put(c, sd);
1427                    }
1428                    return sd.getIServiceConnection();
1429                }
1430            }
1431            ArrayMap<ServiceConnection, LoadedApk.ServiceDispatcher> holder
1432                    = mUnboundServices.get(context);
1433            if (holder != null) {
1434                sd = holder.get(c);
1435                if (sd != null) {
1436                    RuntimeException ex = sd.getUnbindLocation();
1437                    throw new IllegalArgumentException(
1438                            "Unbinding Service " + c
1439                            + " that was already unbound", ex);
1440                }
1441            }
1442            if (context == null) {
1443                throw new IllegalStateException("Unbinding Service " + c
1444                        + " from Context that is no longer in use: " + context);
1445            } else {
1446                throw new IllegalArgumentException("Service not registered: " + c);
1447            }
1448        }
1449    }
1450
1451    static final class ServiceDispatcher {
1452        private final ServiceDispatcher.InnerConnection mIServiceConnection;
1453        private final ServiceConnection mConnection;
1454        private final Context mContext;
1455        private final Handler mActivityThread;
1456        private final ServiceConnectionLeaked mLocation;
1457        private final int mFlags;
1458
1459        private RuntimeException mUnbindLocation;
1460
1461        private boolean mForgotten;
1462
1463        private static class ConnectionInfo {
1464            IBinder binder;
1465            IBinder.DeathRecipient deathMonitor;
1466        }
1467
1468        private static class InnerConnection extends IServiceConnection.Stub {
1469            final WeakReference<LoadedApk.ServiceDispatcher> mDispatcher;
1470
1471            InnerConnection(LoadedApk.ServiceDispatcher sd) {
1472                mDispatcher = new WeakReference<LoadedApk.ServiceDispatcher>(sd);
1473            }
1474
1475            public void connected(ComponentName name, IBinder service, boolean dead)
1476                    throws RemoteException {
1477                LoadedApk.ServiceDispatcher sd = mDispatcher.get();
1478                if (sd != null) {
1479                    sd.connected(name, service, dead);
1480                }
1481            }
1482        }
1483
1484        private final ArrayMap<ComponentName, ServiceDispatcher.ConnectionInfo> mActiveConnections
1485            = new ArrayMap<ComponentName, ServiceDispatcher.ConnectionInfo>();
1486
1487        ServiceDispatcher(ServiceConnection conn,
1488                Context context, Handler activityThread, int flags) {
1489            mIServiceConnection = new InnerConnection(this);
1490            mConnection = conn;
1491            mContext = context;
1492            mActivityThread = activityThread;
1493            mLocation = new ServiceConnectionLeaked(null);
1494            mLocation.fillInStackTrace();
1495            mFlags = flags;
1496        }
1497
1498        void validate(Context context, Handler activityThread) {
1499            if (mContext != context) {
1500                throw new RuntimeException(
1501                    "ServiceConnection " + mConnection +
1502                    " registered with differing Context (was " +
1503                    mContext + " now " + context + ")");
1504            }
1505            if (mActivityThread != activityThread) {
1506                throw new RuntimeException(
1507                    "ServiceConnection " + mConnection +
1508                    " registered with differing handler (was " +
1509                    mActivityThread + " now " + activityThread + ")");
1510            }
1511        }
1512
1513        void doForget() {
1514            synchronized(this) {
1515                for (int i=0; i<mActiveConnections.size(); i++) {
1516                    ServiceDispatcher.ConnectionInfo ci = mActiveConnections.valueAt(i);
1517                    ci.binder.unlinkToDeath(ci.deathMonitor, 0);
1518                }
1519                mActiveConnections.clear();
1520                mForgotten = true;
1521            }
1522        }
1523
1524        ServiceConnectionLeaked getLocation() {
1525            return mLocation;
1526        }
1527
1528        ServiceConnection getServiceConnection() {
1529            return mConnection;
1530        }
1531
1532        IServiceConnection getIServiceConnection() {
1533            return mIServiceConnection;
1534        }
1535
1536        int getFlags() {
1537            return mFlags;
1538        }
1539
1540        void setUnbindLocation(RuntimeException ex) {
1541            mUnbindLocation = ex;
1542        }
1543
1544        RuntimeException getUnbindLocation() {
1545            return mUnbindLocation;
1546        }
1547
1548        public void connected(ComponentName name, IBinder service, boolean dead) {
1549            if (mActivityThread != null) {
1550                mActivityThread.post(new RunConnection(name, service, 0, dead));
1551            } else {
1552                doConnected(name, service, dead);
1553            }
1554        }
1555
1556        public void death(ComponentName name, IBinder service) {
1557            if (mActivityThread != null) {
1558                mActivityThread.post(new RunConnection(name, service, 1, false));
1559            } else {
1560                doDeath(name, service);
1561            }
1562        }
1563
1564        public void doConnected(ComponentName name, IBinder service, boolean dead) {
1565            ServiceDispatcher.ConnectionInfo old;
1566            ServiceDispatcher.ConnectionInfo info;
1567
1568            synchronized (this) {
1569                if (mForgotten) {
1570                    // We unbound before receiving the connection; ignore
1571                    // any connection received.
1572                    return;
1573                }
1574                old = mActiveConnections.get(name);
1575                if (old != null && old.binder == service) {
1576                    // Huh, already have this one.  Oh well!
1577                    return;
1578                }
1579
1580                if (service != null) {
1581                    // A new service is being connected... set it all up.
1582                    info = new ConnectionInfo();
1583                    info.binder = service;
1584                    info.deathMonitor = new DeathMonitor(name, service);
1585                    try {
1586                        service.linkToDeath(info.deathMonitor, 0);
1587                        mActiveConnections.put(name, info);
1588                    } catch (RemoteException e) {
1589                        // This service was dead before we got it...  just
1590                        // don't do anything with it.
1591                        mActiveConnections.remove(name);
1592                        return;
1593                    }
1594
1595                } else {
1596                    // The named service is being disconnected... clean up.
1597                    mActiveConnections.remove(name);
1598                }
1599
1600                if (old != null) {
1601                    old.binder.unlinkToDeath(old.deathMonitor, 0);
1602                }
1603            }
1604
1605            // If there was an old service, it is now disconnected.
1606            if (old != null) {
1607                mConnection.onServiceDisconnected(name);
1608            }
1609            if (dead) {
1610                mConnection.onBindingDied(name);
1611            }
1612            // If there is a new service, it is now connected.
1613            if (service != null) {
1614                mConnection.onServiceConnected(name, service);
1615            }
1616        }
1617
1618        public void doDeath(ComponentName name, IBinder service) {
1619            synchronized (this) {
1620                ConnectionInfo old = mActiveConnections.get(name);
1621                if (old == null || old.binder != service) {
1622                    // Death for someone different than who we last
1623                    // reported...  just ignore it.
1624                    return;
1625                }
1626                mActiveConnections.remove(name);
1627                old.binder.unlinkToDeath(old.deathMonitor, 0);
1628            }
1629
1630            mConnection.onServiceDisconnected(name);
1631        }
1632
1633        private final class RunConnection implements Runnable {
1634            RunConnection(ComponentName name, IBinder service, int command, boolean dead) {
1635                mName = name;
1636                mService = service;
1637                mCommand = command;
1638                mDead = dead;
1639            }
1640
1641            public void run() {
1642                if (mCommand == 0) {
1643                    doConnected(mName, mService, mDead);
1644                } else if (mCommand == 1) {
1645                    doDeath(mName, mService);
1646                }
1647            }
1648
1649            final ComponentName mName;
1650            final IBinder mService;
1651            final int mCommand;
1652            final boolean mDead;
1653        }
1654
1655        private final class DeathMonitor implements IBinder.DeathRecipient
1656        {
1657            DeathMonitor(ComponentName name, IBinder service) {
1658                mName = name;
1659                mService = service;
1660            }
1661
1662            public void binderDied() {
1663                death(mName, mService);
1664            }
1665
1666            final ComponentName mName;
1667            final IBinder mService;
1668        }
1669    }
1670}
1671