PackageManagerService.java revision b371c7b6e234bda71a0266e67722c859227f643c
1/*
2 * Copyright (C) 2006 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 com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
45import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
46import static android.content.pm.PackageManager.INSTALL_INTERNAL;
47import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
51import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
52import static android.content.pm.PackageManager.MATCH_ALL;
53import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST;
54import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR;
55import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING;
56import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
57import static android.content.pm.PackageParser.isApkFile;
58import static android.os.Process.PACKAGE_INFO_GID;
59import static android.os.Process.SYSTEM_UID;
60import static android.system.OsConstants.O_CREAT;
61import static android.system.OsConstants.O_RDWR;
62import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
63import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
64import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
65import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
66import static com.android.internal.util.ArrayUtils.appendInt;
67import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
68import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
69import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
70import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
71import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
72
73import android.Manifest;
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.AppGlobals;
77import android.app.IActivityManager;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.app.usage.UsageStats;
81import android.app.usage.UsageStatsManager;
82import android.content.BroadcastReceiver;
83import android.content.ComponentName;
84import android.content.Context;
85import android.content.IIntentReceiver;
86import android.content.Intent;
87import android.content.IntentFilter;
88import android.content.IntentSender;
89import android.content.IntentSender.SendIntentException;
90import android.content.ServiceConnection;
91import android.content.pm.ActivityInfo;
92import android.content.pm.ApplicationInfo;
93import android.content.pm.FeatureInfo;
94import android.content.pm.IPackageDataObserver;
95import android.content.pm.IPackageDeleteObserver;
96import android.content.pm.IPackageDeleteObserver2;
97import android.content.pm.IPackageInstallObserver2;
98import android.content.pm.IPackageInstaller;
99import android.content.pm.IPackageManager;
100import android.content.pm.IPackageMoveObserver;
101import android.content.pm.IPackageStatsObserver;
102import android.content.pm.InstrumentationInfo;
103import android.content.pm.IntentFilterVerificationInfo;
104import android.content.pm.KeySet;
105import android.content.pm.ManifestDigest;
106import android.content.pm.PackageCleanItem;
107import android.content.pm.PackageInfo;
108import android.content.pm.PackageInfoLite;
109import android.content.pm.PackageInstaller;
110import android.content.pm.PackageManager;
111import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
112import android.content.pm.PackageParser;
113import android.content.pm.PackageParser.ActivityIntentInfo;
114import android.content.pm.PackageParser.PackageLite;
115import android.content.pm.PackageParser.PackageParserException;
116import android.content.pm.PackageStats;
117import android.content.pm.PackageUserState;
118import android.content.pm.ParceledListSlice;
119import android.content.pm.PermissionGroupInfo;
120import android.content.pm.PermissionInfo;
121import android.content.pm.ProviderInfo;
122import android.content.pm.ResolveInfo;
123import android.content.pm.ServiceInfo;
124import android.content.pm.Signature;
125import android.content.pm.UserInfo;
126import android.content.pm.VerificationParams;
127import android.content.pm.VerifierDeviceIdentity;
128import android.content.pm.VerifierInfo;
129import android.content.res.Resources;
130import android.hardware.display.DisplayManager;
131import android.net.Uri;
132import android.os.Binder;
133import android.os.Build;
134import android.os.Bundle;
135import android.os.Debug;
136import android.os.Environment;
137import android.os.Environment.UserEnvironment;
138import android.os.FileUtils;
139import android.os.Handler;
140import android.os.IBinder;
141import android.os.Looper;
142import android.os.Message;
143import android.os.Parcel;
144import android.os.ParcelFileDescriptor;
145import android.os.Process;
146import android.os.RemoteCallbackList;
147import android.os.RemoteException;
148import android.os.SELinux;
149import android.os.ServiceManager;
150import android.os.SystemClock;
151import android.os.SystemProperties;
152import android.os.UserHandle;
153import android.os.UserManager;
154import android.os.storage.IMountService;
155import android.os.storage.StorageEventListener;
156import android.os.storage.StorageManager;
157import android.os.storage.VolumeInfo;
158import android.os.storage.VolumeRecord;
159import android.security.KeyStore;
160import android.security.SystemKeyStore;
161import android.system.ErrnoException;
162import android.system.Os;
163import android.system.StructStat;
164import android.text.TextUtils;
165import android.text.format.DateUtils;
166import android.util.ArrayMap;
167import android.util.ArraySet;
168import android.util.AtomicFile;
169import android.util.DisplayMetrics;
170import android.util.EventLog;
171import android.util.ExceptionUtils;
172import android.util.Log;
173import android.util.LogPrinter;
174import android.util.MathUtils;
175import android.util.PrintStreamPrinter;
176import android.util.Slog;
177import android.util.SparseArray;
178import android.util.SparseBooleanArray;
179import android.util.SparseIntArray;
180import android.util.Xml;
181import android.view.Display;
182
183import dalvik.system.DexFile;
184import dalvik.system.VMRuntime;
185
186import libcore.io.IoUtils;
187import libcore.util.EmptyArray;
188
189import com.android.internal.R;
190import com.android.internal.app.IMediaContainerService;
191import com.android.internal.app.ResolverActivity;
192import com.android.internal.content.NativeLibraryHelper;
193import com.android.internal.content.PackageHelper;
194import com.android.internal.os.IParcelFileDescriptorFactory;
195import com.android.internal.os.SomeArgs;
196import com.android.internal.util.ArrayUtils;
197import com.android.internal.util.FastPrintWriter;
198import com.android.internal.util.FastXmlSerializer;
199import com.android.internal.util.IndentingPrintWriter;
200import com.android.internal.util.Preconditions;
201import com.android.server.EventLogTags;
202import com.android.server.FgThread;
203import com.android.server.IntentResolver;
204import com.android.server.LocalServices;
205import com.android.server.ServiceThread;
206import com.android.server.SystemConfig;
207import com.android.server.Watchdog;
208import com.android.server.pm.Settings.DatabaseVersion;
209import com.android.server.pm.PermissionsState.PermissionState;
210import com.android.server.storage.DeviceStorageMonitorInternal;
211
212import org.xmlpull.v1.XmlPullParser;
213import org.xmlpull.v1.XmlSerializer;
214
215import java.io.BufferedInputStream;
216import java.io.BufferedOutputStream;
217import java.io.BufferedReader;
218import java.io.ByteArrayInputStream;
219import java.io.ByteArrayOutputStream;
220import java.io.File;
221import java.io.FileDescriptor;
222import java.io.FileNotFoundException;
223import java.io.FileOutputStream;
224import java.io.FileReader;
225import java.io.FilenameFilter;
226import java.io.IOException;
227import java.io.InputStream;
228import java.io.PrintWriter;
229import java.nio.charset.StandardCharsets;
230import java.security.NoSuchAlgorithmException;
231import java.security.PublicKey;
232import java.security.cert.CertificateEncodingException;
233import java.security.cert.CertificateException;
234import java.text.SimpleDateFormat;
235import java.util.ArrayList;
236import java.util.Arrays;
237import java.util.Collection;
238import java.util.Collections;
239import java.util.Comparator;
240import java.util.Date;
241import java.util.Iterator;
242import java.util.List;
243import java.util.Map;
244import java.util.Objects;
245import java.util.Set;
246import java.util.concurrent.CountDownLatch;
247import java.util.concurrent.TimeUnit;
248import java.util.concurrent.atomic.AtomicBoolean;
249import java.util.concurrent.atomic.AtomicInteger;
250import java.util.concurrent.atomic.AtomicLong;
251
252/**
253 * Keep track of all those .apks everywhere.
254 *
255 * This is very central to the platform's security; please run the unit
256 * tests whenever making modifications here:
257 *
258mmm frameworks/base/tests/AndroidTests
259adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
260adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
261 *
262 * {@hide}
263 */
264public class PackageManagerService extends IPackageManager.Stub {
265    static final String TAG = "PackageManager";
266    static final boolean DEBUG_SETTINGS = false;
267    static final boolean DEBUG_PREFERRED = false;
268    static final boolean DEBUG_UPGRADE = false;
269    private static final boolean DEBUG_BACKUP = true;
270    private static final boolean DEBUG_INSTALL = false;
271    private static final boolean DEBUG_REMOVE = false;
272    private static final boolean DEBUG_BROADCASTS = false;
273    private static final boolean DEBUG_SHOW_INFO = false;
274    private static final boolean DEBUG_PACKAGE_INFO = false;
275    private static final boolean DEBUG_INTENT_MATCHING = false;
276    private static final boolean DEBUG_PACKAGE_SCANNING = false;
277    private static final boolean DEBUG_VERIFY = false;
278    private static final boolean DEBUG_DEXOPT = false;
279    private static final boolean DEBUG_ABI_SELECTION = false;
280
281    private static final int RADIO_UID = Process.PHONE_UID;
282    private static final int LOG_UID = Process.LOG_UID;
283    private static final int NFC_UID = Process.NFC_UID;
284    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
285    private static final int SHELL_UID = Process.SHELL_UID;
286
287    // Cap the size of permission trees that 3rd party apps can define
288    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
289
290    // Suffix used during package installation when copying/moving
291    // package apks to install directory.
292    private static final String INSTALL_PACKAGE_SUFFIX = "-";
293
294    static final int SCAN_NO_DEX = 1<<1;
295    static final int SCAN_FORCE_DEX = 1<<2;
296    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
297    static final int SCAN_NEW_INSTALL = 1<<4;
298    static final int SCAN_NO_PATHS = 1<<5;
299    static final int SCAN_UPDATE_TIME = 1<<6;
300    static final int SCAN_DEFER_DEX = 1<<7;
301    static final int SCAN_BOOTING = 1<<8;
302    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
303    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
304    static final int SCAN_REQUIRE_KNOWN = 1<<12;
305
306    static final int REMOVE_CHATTY = 1<<16;
307
308    private static final int[] EMPTY_INT_ARRAY = new int[0];
309
310    /**
311     * Timeout (in milliseconds) after which the watchdog should declare that
312     * our handler thread is wedged.  The usual default for such things is one
313     * minute but we sometimes do very lengthy I/O operations on this thread,
314     * such as installing multi-gigabyte applications, so ours needs to be longer.
315     */
316    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
317
318    /**
319     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
320     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
321     * settings entry if available, otherwise we use the hardcoded default.  If it's been
322     * more than this long since the last fstrim, we force one during the boot sequence.
323     *
324     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
325     * one gets run at the next available charging+idle time.  This final mandatory
326     * no-fstrim check kicks in only of the other scheduling criteria is never met.
327     */
328    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
329
330    /**
331     * Whether verification is enabled by default.
332     */
333    private static final boolean DEFAULT_VERIFY_ENABLE = true;
334
335    /**
336     * The default maximum time to wait for the verification agent to return in
337     * milliseconds.
338     */
339    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
340
341    /**
342     * The default response for package verification timeout.
343     *
344     * This can be either PackageManager.VERIFICATION_ALLOW or
345     * PackageManager.VERIFICATION_REJECT.
346     */
347    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
348
349    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
350
351    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
352            DEFAULT_CONTAINER_PACKAGE,
353            "com.android.defcontainer.DefaultContainerService");
354
355    private static final String KILL_APP_REASON_GIDS_CHANGED =
356            "permission grant or revoke changed gids";
357
358    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
359            "permissions revoked";
360
361    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
362
363    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
364
365    /** Permission grant: not grant the permission. */
366    private static final int GRANT_DENIED = 1;
367
368    /** Permission grant: grant the permission as an install permission. */
369    private static final int GRANT_INSTALL = 2;
370
371    /** Permission grant: grant the permission as a runtime one. */
372    private static final int GRANT_RUNTIME = 3;
373
374    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
375    private static final int GRANT_UPGRADE = 4;
376
377    final ServiceThread mHandlerThread;
378
379    final PackageHandler mHandler;
380
381    /**
382     * Messages for {@link #mHandler} that need to wait for system ready before
383     * being dispatched.
384     */
385    private ArrayList<Message> mPostSystemReadyMessages;
386
387    final int mSdkVersion = Build.VERSION.SDK_INT;
388
389    final Context mContext;
390    final boolean mFactoryTest;
391    final boolean mOnlyCore;
392    final boolean mLazyDexOpt;
393    final long mDexOptLRUThresholdInMills;
394    final DisplayMetrics mMetrics;
395    final int mDefParseFlags;
396    final String[] mSeparateProcesses;
397    final boolean mIsUpgrade;
398
399    // This is where all application persistent data goes.
400    final File mAppDataDir;
401
402    // This is where all application persistent data goes for secondary users.
403    final File mUserAppDataDir;
404
405    /** The location for ASEC container files on internal storage. */
406    final String mAsecInternalPath;
407
408    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
409    // LOCK HELD.  Can be called with mInstallLock held.
410    final Installer mInstaller;
411
412    /** Directory where installed third-party apps stored */
413    final File mAppInstallDir;
414
415    /**
416     * Directory to which applications installed internally have their
417     * 32 bit native libraries copied.
418     */
419    private File mAppLib32InstallDir;
420
421    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
422    // apps.
423    final File mDrmAppPrivateInstallDir;
424
425    // ----------------------------------------------------------------
426
427    // Lock for state used when installing and doing other long running
428    // operations.  Methods that must be called with this lock held have
429    // the suffix "LI".
430    final Object mInstallLock = new Object();
431
432    // ----------------------------------------------------------------
433
434    // Keys are String (package name), values are Package.  This also serves
435    // as the lock for the global state.  Methods that must be called with
436    // this lock held have the prefix "LP".
437    final ArrayMap<String, PackageParser.Package> mPackages =
438            new ArrayMap<String, PackageParser.Package>();
439
440    // Tracks available target package names -> overlay package paths.
441    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
442        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
443
444    final Settings mSettings;
445    boolean mRestoredSettings;
446
447    // System configuration read by SystemConfig.
448    final int[] mGlobalGids;
449    final SparseArray<ArraySet<String>> mSystemPermissions;
450    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
451
452    // If mac_permissions.xml was found for seinfo labeling.
453    boolean mFoundPolicyFile;
454
455    // If a recursive restorecon of /data/data/<pkg> is needed.
456    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
457
458    public static final class SharedLibraryEntry {
459        public final String path;
460        public final String apk;
461
462        SharedLibraryEntry(String _path, String _apk) {
463            path = _path;
464            apk = _apk;
465        }
466    }
467
468    // Currently known shared libraries.
469    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
470            new ArrayMap<String, SharedLibraryEntry>();
471
472    // All available activities, for your resolving pleasure.
473    final ActivityIntentResolver mActivities =
474            new ActivityIntentResolver();
475
476    // All available receivers, for your resolving pleasure.
477    final ActivityIntentResolver mReceivers =
478            new ActivityIntentResolver();
479
480    // All available services, for your resolving pleasure.
481    final ServiceIntentResolver mServices = new ServiceIntentResolver();
482
483    // All available providers, for your resolving pleasure.
484    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
485
486    // Mapping from provider base names (first directory in content URI codePath)
487    // to the provider information.
488    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
489            new ArrayMap<String, PackageParser.Provider>();
490
491    // Mapping from instrumentation class names to info about them.
492    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
493            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
494
495    // Mapping from permission names to info about them.
496    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
497            new ArrayMap<String, PackageParser.PermissionGroup>();
498
499    // Packages whose data we have transfered into another package, thus
500    // should no longer exist.
501    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
502
503    // Broadcast actions that are only available to the system.
504    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
505
506    /** List of packages waiting for verification. */
507    final SparseArray<PackageVerificationState> mPendingVerification
508            = new SparseArray<PackageVerificationState>();
509
510    /** Set of packages associated with each app op permission. */
511    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
512
513    final PackageInstallerService mInstallerService;
514
515    private final PackageDexOptimizer mPackageDexOptimizer;
516
517    private AtomicInteger mNextMoveId = new AtomicInteger();
518    private final MoveCallbacks mMoveCallbacks;
519
520    // Cache of users who need badging.
521    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
522
523    /** Token for keys in mPendingVerification. */
524    private int mPendingVerificationToken = 0;
525
526    volatile boolean mSystemReady;
527    volatile boolean mSafeMode;
528    volatile boolean mHasSystemUidErrors;
529
530    ApplicationInfo mAndroidApplication;
531    final ActivityInfo mResolveActivity = new ActivityInfo();
532    final ResolveInfo mResolveInfo = new ResolveInfo();
533    ComponentName mResolveComponentName;
534    PackageParser.Package mPlatformPackage;
535    ComponentName mCustomResolverComponentName;
536
537    boolean mResolverReplaced = false;
538
539    private final ComponentName mIntentFilterVerifierComponent;
540    private int mIntentFilterVerificationToken = 0;
541
542    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
543            = new SparseArray<IntentFilterVerificationState>();
544
545    private interface IntentFilterVerifier<T extends IntentFilter> {
546        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
547                                               T filter, String packageName);
548        void startVerifications(int userId);
549        void receiveVerificationResponse(int verificationId);
550    }
551
552    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
553        private Context mContext;
554        private ComponentName mIntentFilterVerifierComponent;
555        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
556
557        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
558            mContext = context;
559            mIntentFilterVerifierComponent = verifierComponent;
560        }
561
562        private String getDefaultScheme() {
563            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
564            return IntentFilter.SCHEME_HTTP;
565        }
566
567        @Override
568        public void startVerifications(int userId) {
569            // Launch verifications requests
570            int count = mCurrentIntentFilterVerifications.size();
571            for (int n=0; n<count; n++) {
572                int verificationId = mCurrentIntentFilterVerifications.get(n);
573                final IntentFilterVerificationState ivs =
574                        mIntentFilterVerificationStates.get(verificationId);
575
576                String packageName = ivs.getPackageName();
577
578                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
579                final int filterCount = filters.size();
580                ArraySet<String> domainsSet = new ArraySet<>();
581                for (int m=0; m<filterCount; m++) {
582                    PackageParser.ActivityIntentInfo filter = filters.get(m);
583                    domainsSet.addAll(filter.getHostsList());
584                }
585                ArrayList<String> domainsList = new ArrayList<>(domainsSet);
586                synchronized (mPackages) {
587                    if (mSettings.createIntentFilterVerificationIfNeededLPw(
588                            packageName, domainsList) != null) {
589                        scheduleWriteSettingsLocked();
590                    }
591                }
592                sendVerificationRequest(userId, verificationId, ivs);
593            }
594            mCurrentIntentFilterVerifications.clear();
595        }
596
597        private void sendVerificationRequest(int userId, int verificationId,
598                IntentFilterVerificationState ivs) {
599
600            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
601            verificationIntent.putExtra(
602                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
603                    verificationId);
604            verificationIntent.putExtra(
605                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
606                    getDefaultScheme());
607            verificationIntent.putExtra(
608                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
609                    ivs.getHostsString());
610            verificationIntent.putExtra(
611                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
612                    ivs.getPackageName());
613            verificationIntent.setComponent(mIntentFilterVerifierComponent);
614            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
615
616            UserHandle user = new UserHandle(userId);
617            mContext.sendBroadcastAsUser(verificationIntent, user);
618            Slog.d(TAG, "Sending IntenFilter verification broadcast");
619        }
620
621        public void receiveVerificationResponse(int verificationId) {
622            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
623
624            final boolean verified = ivs.isVerified();
625
626            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
627            final int count = filters.size();
628            for (int n=0; n<count; n++) {
629                PackageParser.ActivityIntentInfo filter = filters.get(n);
630                filter.setVerified(verified);
631
632                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
633                        + verified + " and hosts:" + ivs.getHostsString());
634            }
635
636            mIntentFilterVerificationStates.remove(verificationId);
637
638            final String packageName = ivs.getPackageName();
639            IntentFilterVerificationInfo ivi = null;
640
641            synchronized (mPackages) {
642                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
643            }
644            if (ivi == null) {
645                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
646                        + verificationId + " packageName:" + packageName);
647                return;
648            }
649            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId:"
650                    + verificationId);
651
652            synchronized (mPackages) {
653                if (verified) {
654                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
655                } else {
656                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
657                }
658                scheduleWriteSettingsLocked();
659
660                final int userId = ivs.getUserId();
661                if (userId != UserHandle.USER_ALL) {
662                    final int userStatus =
663                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
664
665                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
666                    boolean needUpdate = false;
667
668                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
669                    // already been set by the User thru the Disambiguation dialog
670                    switch (userStatus) {
671                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
672                            if (verified) {
673                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
674                            } else {
675                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
676                            }
677                            needUpdate = true;
678                            break;
679
680                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
681                            if (verified) {
682                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
683                                needUpdate = true;
684                            }
685                            break;
686
687                        default:
688                            // Nothing to do
689                    }
690
691                    if (needUpdate) {
692                        mSettings.updateIntentFilterVerificationStatusLPw(
693                                packageName, updatedStatus, userId);
694                        scheduleWritePackageRestrictionsLocked(userId);
695                    }
696                }
697            }
698        }
699
700        @Override
701        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
702                    ActivityIntentInfo filter, String packageName) {
703            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
704                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
705                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
706                return false;
707            }
708            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
709            if (ivs == null) {
710                ivs = createDomainVerificationState(verifierId, userId, verificationId,
711                        packageName);
712            }
713            if (!hasValidDomains(filter)) {
714                return false;
715            }
716            ivs.addFilter(filter);
717            return true;
718        }
719
720        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
721                int userId, int verificationId, String packageName) {
722            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
723                    verifierId, userId, packageName);
724            ivs.setPendingState();
725            synchronized (mPackages) {
726                mIntentFilterVerificationStates.append(verificationId, ivs);
727                mCurrentIntentFilterVerifications.add(verificationId);
728            }
729            return ivs;
730        }
731    }
732
733    private static boolean hasValidDomains(ActivityIntentInfo filter) {
734        return hasValidDomains(filter, true);
735    }
736
737    private static boolean hasValidDomains(ActivityIntentInfo filter, boolean logging) {
738        boolean hasHTTPorHTTPS = filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
739                filter.hasDataScheme(IntentFilter.SCHEME_HTTPS);
740        if (!hasHTTPorHTTPS) {
741            if (logging) {
742                Slog.d(TAG, "IntentFilter does not contain any HTTP or HTTPS data scheme");
743            }
744            return false;
745        }
746        return true;
747    }
748
749    private IntentFilterVerifier mIntentFilterVerifier;
750
751    // Set of pending broadcasts for aggregating enable/disable of components.
752    static class PendingPackageBroadcasts {
753        // for each user id, a map of <package name -> components within that package>
754        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
755
756        public PendingPackageBroadcasts() {
757            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
758        }
759
760        public ArrayList<String> get(int userId, String packageName) {
761            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
762            return packages.get(packageName);
763        }
764
765        public void put(int userId, String packageName, ArrayList<String> components) {
766            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
767            packages.put(packageName, components);
768        }
769
770        public void remove(int userId, String packageName) {
771            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
772            if (packages != null) {
773                packages.remove(packageName);
774            }
775        }
776
777        public void remove(int userId) {
778            mUidMap.remove(userId);
779        }
780
781        public int userIdCount() {
782            return mUidMap.size();
783        }
784
785        public int userIdAt(int n) {
786            return mUidMap.keyAt(n);
787        }
788
789        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
790            return mUidMap.get(userId);
791        }
792
793        public int size() {
794            // total number of pending broadcast entries across all userIds
795            int num = 0;
796            for (int i = 0; i< mUidMap.size(); i++) {
797                num += mUidMap.valueAt(i).size();
798            }
799            return num;
800        }
801
802        public void clear() {
803            mUidMap.clear();
804        }
805
806        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
807            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
808            if (map == null) {
809                map = new ArrayMap<String, ArrayList<String>>();
810                mUidMap.put(userId, map);
811            }
812            return map;
813        }
814    }
815    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
816
817    // Service Connection to remote media container service to copy
818    // package uri's from external media onto secure containers
819    // or internal storage.
820    private IMediaContainerService mContainerService = null;
821
822    static final int SEND_PENDING_BROADCAST = 1;
823    static final int MCS_BOUND = 3;
824    static final int END_COPY = 4;
825    static final int INIT_COPY = 5;
826    static final int MCS_UNBIND = 6;
827    static final int START_CLEANING_PACKAGE = 7;
828    static final int FIND_INSTALL_LOC = 8;
829    static final int POST_INSTALL = 9;
830    static final int MCS_RECONNECT = 10;
831    static final int MCS_GIVE_UP = 11;
832    static final int UPDATED_MEDIA_STATUS = 12;
833    static final int WRITE_SETTINGS = 13;
834    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
835    static final int PACKAGE_VERIFIED = 15;
836    static final int CHECK_PENDING_VERIFICATION = 16;
837    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
838    static final int INTENT_FILTER_VERIFIED = 18;
839
840    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
841
842    // Delay time in millisecs
843    static final int BROADCAST_DELAY = 10 * 1000;
844
845    static UserManagerService sUserManager;
846
847    // Stores a list of users whose package restrictions file needs to be updated
848    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
849
850    final private DefaultContainerConnection mDefContainerConn =
851            new DefaultContainerConnection();
852    class DefaultContainerConnection implements ServiceConnection {
853        public void onServiceConnected(ComponentName name, IBinder service) {
854            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
855            IMediaContainerService imcs =
856                IMediaContainerService.Stub.asInterface(service);
857            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
858        }
859
860        public void onServiceDisconnected(ComponentName name) {
861            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
862        }
863    };
864
865    // Recordkeeping of restore-after-install operations that are currently in flight
866    // between the Package Manager and the Backup Manager
867    class PostInstallData {
868        public InstallArgs args;
869        public PackageInstalledInfo res;
870
871        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
872            args = _a;
873            res = _r;
874        }
875    };
876    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
877    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
878
879    // backup/restore of preferred activity state
880    private static final String TAG_PREFERRED_BACKUP = "pa";
881
882    private final String mRequiredVerifierPackage;
883
884    private final PackageUsage mPackageUsage = new PackageUsage();
885
886    private class PackageUsage {
887        private static final int WRITE_INTERVAL
888            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
889
890        private final Object mFileLock = new Object();
891        private final AtomicLong mLastWritten = new AtomicLong(0);
892        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
893
894        private boolean mIsHistoricalPackageUsageAvailable = true;
895
896        boolean isHistoricalPackageUsageAvailable() {
897            return mIsHistoricalPackageUsageAvailable;
898        }
899
900        void write(boolean force) {
901            if (force) {
902                writeInternal();
903                return;
904            }
905            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
906                && !DEBUG_DEXOPT) {
907                return;
908            }
909            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
910                new Thread("PackageUsage_DiskWriter") {
911                    @Override
912                    public void run() {
913                        try {
914                            writeInternal();
915                        } finally {
916                            mBackgroundWriteRunning.set(false);
917                        }
918                    }
919                }.start();
920            }
921        }
922
923        private void writeInternal() {
924            synchronized (mPackages) {
925                synchronized (mFileLock) {
926                    AtomicFile file = getFile();
927                    FileOutputStream f = null;
928                    try {
929                        f = file.startWrite();
930                        BufferedOutputStream out = new BufferedOutputStream(f);
931                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
932                        StringBuilder sb = new StringBuilder();
933                        for (PackageParser.Package pkg : mPackages.values()) {
934                            if (pkg.mLastPackageUsageTimeInMills == 0) {
935                                continue;
936                            }
937                            sb.setLength(0);
938                            sb.append(pkg.packageName);
939                            sb.append(' ');
940                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
941                            sb.append('\n');
942                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
943                        }
944                        out.flush();
945                        file.finishWrite(f);
946                    } catch (IOException e) {
947                        if (f != null) {
948                            file.failWrite(f);
949                        }
950                        Log.e(TAG, "Failed to write package usage times", e);
951                    }
952                }
953            }
954            mLastWritten.set(SystemClock.elapsedRealtime());
955        }
956
957        void readLP() {
958            synchronized (mFileLock) {
959                AtomicFile file = getFile();
960                BufferedInputStream in = null;
961                try {
962                    in = new BufferedInputStream(file.openRead());
963                    StringBuffer sb = new StringBuffer();
964                    while (true) {
965                        String packageName = readToken(in, sb, ' ');
966                        if (packageName == null) {
967                            break;
968                        }
969                        String timeInMillisString = readToken(in, sb, '\n');
970                        if (timeInMillisString == null) {
971                            throw new IOException("Failed to find last usage time for package "
972                                                  + packageName);
973                        }
974                        PackageParser.Package pkg = mPackages.get(packageName);
975                        if (pkg == null) {
976                            continue;
977                        }
978                        long timeInMillis;
979                        try {
980                            timeInMillis = Long.parseLong(timeInMillisString.toString());
981                        } catch (NumberFormatException e) {
982                            throw new IOException("Failed to parse " + timeInMillisString
983                                                  + " as a long.", e);
984                        }
985                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
986                    }
987                } catch (FileNotFoundException expected) {
988                    mIsHistoricalPackageUsageAvailable = false;
989                } catch (IOException e) {
990                    Log.w(TAG, "Failed to read package usage times", e);
991                } finally {
992                    IoUtils.closeQuietly(in);
993                }
994            }
995            mLastWritten.set(SystemClock.elapsedRealtime());
996        }
997
998        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
999                throws IOException {
1000            sb.setLength(0);
1001            while (true) {
1002                int ch = in.read();
1003                if (ch == -1) {
1004                    if (sb.length() == 0) {
1005                        return null;
1006                    }
1007                    throw new IOException("Unexpected EOF");
1008                }
1009                if (ch == endOfToken) {
1010                    return sb.toString();
1011                }
1012                sb.append((char)ch);
1013            }
1014        }
1015
1016        private AtomicFile getFile() {
1017            File dataDir = Environment.getDataDirectory();
1018            File systemDir = new File(dataDir, "system");
1019            File fname = new File(systemDir, "package-usage.list");
1020            return new AtomicFile(fname);
1021        }
1022    }
1023
1024    class PackageHandler extends Handler {
1025        private boolean mBound = false;
1026        final ArrayList<HandlerParams> mPendingInstalls =
1027            new ArrayList<HandlerParams>();
1028
1029        private boolean connectToService() {
1030            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1031                    " DefaultContainerService");
1032            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1033            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1034            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1035                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1036                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1037                mBound = true;
1038                return true;
1039            }
1040            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1041            return false;
1042        }
1043
1044        private void disconnectService() {
1045            mContainerService = null;
1046            mBound = false;
1047            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1048            mContext.unbindService(mDefContainerConn);
1049            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1050        }
1051
1052        PackageHandler(Looper looper) {
1053            super(looper);
1054        }
1055
1056        public void handleMessage(Message msg) {
1057            try {
1058                doHandleMessage(msg);
1059            } finally {
1060                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1061            }
1062        }
1063
1064        void doHandleMessage(Message msg) {
1065            switch (msg.what) {
1066                case INIT_COPY: {
1067                    HandlerParams params = (HandlerParams) msg.obj;
1068                    int idx = mPendingInstalls.size();
1069                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1070                    // If a bind was already initiated we dont really
1071                    // need to do anything. The pending install
1072                    // will be processed later on.
1073                    if (!mBound) {
1074                        // If this is the only one pending we might
1075                        // have to bind to the service again.
1076                        if (!connectToService()) {
1077                            Slog.e(TAG, "Failed to bind to media container service");
1078                            params.serviceError();
1079                            return;
1080                        } else {
1081                            // Once we bind to the service, the first
1082                            // pending request will be processed.
1083                            mPendingInstalls.add(idx, params);
1084                        }
1085                    } else {
1086                        mPendingInstalls.add(idx, params);
1087                        // Already bound to the service. Just make
1088                        // sure we trigger off processing the first request.
1089                        if (idx == 0) {
1090                            mHandler.sendEmptyMessage(MCS_BOUND);
1091                        }
1092                    }
1093                    break;
1094                }
1095                case MCS_BOUND: {
1096                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1097                    if (msg.obj != null) {
1098                        mContainerService = (IMediaContainerService) msg.obj;
1099                    }
1100                    if (mContainerService == null) {
1101                        // Something seriously wrong. Bail out
1102                        Slog.e(TAG, "Cannot bind to media container service");
1103                        for (HandlerParams params : mPendingInstalls) {
1104                            // Indicate service bind error
1105                            params.serviceError();
1106                        }
1107                        mPendingInstalls.clear();
1108                    } else if (mPendingInstalls.size() > 0) {
1109                        HandlerParams params = mPendingInstalls.get(0);
1110                        if (params != null) {
1111                            if (params.startCopy()) {
1112                                // We are done...  look for more work or to
1113                                // go idle.
1114                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1115                                        "Checking for more work or unbind...");
1116                                // Delete pending install
1117                                if (mPendingInstalls.size() > 0) {
1118                                    mPendingInstalls.remove(0);
1119                                }
1120                                if (mPendingInstalls.size() == 0) {
1121                                    if (mBound) {
1122                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1123                                                "Posting delayed MCS_UNBIND");
1124                                        removeMessages(MCS_UNBIND);
1125                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1126                                        // Unbind after a little delay, to avoid
1127                                        // continual thrashing.
1128                                        sendMessageDelayed(ubmsg, 10000);
1129                                    }
1130                                } else {
1131                                    // There are more pending requests in queue.
1132                                    // Just post MCS_BOUND message to trigger processing
1133                                    // of next pending install.
1134                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1135                                            "Posting MCS_BOUND for next work");
1136                                    mHandler.sendEmptyMessage(MCS_BOUND);
1137                                }
1138                            }
1139                        }
1140                    } else {
1141                        // Should never happen ideally.
1142                        Slog.w(TAG, "Empty queue");
1143                    }
1144                    break;
1145                }
1146                case MCS_RECONNECT: {
1147                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1148                    if (mPendingInstalls.size() > 0) {
1149                        if (mBound) {
1150                            disconnectService();
1151                        }
1152                        if (!connectToService()) {
1153                            Slog.e(TAG, "Failed to bind to media container service");
1154                            for (HandlerParams params : mPendingInstalls) {
1155                                // Indicate service bind error
1156                                params.serviceError();
1157                            }
1158                            mPendingInstalls.clear();
1159                        }
1160                    }
1161                    break;
1162                }
1163                case MCS_UNBIND: {
1164                    // If there is no actual work left, then time to unbind.
1165                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1166
1167                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1168                        if (mBound) {
1169                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1170
1171                            disconnectService();
1172                        }
1173                    } else if (mPendingInstalls.size() > 0) {
1174                        // There are more pending requests in queue.
1175                        // Just post MCS_BOUND message to trigger processing
1176                        // of next pending install.
1177                        mHandler.sendEmptyMessage(MCS_BOUND);
1178                    }
1179
1180                    break;
1181                }
1182                case MCS_GIVE_UP: {
1183                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1184                    mPendingInstalls.remove(0);
1185                    break;
1186                }
1187                case SEND_PENDING_BROADCAST: {
1188                    String packages[];
1189                    ArrayList<String> components[];
1190                    int size = 0;
1191                    int uids[];
1192                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1193                    synchronized (mPackages) {
1194                        if (mPendingBroadcasts == null) {
1195                            return;
1196                        }
1197                        size = mPendingBroadcasts.size();
1198                        if (size <= 0) {
1199                            // Nothing to be done. Just return
1200                            return;
1201                        }
1202                        packages = new String[size];
1203                        components = new ArrayList[size];
1204                        uids = new int[size];
1205                        int i = 0;  // filling out the above arrays
1206
1207                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1208                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1209                            Iterator<Map.Entry<String, ArrayList<String>>> it
1210                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1211                                            .entrySet().iterator();
1212                            while (it.hasNext() && i < size) {
1213                                Map.Entry<String, ArrayList<String>> ent = it.next();
1214                                packages[i] = ent.getKey();
1215                                components[i] = ent.getValue();
1216                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1217                                uids[i] = (ps != null)
1218                                        ? UserHandle.getUid(packageUserId, ps.appId)
1219                                        : -1;
1220                                i++;
1221                            }
1222                        }
1223                        size = i;
1224                        mPendingBroadcasts.clear();
1225                    }
1226                    // Send broadcasts
1227                    for (int i = 0; i < size; i++) {
1228                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1229                    }
1230                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1231                    break;
1232                }
1233                case START_CLEANING_PACKAGE: {
1234                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1235                    final String packageName = (String)msg.obj;
1236                    final int userId = msg.arg1;
1237                    final boolean andCode = msg.arg2 != 0;
1238                    synchronized (mPackages) {
1239                        if (userId == UserHandle.USER_ALL) {
1240                            int[] users = sUserManager.getUserIds();
1241                            for (int user : users) {
1242                                mSettings.addPackageToCleanLPw(
1243                                        new PackageCleanItem(user, packageName, andCode));
1244                            }
1245                        } else {
1246                            mSettings.addPackageToCleanLPw(
1247                                    new PackageCleanItem(userId, packageName, andCode));
1248                        }
1249                    }
1250                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1251                    startCleaningPackages();
1252                } break;
1253                case POST_INSTALL: {
1254                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1255                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1256                    mRunningInstalls.delete(msg.arg1);
1257                    boolean deleteOld = false;
1258
1259                    if (data != null) {
1260                        InstallArgs args = data.args;
1261                        PackageInstalledInfo res = data.res;
1262
1263                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1264                            res.removedInfo.sendBroadcast(false, true, false);
1265                            Bundle extras = new Bundle(1);
1266                            extras.putInt(Intent.EXTRA_UID, res.uid);
1267
1268                            // Now that we successfully installed the package, grant runtime
1269                            // permissions if requested before broadcasting the install.
1270                            if ((args.installFlags
1271                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1272                                grantRequestedRuntimePermissions(res.pkg,
1273                                        args.user.getIdentifier());
1274                            }
1275
1276                            // Determine the set of users who are adding this
1277                            // package for the first time vs. those who are seeing
1278                            // an update.
1279                            int[] firstUsers;
1280                            int[] updateUsers = new int[0];
1281                            if (res.origUsers == null || res.origUsers.length == 0) {
1282                                firstUsers = res.newUsers;
1283                            } else {
1284                                firstUsers = new int[0];
1285                                for (int i=0; i<res.newUsers.length; i++) {
1286                                    int user = res.newUsers[i];
1287                                    boolean isNew = true;
1288                                    for (int j=0; j<res.origUsers.length; j++) {
1289                                        if (res.origUsers[j] == user) {
1290                                            isNew = false;
1291                                            break;
1292                                        }
1293                                    }
1294                                    if (isNew) {
1295                                        int[] newFirst = new int[firstUsers.length+1];
1296                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1297                                                firstUsers.length);
1298                                        newFirst[firstUsers.length] = user;
1299                                        firstUsers = newFirst;
1300                                    } else {
1301                                        int[] newUpdate = new int[updateUsers.length+1];
1302                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1303                                                updateUsers.length);
1304                                        newUpdate[updateUsers.length] = user;
1305                                        updateUsers = newUpdate;
1306                                    }
1307                                }
1308                            }
1309                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1310                                    res.pkg.applicationInfo.packageName,
1311                                    extras, null, null, firstUsers);
1312                            final boolean update = res.removedInfo.removedPackage != null;
1313                            if (update) {
1314                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1315                            }
1316                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1317                                    res.pkg.applicationInfo.packageName,
1318                                    extras, null, null, updateUsers);
1319                            if (update) {
1320                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1321                                        res.pkg.applicationInfo.packageName,
1322                                        extras, null, null, updateUsers);
1323                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1324                                        null, null,
1325                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1326
1327                                // treat asec-hosted packages like removable media on upgrade
1328                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1329                                    if (DEBUG_INSTALL) {
1330                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1331                                                + " is ASEC-hosted -> AVAILABLE");
1332                                    }
1333                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1334                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1335                                    pkgList.add(res.pkg.applicationInfo.packageName);
1336                                    sendResourcesChangedBroadcast(true, true,
1337                                            pkgList,uidArray, null);
1338                                }
1339                            }
1340                            if (res.removedInfo.args != null) {
1341                                // Remove the replaced package's older resources safely now
1342                                deleteOld = true;
1343                            }
1344
1345                            // Log current value of "unknown sources" setting
1346                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1347                                getUnknownSourcesSettings());
1348                        }
1349                        // Force a gc to clear up things
1350                        Runtime.getRuntime().gc();
1351                        // We delete after a gc for applications  on sdcard.
1352                        if (deleteOld) {
1353                            synchronized (mInstallLock) {
1354                                res.removedInfo.args.doPostDeleteLI(true);
1355                            }
1356                        }
1357                        if (args.observer != null) {
1358                            try {
1359                                Bundle extras = extrasForInstallResult(res);
1360                                args.observer.onPackageInstalled(res.name, res.returnCode,
1361                                        res.returnMsg, extras);
1362                            } catch (RemoteException e) {
1363                                Slog.i(TAG, "Observer no longer exists.");
1364                            }
1365                        }
1366                    } else {
1367                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1368                    }
1369                } break;
1370                case UPDATED_MEDIA_STATUS: {
1371                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1372                    boolean reportStatus = msg.arg1 == 1;
1373                    boolean doGc = msg.arg2 == 1;
1374                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1375                    if (doGc) {
1376                        // Force a gc to clear up stale containers.
1377                        Runtime.getRuntime().gc();
1378                    }
1379                    if (msg.obj != null) {
1380                        @SuppressWarnings("unchecked")
1381                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1382                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1383                        // Unload containers
1384                        unloadAllContainers(args);
1385                    }
1386                    if (reportStatus) {
1387                        try {
1388                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1389                            PackageHelper.getMountService().finishMediaUpdate();
1390                        } catch (RemoteException e) {
1391                            Log.e(TAG, "MountService not running?");
1392                        }
1393                    }
1394                } break;
1395                case WRITE_SETTINGS: {
1396                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1397                    synchronized (mPackages) {
1398                        removeMessages(WRITE_SETTINGS);
1399                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1400                        mSettings.writeLPr();
1401                        mDirtyUsers.clear();
1402                    }
1403                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1404                } break;
1405                case WRITE_PACKAGE_RESTRICTIONS: {
1406                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1407                    synchronized (mPackages) {
1408                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1409                        for (int userId : mDirtyUsers) {
1410                            mSettings.writePackageRestrictionsLPr(userId);
1411                        }
1412                        mDirtyUsers.clear();
1413                    }
1414                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1415                } break;
1416                case CHECK_PENDING_VERIFICATION: {
1417                    final int verificationId = msg.arg1;
1418                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1419
1420                    if ((state != null) && !state.timeoutExtended()) {
1421                        final InstallArgs args = state.getInstallArgs();
1422                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1423
1424                        Slog.i(TAG, "Verification timed out for " + originUri);
1425                        mPendingVerification.remove(verificationId);
1426
1427                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1428
1429                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1430                            Slog.i(TAG, "Continuing with installation of " + originUri);
1431                            state.setVerifierResponse(Binder.getCallingUid(),
1432                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1433                            broadcastPackageVerified(verificationId, originUri,
1434                                    PackageManager.VERIFICATION_ALLOW,
1435                                    state.getInstallArgs().getUser());
1436                            try {
1437                                ret = args.copyApk(mContainerService, true);
1438                            } catch (RemoteException e) {
1439                                Slog.e(TAG, "Could not contact the ContainerService");
1440                            }
1441                        } else {
1442                            broadcastPackageVerified(verificationId, originUri,
1443                                    PackageManager.VERIFICATION_REJECT,
1444                                    state.getInstallArgs().getUser());
1445                        }
1446
1447                        processPendingInstall(args, ret);
1448                        mHandler.sendEmptyMessage(MCS_UNBIND);
1449                    }
1450                    break;
1451                }
1452                case PACKAGE_VERIFIED: {
1453                    final int verificationId = msg.arg1;
1454
1455                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1456                    if (state == null) {
1457                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1458                        break;
1459                    }
1460
1461                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1462
1463                    state.setVerifierResponse(response.callerUid, response.code);
1464
1465                    if (state.isVerificationComplete()) {
1466                        mPendingVerification.remove(verificationId);
1467
1468                        final InstallArgs args = state.getInstallArgs();
1469                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1470
1471                        int ret;
1472                        if (state.isInstallAllowed()) {
1473                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1474                            broadcastPackageVerified(verificationId, originUri,
1475                                    response.code, state.getInstallArgs().getUser());
1476                            try {
1477                                ret = args.copyApk(mContainerService, true);
1478                            } catch (RemoteException e) {
1479                                Slog.e(TAG, "Could not contact the ContainerService");
1480                            }
1481                        } else {
1482                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1483                        }
1484
1485                        processPendingInstall(args, ret);
1486
1487                        mHandler.sendEmptyMessage(MCS_UNBIND);
1488                    }
1489
1490                    break;
1491                }
1492                case START_INTENT_FILTER_VERIFICATIONS: {
1493                    int userId = msg.arg1;
1494                    int verifierUid = msg.arg2;
1495                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1496
1497                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1498                    break;
1499                }
1500                case INTENT_FILTER_VERIFIED: {
1501                    final int verificationId = msg.arg1;
1502
1503                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1504                            verificationId);
1505                    if (state == null) {
1506                        Slog.w(TAG, "Invalid IntentFilter verification token "
1507                                + verificationId + " received");
1508                        break;
1509                    }
1510
1511                    final int userId = state.getUserId();
1512
1513                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1514                            + verificationId + " and userId:" + userId);
1515
1516                    final IntentFilterVerificationResponse response =
1517                            (IntentFilterVerificationResponse) msg.obj;
1518
1519                    state.setVerifierResponse(response.callerUid, response.code);
1520
1521                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1522                            + " and userId:" + userId
1523                            + " is settings verifier response with response code:"
1524                            + response.code);
1525
1526                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1527                        Slog.d(TAG, "Domains failing verification: "
1528                                + response.getFailedDomainsString());
1529                    }
1530
1531                    if (state.isVerificationComplete()) {
1532                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1533                    } else {
1534                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1535                                + " was not said to be complete");
1536                    }
1537
1538                    break;
1539                }
1540            }
1541        }
1542    }
1543
1544    private StorageEventListener mStorageListener = new StorageEventListener() {
1545        @Override
1546        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1547            if (vol.type == VolumeInfo.TYPE_PRIVATE) {
1548                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1549                    // TODO: ensure that private directories exist for all active users
1550                    // TODO: remove user data whose serial number doesn't match
1551                    loadPrivatePackages(vol);
1552                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1553                    unloadPrivatePackages(vol);
1554                }
1555            }
1556
1557            if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) {
1558                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1559                    updateExternalMediaStatus(true, false);
1560                } else if (vol.state == VolumeInfo.STATE_EJECTING) {
1561                    updateExternalMediaStatus(false, false);
1562                }
1563            }
1564        }
1565
1566        @Override
1567        public void onVolumeForgotten(String fsUuid) {
1568            // TODO: remove all packages hosted on this uuid
1569        }
1570    };
1571
1572    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1573        if (userId >= UserHandle.USER_OWNER) {
1574            grantRequestedRuntimePermissionsForUser(pkg, userId);
1575        } else if (userId == UserHandle.USER_ALL) {
1576            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1577                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1578            }
1579        }
1580    }
1581
1582    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1583        SettingBase sb = (SettingBase) pkg.mExtras;
1584        if (sb == null) {
1585            return;
1586        }
1587
1588        PermissionsState permissionsState = sb.getPermissionsState();
1589
1590        for (String permission : pkg.requestedPermissions) {
1591            BasePermission bp = mSettings.mPermissions.get(permission);
1592            if (bp != null && bp.isRuntime()) {
1593                permissionsState.grantRuntimePermission(bp, userId);
1594            }
1595        }
1596    }
1597
1598    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1599        Bundle extras = null;
1600        switch (res.returnCode) {
1601            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1602                extras = new Bundle();
1603                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1604                        res.origPermission);
1605                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1606                        res.origPackage);
1607                break;
1608            }
1609            case PackageManager.INSTALL_SUCCEEDED: {
1610                extras = new Bundle();
1611                extras.putBoolean(Intent.EXTRA_REPLACING,
1612                        res.removedInfo != null && res.removedInfo.removedPackage != null);
1613                break;
1614            }
1615        }
1616        return extras;
1617    }
1618
1619    void scheduleWriteSettingsLocked() {
1620        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1621            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1622        }
1623    }
1624
1625    void scheduleWritePackageRestrictionsLocked(int userId) {
1626        if (!sUserManager.exists(userId)) return;
1627        mDirtyUsers.add(userId);
1628        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1629            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1630        }
1631    }
1632
1633    public static PackageManagerService main(Context context, Installer installer,
1634            boolean factoryTest, boolean onlyCore) {
1635        PackageManagerService m = new PackageManagerService(context, installer,
1636                factoryTest, onlyCore);
1637        ServiceManager.addService("package", m);
1638        return m;
1639    }
1640
1641    static String[] splitString(String str, char sep) {
1642        int count = 1;
1643        int i = 0;
1644        while ((i=str.indexOf(sep, i)) >= 0) {
1645            count++;
1646            i++;
1647        }
1648
1649        String[] res = new String[count];
1650        i=0;
1651        count = 0;
1652        int lastI=0;
1653        while ((i=str.indexOf(sep, i)) >= 0) {
1654            res[count] = str.substring(lastI, i);
1655            count++;
1656            i++;
1657            lastI = i;
1658        }
1659        res[count] = str.substring(lastI, str.length());
1660        return res;
1661    }
1662
1663    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1664        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1665                Context.DISPLAY_SERVICE);
1666        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1667    }
1668
1669    public PackageManagerService(Context context, Installer installer,
1670            boolean factoryTest, boolean onlyCore) {
1671        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1672                SystemClock.uptimeMillis());
1673
1674        if (mSdkVersion <= 0) {
1675            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1676        }
1677
1678        mContext = context;
1679        mFactoryTest = factoryTest;
1680        mOnlyCore = onlyCore;
1681        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1682        mMetrics = new DisplayMetrics();
1683        mSettings = new Settings(mPackages);
1684        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1685                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1686        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1687                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1688        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1689                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1690        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1691                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1692        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1693                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1694        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1695                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1696
1697        // TODO: add a property to control this?
1698        long dexOptLRUThresholdInMinutes;
1699        if (mLazyDexOpt) {
1700            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1701        } else {
1702            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1703        }
1704        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1705
1706        String separateProcesses = SystemProperties.get("debug.separate_processes");
1707        if (separateProcesses != null && separateProcesses.length() > 0) {
1708            if ("*".equals(separateProcesses)) {
1709                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1710                mSeparateProcesses = null;
1711                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1712            } else {
1713                mDefParseFlags = 0;
1714                mSeparateProcesses = separateProcesses.split(",");
1715                Slog.w(TAG, "Running with debug.separate_processes: "
1716                        + separateProcesses);
1717            }
1718        } else {
1719            mDefParseFlags = 0;
1720            mSeparateProcesses = null;
1721        }
1722
1723        mInstaller = installer;
1724        mPackageDexOptimizer = new PackageDexOptimizer(this);
1725        mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper());
1726
1727        getDefaultDisplayMetrics(context, mMetrics);
1728
1729        SystemConfig systemConfig = SystemConfig.getInstance();
1730        mGlobalGids = systemConfig.getGlobalGids();
1731        mSystemPermissions = systemConfig.getSystemPermissions();
1732        mAvailableFeatures = systemConfig.getAvailableFeatures();
1733
1734        synchronized (mInstallLock) {
1735        // writer
1736        synchronized (mPackages) {
1737            mHandlerThread = new ServiceThread(TAG,
1738                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1739            mHandlerThread.start();
1740            mHandler = new PackageHandler(mHandlerThread.getLooper());
1741            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1742
1743            File dataDir = Environment.getDataDirectory();
1744            mAppDataDir = new File(dataDir, "data");
1745            mAppInstallDir = new File(dataDir, "app");
1746            mAppLib32InstallDir = new File(dataDir, "app-lib");
1747            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1748            mUserAppDataDir = new File(dataDir, "user");
1749            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1750
1751            sUserManager = new UserManagerService(context, this,
1752                    mInstallLock, mPackages);
1753
1754            // Propagate permission configuration in to package manager.
1755            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1756                    = systemConfig.getPermissions();
1757            for (int i=0; i<permConfig.size(); i++) {
1758                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1759                BasePermission bp = mSettings.mPermissions.get(perm.name);
1760                if (bp == null) {
1761                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1762                    mSettings.mPermissions.put(perm.name, bp);
1763                }
1764                if (perm.gids != null) {
1765                    bp.setGids(perm.gids, perm.perUser);
1766                }
1767            }
1768
1769            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1770            for (int i=0; i<libConfig.size(); i++) {
1771                mSharedLibraries.put(libConfig.keyAt(i),
1772                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1773            }
1774
1775            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1776
1777            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1778                    mSdkVersion, mOnlyCore);
1779
1780            String customResolverActivity = Resources.getSystem().getString(
1781                    R.string.config_customResolverActivity);
1782            if (TextUtils.isEmpty(customResolverActivity)) {
1783                customResolverActivity = null;
1784            } else {
1785                mCustomResolverComponentName = ComponentName.unflattenFromString(
1786                        customResolverActivity);
1787            }
1788
1789            long startTime = SystemClock.uptimeMillis();
1790
1791            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1792                    startTime);
1793
1794            // Set flag to monitor and not change apk file paths when
1795            // scanning install directories.
1796            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1797
1798            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1799
1800            /**
1801             * Add everything in the in the boot class path to the
1802             * list of process files because dexopt will have been run
1803             * if necessary during zygote startup.
1804             */
1805            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1806            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1807
1808            if (bootClassPath != null) {
1809                String[] bootClassPathElements = splitString(bootClassPath, ':');
1810                for (String element : bootClassPathElements) {
1811                    alreadyDexOpted.add(element);
1812                }
1813            } else {
1814                Slog.w(TAG, "No BOOTCLASSPATH found!");
1815            }
1816
1817            if (systemServerClassPath != null) {
1818                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1819                for (String element : systemServerClassPathElements) {
1820                    alreadyDexOpted.add(element);
1821                }
1822            } else {
1823                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1824            }
1825
1826            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1827            final String[] dexCodeInstructionSets =
1828                    getDexCodeInstructionSets(
1829                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1830
1831            /**
1832             * Ensure all external libraries have had dexopt run on them.
1833             */
1834            if (mSharedLibraries.size() > 0) {
1835                // NOTE: For now, we're compiling these system "shared libraries"
1836                // (and framework jars) into all available architectures. It's possible
1837                // to compile them only when we come across an app that uses them (there's
1838                // already logic for that in scanPackageLI) but that adds some complexity.
1839                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1840                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1841                        final String lib = libEntry.path;
1842                        if (lib == null) {
1843                            continue;
1844                        }
1845
1846                        try {
1847                            int dexoptNeeded = DexFile.getDexOptNeeded(lib, null, dexCodeInstructionSet, false);
1848                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1849                                alreadyDexOpted.add(lib);
1850                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1851                            }
1852                        } catch (FileNotFoundException e) {
1853                            Slog.w(TAG, "Library not found: " + lib);
1854                        } catch (IOException e) {
1855                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1856                                    + e.getMessage());
1857                        }
1858                    }
1859                }
1860            }
1861
1862            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1863
1864            // Gross hack for now: we know this file doesn't contain any
1865            // code, so don't dexopt it to avoid the resulting log spew.
1866            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1867
1868            // Gross hack for now: we know this file is only part of
1869            // the boot class path for art, so don't dexopt it to
1870            // avoid the resulting log spew.
1871            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1872
1873            /**
1874             * And there are a number of commands implemented in Java, which
1875             * we currently need to do the dexopt on so that they can be
1876             * run from a non-root shell.
1877             */
1878            String[] frameworkFiles = frameworkDir.list();
1879            if (frameworkFiles != null) {
1880                // TODO: We could compile these only for the most preferred ABI. We should
1881                // first double check that the dex files for these commands are not referenced
1882                // by other system apps.
1883                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1884                    for (int i=0; i<frameworkFiles.length; i++) {
1885                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1886                        String path = libPath.getPath();
1887                        // Skip the file if we already did it.
1888                        if (alreadyDexOpted.contains(path)) {
1889                            continue;
1890                        }
1891                        // Skip the file if it is not a type we want to dexopt.
1892                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1893                            continue;
1894                        }
1895                        try {
1896                            int dexoptNeeded = DexFile.getDexOptNeeded(path, null, dexCodeInstructionSet, false);
1897                            if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) {
1898                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet, dexoptNeeded);
1899                            }
1900                        } catch (FileNotFoundException e) {
1901                            Slog.w(TAG, "Jar not found: " + path);
1902                        } catch (IOException e) {
1903                            Slog.w(TAG, "Exception reading jar: " + path, e);
1904                        }
1905                    }
1906                }
1907            }
1908
1909            // Collect vendor overlay packages.
1910            // (Do this before scanning any apps.)
1911            // For security and version matching reason, only consider
1912            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1913            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1914            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1915                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1916
1917            // Find base frameworks (resource packages without code).
1918            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1919                    | PackageParser.PARSE_IS_SYSTEM_DIR
1920                    | PackageParser.PARSE_IS_PRIVILEGED,
1921                    scanFlags | SCAN_NO_DEX, 0);
1922
1923            // Collected privileged system packages.
1924            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1925            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1926                    | PackageParser.PARSE_IS_SYSTEM_DIR
1927                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1928
1929            // Collect ordinary system packages.
1930            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1931            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1932                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1933
1934            // Collect all vendor packages.
1935            File vendorAppDir = new File("/vendor/app");
1936            try {
1937                vendorAppDir = vendorAppDir.getCanonicalFile();
1938            } catch (IOException e) {
1939                // failed to look up canonical path, continue with original one
1940            }
1941            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1942                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1943
1944            // Collect all OEM packages.
1945            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1946            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1947                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1948
1949            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1950            mInstaller.moveFiles();
1951
1952            // Prune any system packages that no longer exist.
1953            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1954            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1955            if (!mOnlyCore) {
1956                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1957                while (psit.hasNext()) {
1958                    PackageSetting ps = psit.next();
1959
1960                    /*
1961                     * If this is not a system app, it can't be a
1962                     * disable system app.
1963                     */
1964                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1965                        continue;
1966                    }
1967
1968                    /*
1969                     * If the package is scanned, it's not erased.
1970                     */
1971                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1972                    if (scannedPkg != null) {
1973                        /*
1974                         * If the system app is both scanned and in the
1975                         * disabled packages list, then it must have been
1976                         * added via OTA. Remove it from the currently
1977                         * scanned package so the previously user-installed
1978                         * application can be scanned.
1979                         */
1980                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1981                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1982                                    + ps.name + "; removing system app.  Last known codePath="
1983                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1984                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1985                                    + scannedPkg.mVersionCode);
1986                            removePackageLI(ps, true);
1987                            expectingBetter.put(ps.name, ps.codePath);
1988                        }
1989
1990                        continue;
1991                    }
1992
1993                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1994                        psit.remove();
1995                        logCriticalInfo(Log.WARN, "System package " + ps.name
1996                                + " no longer exists; wiping its data");
1997                        removeDataDirsLI(null, ps.name);
1998                    } else {
1999                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
2000                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
2001                            possiblyDeletedUpdatedSystemApps.add(ps.name);
2002                        }
2003                    }
2004                }
2005            }
2006
2007            //look for any incomplete package installations
2008            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
2009            //clean up list
2010            for(int i = 0; i < deletePkgsList.size(); i++) {
2011                //clean up here
2012                cleanupInstallFailedPackage(deletePkgsList.get(i));
2013            }
2014            //delete tmp files
2015            deleteTempPackageFiles();
2016
2017            // Remove any shared userIDs that have no associated packages
2018            mSettings.pruneSharedUsersLPw();
2019
2020            if (!mOnlyCore) {
2021                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2022                        SystemClock.uptimeMillis());
2023                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2024
2025                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2026                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2027
2028                /**
2029                 * Remove disable package settings for any updated system
2030                 * apps that were removed via an OTA. If they're not a
2031                 * previously-updated app, remove them completely.
2032                 * Otherwise, just revoke their system-level permissions.
2033                 */
2034                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2035                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2036                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2037
2038                    String msg;
2039                    if (deletedPkg == null) {
2040                        msg = "Updated system package " + deletedAppName
2041                                + " no longer exists; wiping its data";
2042                        removeDataDirsLI(null, deletedAppName);
2043                    } else {
2044                        msg = "Updated system app + " + deletedAppName
2045                                + " no longer present; removing system privileges for "
2046                                + deletedAppName;
2047
2048                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2049
2050                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2051                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2052                    }
2053                    logCriticalInfo(Log.WARN, msg);
2054                }
2055
2056                /**
2057                 * Make sure all system apps that we expected to appear on
2058                 * the userdata partition actually showed up. If they never
2059                 * appeared, crawl back and revive the system version.
2060                 */
2061                for (int i = 0; i < expectingBetter.size(); i++) {
2062                    final String packageName = expectingBetter.keyAt(i);
2063                    if (!mPackages.containsKey(packageName)) {
2064                        final File scanFile = expectingBetter.valueAt(i);
2065
2066                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2067                                + " but never showed up; reverting to system");
2068
2069                        final int reparseFlags;
2070                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2071                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2072                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2073                                    | PackageParser.PARSE_IS_PRIVILEGED;
2074                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2075                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2076                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2077                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2078                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2079                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2080                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2081                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2082                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2083                        } else {
2084                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2085                            continue;
2086                        }
2087
2088                        mSettings.enableSystemPackageLPw(packageName);
2089
2090                        try {
2091                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2092                        } catch (PackageManagerException e) {
2093                            Slog.e(TAG, "Failed to parse original system package: "
2094                                    + e.getMessage());
2095                        }
2096                    }
2097                }
2098            }
2099
2100            // Now that we know all of the shared libraries, update all clients to have
2101            // the correct library paths.
2102            updateAllSharedLibrariesLPw();
2103
2104            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2105                // NOTE: We ignore potential failures here during a system scan (like
2106                // the rest of the commands above) because there's precious little we
2107                // can do about it. A settings error is reported, though.
2108                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2109                        false /* force dexopt */, false /* defer dexopt */);
2110            }
2111
2112            // Now that we know all the packages we are keeping,
2113            // read and update their last usage times.
2114            mPackageUsage.readLP();
2115
2116            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2117                    SystemClock.uptimeMillis());
2118            Slog.i(TAG, "Time to scan packages: "
2119                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2120                    + " seconds");
2121
2122            // If the platform SDK has changed since the last time we booted,
2123            // we need to re-grant app permission to catch any new ones that
2124            // appear.  This is really a hack, and means that apps can in some
2125            // cases get permissions that the user didn't initially explicitly
2126            // allow...  it would be nice to have some better way to handle
2127            // this situation.
2128            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2129                    != mSdkVersion;
2130            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2131                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2132                    + "; regranting permissions for internal storage");
2133            mSettings.mInternalSdkPlatform = mSdkVersion;
2134
2135            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2136                    | (regrantPermissions
2137                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2138                            : 0));
2139
2140            // If this is the first boot, and it is a normal boot, then
2141            // we need to initialize the default preferred apps.
2142            if (!mRestoredSettings && !onlyCore) {
2143                mSettings.readDefaultPreferredAppsLPw(this, 0);
2144            }
2145
2146            // If this is first boot after an OTA, and a normal boot, then
2147            // we need to clear code cache directories.
2148            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2149            if (mIsUpgrade && !onlyCore) {
2150                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2151                for (int i = 0; i < mSettings.mPackages.size(); i++) {
2152                    final PackageSetting ps = mSettings.mPackages.valueAt(i);
2153                    deleteCodeCacheDirsLI(ps.volumeUuid, ps.name);
2154                }
2155                mSettings.mFingerprint = Build.FINGERPRINT;
2156            }
2157
2158            primeDomainVerificationsLPw(false);
2159            checkDefaultBrowser();
2160
2161            // All the changes are done during package scanning.
2162            mSettings.updateInternalDatabaseVersion();
2163
2164            // can downgrade to reader
2165            mSettings.writeLPr();
2166
2167            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2168                    SystemClock.uptimeMillis());
2169
2170            mRequiredVerifierPackage = getRequiredVerifierLPr();
2171
2172            mInstallerService = new PackageInstallerService(context, this);
2173
2174            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2175            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2176                    mIntentFilterVerifierComponent);
2177
2178        } // synchronized (mPackages)
2179        } // synchronized (mInstallLock)
2180
2181        // Now after opening every single application zip, make sure they
2182        // are all flushed.  Not really needed, but keeps things nice and
2183        // tidy.
2184        Runtime.getRuntime().gc();
2185    }
2186
2187    @Override
2188    public boolean isFirstBoot() {
2189        return !mRestoredSettings;
2190    }
2191
2192    @Override
2193    public boolean isOnlyCoreApps() {
2194        return mOnlyCore;
2195    }
2196
2197    @Override
2198    public boolean isUpgrade() {
2199        return mIsUpgrade;
2200    }
2201
2202    private String getRequiredVerifierLPr() {
2203        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2204        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2205                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2206
2207        String requiredVerifier = null;
2208
2209        final int N = receivers.size();
2210        for (int i = 0; i < N; i++) {
2211            final ResolveInfo info = receivers.get(i);
2212
2213            if (info.activityInfo == null) {
2214                continue;
2215            }
2216
2217            final String packageName = info.activityInfo.packageName;
2218
2219            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2220                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2221                continue;
2222            }
2223
2224            if (requiredVerifier != null) {
2225                throw new RuntimeException("There can be only one required verifier");
2226            }
2227
2228            requiredVerifier = packageName;
2229        }
2230
2231        return requiredVerifier;
2232    }
2233
2234    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2235        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2236        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2237                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2238
2239        ComponentName verifierComponentName = null;
2240
2241        int priority = -1000;
2242        final int N = receivers.size();
2243        for (int i = 0; i < N; i++) {
2244            final ResolveInfo info = receivers.get(i);
2245
2246            if (info.activityInfo == null) {
2247                continue;
2248            }
2249
2250            final String packageName = info.activityInfo.packageName;
2251
2252            final PackageSetting ps = mSettings.mPackages.get(packageName);
2253            if (ps == null) {
2254                continue;
2255            }
2256
2257            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2258                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2259                continue;
2260            }
2261
2262            // Select the IntentFilterVerifier with the highest priority
2263            if (priority < info.priority) {
2264                priority = info.priority;
2265                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2266                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2267                        " with priority: " + info.priority);
2268            }
2269        }
2270
2271        return verifierComponentName;
2272    }
2273
2274    private void primeDomainVerificationsLPw(boolean logging) {
2275        Slog.d(TAG, "Start priming domain verifications");
2276        boolean updated = false;
2277        ArraySet<String> allHostsSet = new ArraySet<>();
2278        for (PackageParser.Package pkg : mPackages.values()) {
2279            final String packageName = pkg.packageName;
2280            if (!hasDomainURLs(pkg)) {
2281                if (logging) {
2282                    Slog.d(TAG, "No priming domain verifications for " +
2283                            "package with no domain URLs: " + packageName);
2284                }
2285                continue;
2286            }
2287            if (!pkg.isSystemApp()) {
2288                if (logging) {
2289                    Slog.d(TAG, "No priming domain verifications for a non system package : " +
2290                            packageName);
2291                }
2292                continue;
2293            }
2294            for (PackageParser.Activity a : pkg.activities) {
2295                for (ActivityIntentInfo filter : a.intents) {
2296                    if (hasValidDomains(filter, false)) {
2297                        allHostsSet.addAll(filter.getHostsList());
2298                    }
2299                }
2300            }
2301            if (allHostsSet.size() == 0) {
2302                allHostsSet.add("*");
2303            }
2304            ArrayList<String> allHostsList = new ArrayList<>(allHostsSet);
2305            IntentFilterVerificationInfo ivi =
2306                    mSettings.createIntentFilterVerificationIfNeededLPw(packageName, allHostsList);
2307            if (ivi != null) {
2308                // We will always log this
2309                Slog.d(TAG, "Priming domain verifications for package: " + packageName +
2310                        " with hosts:" + ivi.getDomainsString());
2311                ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
2312                updated = true;
2313            }
2314            else {
2315                if (logging) {
2316                    Slog.d(TAG, "No priming domain verifications for package: " + packageName);
2317                }
2318            }
2319            allHostsSet.clear();
2320        }
2321        if (updated) {
2322            if (logging) {
2323                Slog.d(TAG, "Will need to write primed domain verifications");
2324            }
2325        }
2326        Slog.d(TAG, "End priming domain verifications");
2327    }
2328
2329    private void checkDefaultBrowser() {
2330        final int myUserId = UserHandle.myUserId();
2331        final String packageName = getDefaultBrowserPackageName(myUserId);
2332        PackageInfo info = getPackageInfo(packageName, 0, myUserId);
2333        if (info == null) {
2334            Slog.w(TAG, "Clearing default Browser as its package is no more installed: " +
2335                    packageName);
2336            setDefaultBrowserPackageName(null, myUserId);
2337        }
2338    }
2339
2340    @Override
2341    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2342            throws RemoteException {
2343        try {
2344            return super.onTransact(code, data, reply, flags);
2345        } catch (RuntimeException e) {
2346            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2347                Slog.wtf(TAG, "Package Manager Crash", e);
2348            }
2349            throw e;
2350        }
2351    }
2352
2353    void cleanupInstallFailedPackage(PackageSetting ps) {
2354        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2355
2356        removeDataDirsLI(ps.volumeUuid, ps.name);
2357        if (ps.codePath != null) {
2358            if (ps.codePath.isDirectory()) {
2359                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2360            } else {
2361                ps.codePath.delete();
2362            }
2363        }
2364        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2365            if (ps.resourcePath.isDirectory()) {
2366                FileUtils.deleteContents(ps.resourcePath);
2367            }
2368            ps.resourcePath.delete();
2369        }
2370        mSettings.removePackageLPw(ps.name);
2371    }
2372
2373    static int[] appendInts(int[] cur, int[] add) {
2374        if (add == null) return cur;
2375        if (cur == null) return add;
2376        final int N = add.length;
2377        for (int i=0; i<N; i++) {
2378            cur = appendInt(cur, add[i]);
2379        }
2380        return cur;
2381    }
2382
2383    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2384        if (!sUserManager.exists(userId)) return null;
2385        final PackageSetting ps = (PackageSetting) p.mExtras;
2386        if (ps == null) {
2387            return null;
2388        }
2389
2390        final PermissionsState permissionsState = ps.getPermissionsState();
2391
2392        final int[] gids = permissionsState.computeGids(userId);
2393        final Set<String> permissions = permissionsState.getPermissions(userId);
2394        final PackageUserState state = ps.readUserState(userId);
2395
2396        return PackageParser.generatePackageInfo(p, gids, flags,
2397                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2398    }
2399
2400    @Override
2401    public boolean isPackageFrozen(String packageName) {
2402        synchronized (mPackages) {
2403            final PackageSetting ps = mSettings.mPackages.get(packageName);
2404            if (ps != null) {
2405                return ps.frozen;
2406            }
2407        }
2408        Slog.w(TAG, "Package " + packageName + " is missing; assuming frozen");
2409        return true;
2410    }
2411
2412    @Override
2413    public boolean isPackageAvailable(String packageName, int userId) {
2414        if (!sUserManager.exists(userId)) return false;
2415        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2416        synchronized (mPackages) {
2417            PackageParser.Package p = mPackages.get(packageName);
2418            if (p != null) {
2419                final PackageSetting ps = (PackageSetting) p.mExtras;
2420                if (ps != null) {
2421                    final PackageUserState state = ps.readUserState(userId);
2422                    if (state != null) {
2423                        return PackageParser.isAvailable(state);
2424                    }
2425                }
2426            }
2427        }
2428        return false;
2429    }
2430
2431    @Override
2432    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2433        if (!sUserManager.exists(userId)) return null;
2434        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2435        // reader
2436        synchronized (mPackages) {
2437            PackageParser.Package p = mPackages.get(packageName);
2438            if (DEBUG_PACKAGE_INFO)
2439                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2440            if (p != null) {
2441                return generatePackageInfo(p, flags, userId);
2442            }
2443            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2444                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2445            }
2446        }
2447        return null;
2448    }
2449
2450    @Override
2451    public String[] currentToCanonicalPackageNames(String[] names) {
2452        String[] out = new String[names.length];
2453        // reader
2454        synchronized (mPackages) {
2455            for (int i=names.length-1; i>=0; i--) {
2456                PackageSetting ps = mSettings.mPackages.get(names[i]);
2457                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2458            }
2459        }
2460        return out;
2461    }
2462
2463    @Override
2464    public String[] canonicalToCurrentPackageNames(String[] names) {
2465        String[] out = new String[names.length];
2466        // reader
2467        synchronized (mPackages) {
2468            for (int i=names.length-1; i>=0; i--) {
2469                String cur = mSettings.mRenamedPackages.get(names[i]);
2470                out[i] = cur != null ? cur : names[i];
2471            }
2472        }
2473        return out;
2474    }
2475
2476    @Override
2477    public int getPackageUid(String packageName, int userId) {
2478        if (!sUserManager.exists(userId)) return -1;
2479        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2480
2481        // reader
2482        synchronized (mPackages) {
2483            PackageParser.Package p = mPackages.get(packageName);
2484            if(p != null) {
2485                return UserHandle.getUid(userId, p.applicationInfo.uid);
2486            }
2487            PackageSetting ps = mSettings.mPackages.get(packageName);
2488            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2489                return -1;
2490            }
2491            p = ps.pkg;
2492            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2493        }
2494    }
2495
2496    @Override
2497    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2498        if (!sUserManager.exists(userId)) {
2499            return null;
2500        }
2501
2502        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2503                "getPackageGids");
2504
2505        // reader
2506        synchronized (mPackages) {
2507            PackageParser.Package p = mPackages.get(packageName);
2508            if (DEBUG_PACKAGE_INFO) {
2509                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2510            }
2511            if (p != null) {
2512                PackageSetting ps = (PackageSetting) p.mExtras;
2513                return ps.getPermissionsState().computeGids(userId);
2514            }
2515        }
2516
2517        return null;
2518    }
2519
2520    static PermissionInfo generatePermissionInfo(
2521            BasePermission bp, int flags) {
2522        if (bp.perm != null) {
2523            return PackageParser.generatePermissionInfo(bp.perm, flags);
2524        }
2525        PermissionInfo pi = new PermissionInfo();
2526        pi.name = bp.name;
2527        pi.packageName = bp.sourcePackage;
2528        pi.nonLocalizedLabel = bp.name;
2529        pi.protectionLevel = bp.protectionLevel;
2530        return pi;
2531    }
2532
2533    @Override
2534    public PermissionInfo getPermissionInfo(String name, int flags) {
2535        // reader
2536        synchronized (mPackages) {
2537            final BasePermission p = mSettings.mPermissions.get(name);
2538            if (p != null) {
2539                return generatePermissionInfo(p, flags);
2540            }
2541            return null;
2542        }
2543    }
2544
2545    @Override
2546    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2547        // reader
2548        synchronized (mPackages) {
2549            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2550            for (BasePermission p : mSettings.mPermissions.values()) {
2551                if (group == null) {
2552                    if (p.perm == null || p.perm.info.group == null) {
2553                        out.add(generatePermissionInfo(p, flags));
2554                    }
2555                } else {
2556                    if (p.perm != null && group.equals(p.perm.info.group)) {
2557                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2558                    }
2559                }
2560            }
2561
2562            if (out.size() > 0) {
2563                return out;
2564            }
2565            return mPermissionGroups.containsKey(group) ? out : null;
2566        }
2567    }
2568
2569    @Override
2570    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2571        // reader
2572        synchronized (mPackages) {
2573            return PackageParser.generatePermissionGroupInfo(
2574                    mPermissionGroups.get(name), flags);
2575        }
2576    }
2577
2578    @Override
2579    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2580        // reader
2581        synchronized (mPackages) {
2582            final int N = mPermissionGroups.size();
2583            ArrayList<PermissionGroupInfo> out
2584                    = new ArrayList<PermissionGroupInfo>(N);
2585            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2586                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2587            }
2588            return out;
2589        }
2590    }
2591
2592    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2593            int userId) {
2594        if (!sUserManager.exists(userId)) return null;
2595        PackageSetting ps = mSettings.mPackages.get(packageName);
2596        if (ps != null) {
2597            if (ps.pkg == null) {
2598                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2599                        flags, userId);
2600                if (pInfo != null) {
2601                    return pInfo.applicationInfo;
2602                }
2603                return null;
2604            }
2605            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2606                    ps.readUserState(userId), userId);
2607        }
2608        return null;
2609    }
2610
2611    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2612            int userId) {
2613        if (!sUserManager.exists(userId)) return null;
2614        PackageSetting ps = mSettings.mPackages.get(packageName);
2615        if (ps != null) {
2616            PackageParser.Package pkg = ps.pkg;
2617            if (pkg == null) {
2618                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2619                    return null;
2620                }
2621                // Only data remains, so we aren't worried about code paths
2622                pkg = new PackageParser.Package(packageName);
2623                pkg.applicationInfo.packageName = packageName;
2624                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2625                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2626                pkg.applicationInfo.dataDir = PackageManager.getDataDirForUser(ps.volumeUuid,
2627                        packageName, userId).getAbsolutePath();
2628                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2629                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2630            }
2631            return generatePackageInfo(pkg, flags, userId);
2632        }
2633        return null;
2634    }
2635
2636    @Override
2637    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2638        if (!sUserManager.exists(userId)) return null;
2639        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2640        // writer
2641        synchronized (mPackages) {
2642            PackageParser.Package p = mPackages.get(packageName);
2643            if (DEBUG_PACKAGE_INFO) Log.v(
2644                    TAG, "getApplicationInfo " + packageName
2645                    + ": " + p);
2646            if (p != null) {
2647                PackageSetting ps = mSettings.mPackages.get(packageName);
2648                if (ps == null) return null;
2649                // Note: isEnabledLP() does not apply here - always return info
2650                return PackageParser.generateApplicationInfo(
2651                        p, flags, ps.readUserState(userId), userId);
2652            }
2653            if ("android".equals(packageName)||"system".equals(packageName)) {
2654                return mAndroidApplication;
2655            }
2656            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2657                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2658            }
2659        }
2660        return null;
2661    }
2662
2663    @Override
2664    public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize,
2665            final IPackageDataObserver observer) {
2666        mContext.enforceCallingOrSelfPermission(
2667                android.Manifest.permission.CLEAR_APP_CACHE, null);
2668        // Queue up an async operation since clearing cache may take a little while.
2669        mHandler.post(new Runnable() {
2670            public void run() {
2671                mHandler.removeCallbacks(this);
2672                int retCode = -1;
2673                synchronized (mInstallLock) {
2674                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2675                    if (retCode < 0) {
2676                        Slog.w(TAG, "Couldn't clear application caches");
2677                    }
2678                }
2679                if (observer != null) {
2680                    try {
2681                        observer.onRemoveCompleted(null, (retCode >= 0));
2682                    } catch (RemoteException e) {
2683                        Slog.w(TAG, "RemoveException when invoking call back");
2684                    }
2685                }
2686            }
2687        });
2688    }
2689
2690    @Override
2691    public void freeStorage(final String volumeUuid, final long freeStorageSize,
2692            final IntentSender pi) {
2693        mContext.enforceCallingOrSelfPermission(
2694                android.Manifest.permission.CLEAR_APP_CACHE, null);
2695        // Queue up an async operation since clearing cache may take a little while.
2696        mHandler.post(new Runnable() {
2697            public void run() {
2698                mHandler.removeCallbacks(this);
2699                int retCode = -1;
2700                synchronized (mInstallLock) {
2701                    retCode = mInstaller.freeCache(volumeUuid, freeStorageSize);
2702                    if (retCode < 0) {
2703                        Slog.w(TAG, "Couldn't clear application caches");
2704                    }
2705                }
2706                if(pi != null) {
2707                    try {
2708                        // Callback via pending intent
2709                        int code = (retCode >= 0) ? 1 : 0;
2710                        pi.sendIntent(null, code, null,
2711                                null, null);
2712                    } catch (SendIntentException e1) {
2713                        Slog.i(TAG, "Failed to send pending intent");
2714                    }
2715                }
2716            }
2717        });
2718    }
2719
2720    void freeStorage(String volumeUuid, long freeStorageSize) throws IOException {
2721        synchronized (mInstallLock) {
2722            if (mInstaller.freeCache(volumeUuid, freeStorageSize) < 0) {
2723                throw new IOException("Failed to free enough space");
2724            }
2725        }
2726    }
2727
2728    @Override
2729    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2730        if (!sUserManager.exists(userId)) return null;
2731        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2732        synchronized (mPackages) {
2733            PackageParser.Activity a = mActivities.mActivities.get(component);
2734
2735            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2736            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2737                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2738                if (ps == null) return null;
2739                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2740                        userId);
2741            }
2742            if (mResolveComponentName.equals(component)) {
2743                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2744                        new PackageUserState(), userId);
2745            }
2746        }
2747        return null;
2748    }
2749
2750    @Override
2751    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2752            String resolvedType) {
2753        synchronized (mPackages) {
2754            PackageParser.Activity a = mActivities.mActivities.get(component);
2755            if (a == null) {
2756                return false;
2757            }
2758            for (int i=0; i<a.intents.size(); i++) {
2759                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2760                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2761                    return true;
2762                }
2763            }
2764            return false;
2765        }
2766    }
2767
2768    @Override
2769    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2770        if (!sUserManager.exists(userId)) return null;
2771        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2772        synchronized (mPackages) {
2773            PackageParser.Activity a = mReceivers.mActivities.get(component);
2774            if (DEBUG_PACKAGE_INFO) Log.v(
2775                TAG, "getReceiverInfo " + component + ": " + a);
2776            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2777                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2778                if (ps == null) return null;
2779                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2780                        userId);
2781            }
2782        }
2783        return null;
2784    }
2785
2786    @Override
2787    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2788        if (!sUserManager.exists(userId)) return null;
2789        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2790        synchronized (mPackages) {
2791            PackageParser.Service s = mServices.mServices.get(component);
2792            if (DEBUG_PACKAGE_INFO) Log.v(
2793                TAG, "getServiceInfo " + component + ": " + s);
2794            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2795                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2796                if (ps == null) return null;
2797                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2798                        userId);
2799            }
2800        }
2801        return null;
2802    }
2803
2804    @Override
2805    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2806        if (!sUserManager.exists(userId)) return null;
2807        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2808        synchronized (mPackages) {
2809            PackageParser.Provider p = mProviders.mProviders.get(component);
2810            if (DEBUG_PACKAGE_INFO) Log.v(
2811                TAG, "getProviderInfo " + component + ": " + p);
2812            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2813                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2814                if (ps == null) return null;
2815                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2816                        userId);
2817            }
2818        }
2819        return null;
2820    }
2821
2822    @Override
2823    public String[] getSystemSharedLibraryNames() {
2824        Set<String> libSet;
2825        synchronized (mPackages) {
2826            libSet = mSharedLibraries.keySet();
2827            int size = libSet.size();
2828            if (size > 0) {
2829                String[] libs = new String[size];
2830                libSet.toArray(libs);
2831                return libs;
2832            }
2833        }
2834        return null;
2835    }
2836
2837    /**
2838     * @hide
2839     */
2840    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2841        synchronized (mPackages) {
2842            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2843            if (lib != null && lib.apk != null) {
2844                return mPackages.get(lib.apk);
2845            }
2846        }
2847        return null;
2848    }
2849
2850    @Override
2851    public FeatureInfo[] getSystemAvailableFeatures() {
2852        Collection<FeatureInfo> featSet;
2853        synchronized (mPackages) {
2854            featSet = mAvailableFeatures.values();
2855            int size = featSet.size();
2856            if (size > 0) {
2857                FeatureInfo[] features = new FeatureInfo[size+1];
2858                featSet.toArray(features);
2859                FeatureInfo fi = new FeatureInfo();
2860                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2861                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2862                features[size] = fi;
2863                return features;
2864            }
2865        }
2866        return null;
2867    }
2868
2869    @Override
2870    public boolean hasSystemFeature(String name) {
2871        synchronized (mPackages) {
2872            return mAvailableFeatures.containsKey(name);
2873        }
2874    }
2875
2876    private void checkValidCaller(int uid, int userId) {
2877        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2878            return;
2879
2880        throw new SecurityException("Caller uid=" + uid
2881                + " is not privileged to communicate with user=" + userId);
2882    }
2883
2884    @Override
2885    public int checkPermission(String permName, String pkgName, int userId) {
2886        if (!sUserManager.exists(userId)) {
2887            return PackageManager.PERMISSION_DENIED;
2888        }
2889
2890        synchronized (mPackages) {
2891            final PackageParser.Package p = mPackages.get(pkgName);
2892            if (p != null && p.mExtras != null) {
2893                final PackageSetting ps = (PackageSetting) p.mExtras;
2894                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2895                    return PackageManager.PERMISSION_GRANTED;
2896                }
2897            }
2898        }
2899
2900        return PackageManager.PERMISSION_DENIED;
2901    }
2902
2903    @Override
2904    public int checkUidPermission(String permName, int uid) {
2905        final int userId = UserHandle.getUserId(uid);
2906
2907        if (!sUserManager.exists(userId)) {
2908            return PackageManager.PERMISSION_DENIED;
2909        }
2910
2911        synchronized (mPackages) {
2912            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2913            if (obj != null) {
2914                final SettingBase ps = (SettingBase) obj;
2915                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2916                    return PackageManager.PERMISSION_GRANTED;
2917                }
2918            } else {
2919                ArraySet<String> perms = mSystemPermissions.get(uid);
2920                if (perms != null && perms.contains(permName)) {
2921                    return PackageManager.PERMISSION_GRANTED;
2922                }
2923            }
2924        }
2925
2926        return PackageManager.PERMISSION_DENIED;
2927    }
2928
2929    /**
2930     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2931     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2932     * @param checkShell TODO(yamasani):
2933     * @param message the message to log on security exception
2934     */
2935    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2936            boolean checkShell, String message) {
2937        if (userId < 0) {
2938            throw new IllegalArgumentException("Invalid userId " + userId);
2939        }
2940        if (checkShell) {
2941            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2942        }
2943        if (userId == UserHandle.getUserId(callingUid)) return;
2944        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2945            if (requireFullPermission) {
2946                mContext.enforceCallingOrSelfPermission(
2947                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2948            } else {
2949                try {
2950                    mContext.enforceCallingOrSelfPermission(
2951                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2952                } catch (SecurityException se) {
2953                    mContext.enforceCallingOrSelfPermission(
2954                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2955                }
2956            }
2957        }
2958    }
2959
2960    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2961        if (callingUid == Process.SHELL_UID) {
2962            if (userHandle >= 0
2963                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2964                throw new SecurityException("Shell does not have permission to access user "
2965                        + userHandle);
2966            } else if (userHandle < 0) {
2967                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2968                        + Debug.getCallers(3));
2969            }
2970        }
2971    }
2972
2973    private BasePermission findPermissionTreeLP(String permName) {
2974        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2975            if (permName.startsWith(bp.name) &&
2976                    permName.length() > bp.name.length() &&
2977                    permName.charAt(bp.name.length()) == '.') {
2978                return bp;
2979            }
2980        }
2981        return null;
2982    }
2983
2984    private BasePermission checkPermissionTreeLP(String permName) {
2985        if (permName != null) {
2986            BasePermission bp = findPermissionTreeLP(permName);
2987            if (bp != null) {
2988                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2989                    return bp;
2990                }
2991                throw new SecurityException("Calling uid "
2992                        + Binder.getCallingUid()
2993                        + " is not allowed to add to permission tree "
2994                        + bp.name + " owned by uid " + bp.uid);
2995            }
2996        }
2997        throw new SecurityException("No permission tree found for " + permName);
2998    }
2999
3000    static boolean compareStrings(CharSequence s1, CharSequence s2) {
3001        if (s1 == null) {
3002            return s2 == null;
3003        }
3004        if (s2 == null) {
3005            return false;
3006        }
3007        if (s1.getClass() != s2.getClass()) {
3008            return false;
3009        }
3010        return s1.equals(s2);
3011    }
3012
3013    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
3014        if (pi1.icon != pi2.icon) return false;
3015        if (pi1.logo != pi2.logo) return false;
3016        if (pi1.protectionLevel != pi2.protectionLevel) return false;
3017        if (!compareStrings(pi1.name, pi2.name)) return false;
3018        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
3019        // We'll take care of setting this one.
3020        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
3021        // These are not currently stored in settings.
3022        //if (!compareStrings(pi1.group, pi2.group)) return false;
3023        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
3024        //if (pi1.labelRes != pi2.labelRes) return false;
3025        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
3026        return true;
3027    }
3028
3029    int permissionInfoFootprint(PermissionInfo info) {
3030        int size = info.name.length();
3031        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
3032        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
3033        return size;
3034    }
3035
3036    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
3037        int size = 0;
3038        for (BasePermission perm : mSettings.mPermissions.values()) {
3039            if (perm.uid == tree.uid) {
3040                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
3041            }
3042        }
3043        return size;
3044    }
3045
3046    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
3047        // We calculate the max size of permissions defined by this uid and throw
3048        // if that plus the size of 'info' would exceed our stated maximum.
3049        if (tree.uid != Process.SYSTEM_UID) {
3050            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
3051            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
3052                throw new SecurityException("Permission tree size cap exceeded");
3053            }
3054        }
3055    }
3056
3057    boolean addPermissionLocked(PermissionInfo info, boolean async) {
3058        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
3059            throw new SecurityException("Label must be specified in permission");
3060        }
3061        BasePermission tree = checkPermissionTreeLP(info.name);
3062        BasePermission bp = mSettings.mPermissions.get(info.name);
3063        boolean added = bp == null;
3064        boolean changed = true;
3065        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
3066        if (added) {
3067            enforcePermissionCapLocked(info, tree);
3068            bp = new BasePermission(info.name, tree.sourcePackage,
3069                    BasePermission.TYPE_DYNAMIC);
3070        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
3071            throw new SecurityException(
3072                    "Not allowed to modify non-dynamic permission "
3073                    + info.name);
3074        } else {
3075            if (bp.protectionLevel == fixedLevel
3076                    && bp.perm.owner.equals(tree.perm.owner)
3077                    && bp.uid == tree.uid
3078                    && comparePermissionInfos(bp.perm.info, info)) {
3079                changed = false;
3080            }
3081        }
3082        bp.protectionLevel = fixedLevel;
3083        info = new PermissionInfo(info);
3084        info.protectionLevel = fixedLevel;
3085        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
3086        bp.perm.info.packageName = tree.perm.info.packageName;
3087        bp.uid = tree.uid;
3088        if (added) {
3089            mSettings.mPermissions.put(info.name, bp);
3090        }
3091        if (changed) {
3092            if (!async) {
3093                mSettings.writeLPr();
3094            } else {
3095                scheduleWriteSettingsLocked();
3096            }
3097        }
3098        return added;
3099    }
3100
3101    @Override
3102    public boolean addPermission(PermissionInfo info) {
3103        synchronized (mPackages) {
3104            return addPermissionLocked(info, false);
3105        }
3106    }
3107
3108    @Override
3109    public boolean addPermissionAsync(PermissionInfo info) {
3110        synchronized (mPackages) {
3111            return addPermissionLocked(info, true);
3112        }
3113    }
3114
3115    @Override
3116    public void removePermission(String name) {
3117        synchronized (mPackages) {
3118            checkPermissionTreeLP(name);
3119            BasePermission bp = mSettings.mPermissions.get(name);
3120            if (bp != null) {
3121                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3122                    throw new SecurityException(
3123                            "Not allowed to modify non-dynamic permission "
3124                            + name);
3125                }
3126                mSettings.mPermissions.remove(name);
3127                mSettings.writeLPr();
3128            }
3129        }
3130    }
3131
3132    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3133            BasePermission bp) {
3134        int index = pkg.requestedPermissions.indexOf(bp.name);
3135        if (index == -1) {
3136            throw new SecurityException("Package " + pkg.packageName
3137                    + " has not requested permission " + bp.name);
3138        }
3139        if (!bp.isRuntime()) {
3140            throw new SecurityException("Permission " + bp.name
3141                    + " is not a changeable permission type");
3142        }
3143    }
3144
3145    private static void enforceOnlySystemUpdatesPermissionPolicyFlags(int flagMask, int flagValues) {
3146        if (((flagMask & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0
3147                || (flagValues & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0)
3148                && getCallingUid() != Process.SYSTEM_UID) {
3149            throw new SecurityException("Only the system can modify policy flags");
3150        }
3151    }
3152
3153    @Override
3154    public void grantRuntimePermission(String packageName, String name, int userId) {
3155        if (!sUserManager.exists(userId)) {
3156            return;
3157        }
3158
3159        mContext.enforceCallingOrSelfPermission(
3160                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3161                "grantRuntimePermission");
3162
3163        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3164                "grantRuntimePermission");
3165
3166        boolean gidsChanged = false;
3167        final SettingBase sb;
3168
3169        synchronized (mPackages) {
3170            final PackageParser.Package pkg = mPackages.get(packageName);
3171            if (pkg == null) {
3172                throw new IllegalArgumentException("Unknown package: " + packageName);
3173            }
3174
3175            final BasePermission bp = mSettings.mPermissions.get(name);
3176            if (bp == null) {
3177                throw new IllegalArgumentException("Unknown permission: " + name);
3178            }
3179
3180            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3181
3182            sb = (SettingBase) pkg.mExtras;
3183            if (sb == null) {
3184                throw new IllegalArgumentException("Unknown package: " + packageName);
3185            }
3186
3187            final PermissionsState permissionsState = sb.getPermissionsState();
3188
3189            final int result = permissionsState.grantRuntimePermission(bp, userId);
3190            switch (result) {
3191                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3192                    return;
3193                }
3194
3195                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3196                    gidsChanged = true;
3197                }
3198                break;
3199            }
3200
3201            // Not critical if that is lost - app has to request again.
3202            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3203        }
3204
3205        if (gidsChanged) {
3206            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3207        }
3208    }
3209
3210    @Override
3211    public void revokeRuntimePermission(String packageName, String name, int userId) {
3212        if (!sUserManager.exists(userId)) {
3213            return;
3214        }
3215
3216        mContext.enforceCallingOrSelfPermission(
3217                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3218                "revokeRuntimePermission");
3219
3220        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3221                "revokeRuntimePermission");
3222
3223        final SettingBase sb;
3224
3225        synchronized (mPackages) {
3226            final PackageParser.Package pkg = mPackages.get(packageName);
3227            if (pkg == null) {
3228                throw new IllegalArgumentException("Unknown package: " + packageName);
3229            }
3230
3231            final BasePermission bp = mSettings.mPermissions.get(name);
3232            if (bp == null) {
3233                throw new IllegalArgumentException("Unknown permission: " + name);
3234            }
3235
3236            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3237
3238            sb = (SettingBase) pkg.mExtras;
3239            if (sb == null) {
3240                throw new IllegalArgumentException("Unknown package: " + packageName);
3241            }
3242
3243            final PermissionsState permissionsState = sb.getPermissionsState();
3244
3245            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3246                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3247                return;
3248            }
3249
3250            // Critical, after this call app should never have the permission.
3251            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3252        }
3253
3254        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3255    }
3256
3257    @Override
3258    public int getPermissionFlags(String name, String packageName, int userId) {
3259        if (!sUserManager.exists(userId)) {
3260            return 0;
3261        }
3262
3263        mContext.enforceCallingOrSelfPermission(
3264                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3265                "getPermissionFlags");
3266
3267        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3268                "getPermissionFlags");
3269
3270        synchronized (mPackages) {
3271            final PackageParser.Package pkg = mPackages.get(packageName);
3272            if (pkg == null) {
3273                throw new IllegalArgumentException("Unknown package: " + packageName);
3274            }
3275
3276            final BasePermission bp = mSettings.mPermissions.get(name);
3277            if (bp == null) {
3278                throw new IllegalArgumentException("Unknown permission: " + name);
3279            }
3280
3281            SettingBase sb = (SettingBase) pkg.mExtras;
3282            if (sb == null) {
3283                throw new IllegalArgumentException("Unknown package: " + packageName);
3284            }
3285
3286            PermissionsState permissionsState = sb.getPermissionsState();
3287            return permissionsState.getPermissionFlags(name, userId);
3288        }
3289    }
3290
3291    @Override
3292    public void updatePermissionFlags(String name, String packageName, int flagMask,
3293            int flagValues, int userId) {
3294        if (!sUserManager.exists(userId)) {
3295            return;
3296        }
3297
3298        mContext.enforceCallingOrSelfPermission(
3299                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3300                "updatePermissionFlags");
3301
3302        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3303                "updatePermissionFlags");
3304
3305        enforceOnlySystemUpdatesPermissionPolicyFlags(flagMask, flagValues);
3306
3307        synchronized (mPackages) {
3308            final PackageParser.Package pkg = mPackages.get(packageName);
3309            if (pkg == null) {
3310                throw new IllegalArgumentException("Unknown package: " + packageName);
3311            }
3312
3313            final BasePermission bp = mSettings.mPermissions.get(name);
3314            if (bp == null) {
3315                throw new IllegalArgumentException("Unknown permission: " + name);
3316            }
3317
3318            SettingBase sb = (SettingBase) pkg.mExtras;
3319            if (sb == null) {
3320                throw new IllegalArgumentException("Unknown package: " + packageName);
3321            }
3322
3323            PermissionsState permissionsState = sb.getPermissionsState();
3324
3325            if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) {
3326                // Install and runtime permissions are stored in different places,
3327                // so figure out what permission changed and persist the change.
3328                if (permissionsState.getInstallPermissionState(name) != null) {
3329                    scheduleWriteSettingsLocked();
3330                } else if (permissionsState.getRuntimePermissionState(name, userId) != null) {
3331                    mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3332                }
3333            }
3334        }
3335    }
3336
3337    @Override
3338    public boolean isProtectedBroadcast(String actionName) {
3339        synchronized (mPackages) {
3340            return mProtectedBroadcasts.contains(actionName);
3341        }
3342    }
3343
3344    @Override
3345    public int checkSignatures(String pkg1, String pkg2) {
3346        synchronized (mPackages) {
3347            final PackageParser.Package p1 = mPackages.get(pkg1);
3348            final PackageParser.Package p2 = mPackages.get(pkg2);
3349            if (p1 == null || p1.mExtras == null
3350                    || p2 == null || p2.mExtras == null) {
3351                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3352            }
3353            return compareSignatures(p1.mSignatures, p2.mSignatures);
3354        }
3355    }
3356
3357    @Override
3358    public int checkUidSignatures(int uid1, int uid2) {
3359        // Map to base uids.
3360        uid1 = UserHandle.getAppId(uid1);
3361        uid2 = UserHandle.getAppId(uid2);
3362        // reader
3363        synchronized (mPackages) {
3364            Signature[] s1;
3365            Signature[] s2;
3366            Object obj = mSettings.getUserIdLPr(uid1);
3367            if (obj != null) {
3368                if (obj instanceof SharedUserSetting) {
3369                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3370                } else if (obj instanceof PackageSetting) {
3371                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3372                } else {
3373                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3374                }
3375            } else {
3376                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3377            }
3378            obj = mSettings.getUserIdLPr(uid2);
3379            if (obj != null) {
3380                if (obj instanceof SharedUserSetting) {
3381                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3382                } else if (obj instanceof PackageSetting) {
3383                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3384                } else {
3385                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3386                }
3387            } else {
3388                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3389            }
3390            return compareSignatures(s1, s2);
3391        }
3392    }
3393
3394    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3395        final long identity = Binder.clearCallingIdentity();
3396        try {
3397            if (sb instanceof SharedUserSetting) {
3398                SharedUserSetting sus = (SharedUserSetting) sb;
3399                final int packageCount = sus.packages.size();
3400                for (int i = 0; i < packageCount; i++) {
3401                    PackageSetting susPs = sus.packages.valueAt(i);
3402                    if (userId == UserHandle.USER_ALL) {
3403                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3404                    } else {
3405                        final int uid = UserHandle.getUid(userId, susPs.appId);
3406                        killUid(uid, reason);
3407                    }
3408                }
3409            } else if (sb instanceof PackageSetting) {
3410                PackageSetting ps = (PackageSetting) sb;
3411                if (userId == UserHandle.USER_ALL) {
3412                    killApplication(ps.pkg.packageName, ps.appId, reason);
3413                } else {
3414                    final int uid = UserHandle.getUid(userId, ps.appId);
3415                    killUid(uid, reason);
3416                }
3417            }
3418        } finally {
3419            Binder.restoreCallingIdentity(identity);
3420        }
3421    }
3422
3423    private static void killUid(int uid, String reason) {
3424        IActivityManager am = ActivityManagerNative.getDefault();
3425        if (am != null) {
3426            try {
3427                am.killUid(uid, reason);
3428            } catch (RemoteException e) {
3429                /* ignore - same process */
3430            }
3431        }
3432    }
3433
3434    /**
3435     * Compares two sets of signatures. Returns:
3436     * <br />
3437     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3438     * <br />
3439     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3440     * <br />
3441     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3442     * <br />
3443     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3444     * <br />
3445     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3446     */
3447    static int compareSignatures(Signature[] s1, Signature[] s2) {
3448        if (s1 == null) {
3449            return s2 == null
3450                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3451                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3452        }
3453
3454        if (s2 == null) {
3455            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3456        }
3457
3458        if (s1.length != s2.length) {
3459            return PackageManager.SIGNATURE_NO_MATCH;
3460        }
3461
3462        // Since both signature sets are of size 1, we can compare without HashSets.
3463        if (s1.length == 1) {
3464            return s1[0].equals(s2[0]) ?
3465                    PackageManager.SIGNATURE_MATCH :
3466                    PackageManager.SIGNATURE_NO_MATCH;
3467        }
3468
3469        ArraySet<Signature> set1 = new ArraySet<Signature>();
3470        for (Signature sig : s1) {
3471            set1.add(sig);
3472        }
3473        ArraySet<Signature> set2 = new ArraySet<Signature>();
3474        for (Signature sig : s2) {
3475            set2.add(sig);
3476        }
3477        // Make sure s2 contains all signatures in s1.
3478        if (set1.equals(set2)) {
3479            return PackageManager.SIGNATURE_MATCH;
3480        }
3481        return PackageManager.SIGNATURE_NO_MATCH;
3482    }
3483
3484    /**
3485     * If the database version for this type of package (internal storage or
3486     * external storage) is less than the version where package signatures
3487     * were updated, return true.
3488     */
3489    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3490        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3491                DatabaseVersion.SIGNATURE_END_ENTITY))
3492                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3493                        DatabaseVersion.SIGNATURE_END_ENTITY));
3494    }
3495
3496    /**
3497     * Used for backward compatibility to make sure any packages with
3498     * certificate chains get upgraded to the new style. {@code existingSigs}
3499     * will be in the old format (since they were stored on disk from before the
3500     * system upgrade) and {@code scannedSigs} will be in the newer format.
3501     */
3502    private int compareSignaturesCompat(PackageSignatures existingSigs,
3503            PackageParser.Package scannedPkg) {
3504        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3505            return PackageManager.SIGNATURE_NO_MATCH;
3506        }
3507
3508        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3509        for (Signature sig : existingSigs.mSignatures) {
3510            existingSet.add(sig);
3511        }
3512        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3513        for (Signature sig : scannedPkg.mSignatures) {
3514            try {
3515                Signature[] chainSignatures = sig.getChainSignatures();
3516                for (Signature chainSig : chainSignatures) {
3517                    scannedCompatSet.add(chainSig);
3518                }
3519            } catch (CertificateEncodingException e) {
3520                scannedCompatSet.add(sig);
3521            }
3522        }
3523        /*
3524         * Make sure the expanded scanned set contains all signatures in the
3525         * existing one.
3526         */
3527        if (scannedCompatSet.equals(existingSet)) {
3528            // Migrate the old signatures to the new scheme.
3529            existingSigs.assignSignatures(scannedPkg.mSignatures);
3530            // The new KeySets will be re-added later in the scanning process.
3531            synchronized (mPackages) {
3532                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3533            }
3534            return PackageManager.SIGNATURE_MATCH;
3535        }
3536        return PackageManager.SIGNATURE_NO_MATCH;
3537    }
3538
3539    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3540        if (isExternal(scannedPkg)) {
3541            return mSettings.isExternalDatabaseVersionOlderThan(
3542                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3543        } else {
3544            return mSettings.isInternalDatabaseVersionOlderThan(
3545                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3546        }
3547    }
3548
3549    private int compareSignaturesRecover(PackageSignatures existingSigs,
3550            PackageParser.Package scannedPkg) {
3551        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3552            return PackageManager.SIGNATURE_NO_MATCH;
3553        }
3554
3555        String msg = null;
3556        try {
3557            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3558                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3559                        + scannedPkg.packageName);
3560                return PackageManager.SIGNATURE_MATCH;
3561            }
3562        } catch (CertificateException e) {
3563            msg = e.getMessage();
3564        }
3565
3566        logCriticalInfo(Log.INFO,
3567                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3568        return PackageManager.SIGNATURE_NO_MATCH;
3569    }
3570
3571    @Override
3572    public String[] getPackagesForUid(int uid) {
3573        uid = UserHandle.getAppId(uid);
3574        // reader
3575        synchronized (mPackages) {
3576            Object obj = mSettings.getUserIdLPr(uid);
3577            if (obj instanceof SharedUserSetting) {
3578                final SharedUserSetting sus = (SharedUserSetting) obj;
3579                final int N = sus.packages.size();
3580                final String[] res = new String[N];
3581                final Iterator<PackageSetting> it = sus.packages.iterator();
3582                int i = 0;
3583                while (it.hasNext()) {
3584                    res[i++] = it.next().name;
3585                }
3586                return res;
3587            } else if (obj instanceof PackageSetting) {
3588                final PackageSetting ps = (PackageSetting) obj;
3589                return new String[] { ps.name };
3590            }
3591        }
3592        return null;
3593    }
3594
3595    @Override
3596    public String getNameForUid(int uid) {
3597        // reader
3598        synchronized (mPackages) {
3599            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3600            if (obj instanceof SharedUserSetting) {
3601                final SharedUserSetting sus = (SharedUserSetting) obj;
3602                return sus.name + ":" + sus.userId;
3603            } else if (obj instanceof PackageSetting) {
3604                final PackageSetting ps = (PackageSetting) obj;
3605                return ps.name;
3606            }
3607        }
3608        return null;
3609    }
3610
3611    @Override
3612    public int getUidForSharedUser(String sharedUserName) {
3613        if(sharedUserName == null) {
3614            return -1;
3615        }
3616        // reader
3617        synchronized (mPackages) {
3618            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3619            if (suid == null) {
3620                return -1;
3621            }
3622            return suid.userId;
3623        }
3624    }
3625
3626    @Override
3627    public int getFlagsForUid(int uid) {
3628        synchronized (mPackages) {
3629            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3630            if (obj instanceof SharedUserSetting) {
3631                final SharedUserSetting sus = (SharedUserSetting) obj;
3632                return sus.pkgFlags;
3633            } else if (obj instanceof PackageSetting) {
3634                final PackageSetting ps = (PackageSetting) obj;
3635                return ps.pkgFlags;
3636            }
3637        }
3638        return 0;
3639    }
3640
3641    @Override
3642    public int getPrivateFlagsForUid(int uid) {
3643        synchronized (mPackages) {
3644            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3645            if (obj instanceof SharedUserSetting) {
3646                final SharedUserSetting sus = (SharedUserSetting) obj;
3647                return sus.pkgPrivateFlags;
3648            } else if (obj instanceof PackageSetting) {
3649                final PackageSetting ps = (PackageSetting) obj;
3650                return ps.pkgPrivateFlags;
3651            }
3652        }
3653        return 0;
3654    }
3655
3656    @Override
3657    public boolean isUidPrivileged(int uid) {
3658        uid = UserHandle.getAppId(uid);
3659        // reader
3660        synchronized (mPackages) {
3661            Object obj = mSettings.getUserIdLPr(uid);
3662            if (obj instanceof SharedUserSetting) {
3663                final SharedUserSetting sus = (SharedUserSetting) obj;
3664                final Iterator<PackageSetting> it = sus.packages.iterator();
3665                while (it.hasNext()) {
3666                    if (it.next().isPrivileged()) {
3667                        return true;
3668                    }
3669                }
3670            } else if (obj instanceof PackageSetting) {
3671                final PackageSetting ps = (PackageSetting) obj;
3672                return ps.isPrivileged();
3673            }
3674        }
3675        return false;
3676    }
3677
3678    @Override
3679    public String[] getAppOpPermissionPackages(String permissionName) {
3680        synchronized (mPackages) {
3681            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3682            if (pkgs == null) {
3683                return null;
3684            }
3685            return pkgs.toArray(new String[pkgs.size()]);
3686        }
3687    }
3688
3689    @Override
3690    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3691            int flags, int userId) {
3692        if (!sUserManager.exists(userId)) return null;
3693        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3694        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3695        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3696    }
3697
3698    @Override
3699    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3700            IntentFilter filter, int match, ComponentName activity) {
3701        final int userId = UserHandle.getCallingUserId();
3702        if (DEBUG_PREFERRED) {
3703            Log.v(TAG, "setLastChosenActivity intent=" + intent
3704                + " resolvedType=" + resolvedType
3705                + " flags=" + flags
3706                + " filter=" + filter
3707                + " match=" + match
3708                + " activity=" + activity);
3709            filter.dump(new PrintStreamPrinter(System.out), "    ");
3710        }
3711        intent.setComponent(null);
3712        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3713        // Find any earlier preferred or last chosen entries and nuke them
3714        findPreferredActivity(intent, resolvedType,
3715                flags, query, 0, false, true, false, userId);
3716        // Add the new activity as the last chosen for this filter
3717        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3718                "Setting last chosen");
3719    }
3720
3721    @Override
3722    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3723        final int userId = UserHandle.getCallingUserId();
3724        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3725        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3726        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3727                false, false, false, userId);
3728    }
3729
3730    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3731            int flags, List<ResolveInfo> query, int userId) {
3732        if (query != null) {
3733            final int N = query.size();
3734            if (N == 1) {
3735                return query.get(0);
3736            } else if (N > 1) {
3737                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3738                // If there is more than one activity with the same priority,
3739                // then let the user decide between them.
3740                ResolveInfo r0 = query.get(0);
3741                ResolveInfo r1 = query.get(1);
3742                if (DEBUG_INTENT_MATCHING || debug) {
3743                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3744                            + r1.activityInfo.name + "=" + r1.priority);
3745                }
3746                // If the first activity has a higher priority, or a different
3747                // default, then it is always desireable to pick it.
3748                if (r0.priority != r1.priority
3749                        || r0.preferredOrder != r1.preferredOrder
3750                        || r0.isDefault != r1.isDefault) {
3751                    return query.get(0);
3752                }
3753                // If we have saved a preference for a preferred activity for
3754                // this Intent, use that.
3755                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3756                        flags, query, r0.priority, true, false, debug, userId);
3757                if (ri != null) {
3758                    return ri;
3759                }
3760                if (userId != 0) {
3761                    ri = new ResolveInfo(mResolveInfo);
3762                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3763                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3764                            ri.activityInfo.applicationInfo);
3765                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3766                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3767                    return ri;
3768                }
3769                return mResolveInfo;
3770            }
3771        }
3772        return null;
3773    }
3774
3775    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3776            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3777        final int N = query.size();
3778        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3779                .get(userId);
3780        // Get the list of persistent preferred activities that handle the intent
3781        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3782        List<PersistentPreferredActivity> pprefs = ppir != null
3783                ? ppir.queryIntent(intent, resolvedType,
3784                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3785                : null;
3786        if (pprefs != null && pprefs.size() > 0) {
3787            final int M = pprefs.size();
3788            for (int i=0; i<M; i++) {
3789                final PersistentPreferredActivity ppa = pprefs.get(i);
3790                if (DEBUG_PREFERRED || debug) {
3791                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3792                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3793                            + "\n  component=" + ppa.mComponent);
3794                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3795                }
3796                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3797                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3798                if (DEBUG_PREFERRED || debug) {
3799                    Slog.v(TAG, "Found persistent preferred activity:");
3800                    if (ai != null) {
3801                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3802                    } else {
3803                        Slog.v(TAG, "  null");
3804                    }
3805                }
3806                if (ai == null) {
3807                    // This previously registered persistent preferred activity
3808                    // component is no longer known. Ignore it and do NOT remove it.
3809                    continue;
3810                }
3811                for (int j=0; j<N; j++) {
3812                    final ResolveInfo ri = query.get(j);
3813                    if (!ri.activityInfo.applicationInfo.packageName
3814                            .equals(ai.applicationInfo.packageName)) {
3815                        continue;
3816                    }
3817                    if (!ri.activityInfo.name.equals(ai.name)) {
3818                        continue;
3819                    }
3820                    //  Found a persistent preference that can handle the intent.
3821                    if (DEBUG_PREFERRED || debug) {
3822                        Slog.v(TAG, "Returning persistent preferred activity: " +
3823                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3824                    }
3825                    return ri;
3826                }
3827            }
3828        }
3829        return null;
3830    }
3831
3832    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3833            List<ResolveInfo> query, int priority, boolean always,
3834            boolean removeMatches, boolean debug, int userId) {
3835        if (!sUserManager.exists(userId)) return null;
3836        // writer
3837        synchronized (mPackages) {
3838            if (intent.getSelector() != null) {
3839                intent = intent.getSelector();
3840            }
3841            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3842
3843            // Try to find a matching persistent preferred activity.
3844            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3845                    debug, userId);
3846
3847            // If a persistent preferred activity matched, use it.
3848            if (pri != null) {
3849                return pri;
3850            }
3851
3852            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3853            // Get the list of preferred activities that handle the intent
3854            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3855            List<PreferredActivity> prefs = pir != null
3856                    ? pir.queryIntent(intent, resolvedType,
3857                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3858                    : null;
3859            if (prefs != null && prefs.size() > 0) {
3860                boolean changed = false;
3861                try {
3862                    // First figure out how good the original match set is.
3863                    // We will only allow preferred activities that came
3864                    // from the same match quality.
3865                    int match = 0;
3866
3867                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3868
3869                    final int N = query.size();
3870                    for (int j=0; j<N; j++) {
3871                        final ResolveInfo ri = query.get(j);
3872                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3873                                + ": 0x" + Integer.toHexString(match));
3874                        if (ri.match > match) {
3875                            match = ri.match;
3876                        }
3877                    }
3878
3879                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3880                            + Integer.toHexString(match));
3881
3882                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3883                    final int M = prefs.size();
3884                    for (int i=0; i<M; i++) {
3885                        final PreferredActivity pa = prefs.get(i);
3886                        if (DEBUG_PREFERRED || debug) {
3887                            Slog.v(TAG, "Checking PreferredActivity ds="
3888                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3889                                    + "\n  component=" + pa.mPref.mComponent);
3890                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3891                        }
3892                        if (pa.mPref.mMatch != match) {
3893                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3894                                    + Integer.toHexString(pa.mPref.mMatch));
3895                            continue;
3896                        }
3897                        // If it's not an "always" type preferred activity and that's what we're
3898                        // looking for, skip it.
3899                        if (always && !pa.mPref.mAlways) {
3900                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3901                            continue;
3902                        }
3903                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3904                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3905                        if (DEBUG_PREFERRED || debug) {
3906                            Slog.v(TAG, "Found preferred activity:");
3907                            if (ai != null) {
3908                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3909                            } else {
3910                                Slog.v(TAG, "  null");
3911                            }
3912                        }
3913                        if (ai == null) {
3914                            // This previously registered preferred activity
3915                            // component is no longer known.  Most likely an update
3916                            // to the app was installed and in the new version this
3917                            // component no longer exists.  Clean it up by removing
3918                            // it from the preferred activities list, and skip it.
3919                            Slog.w(TAG, "Removing dangling preferred activity: "
3920                                    + pa.mPref.mComponent);
3921                            pir.removeFilter(pa);
3922                            changed = true;
3923                            continue;
3924                        }
3925                        for (int j=0; j<N; j++) {
3926                            final ResolveInfo ri = query.get(j);
3927                            if (!ri.activityInfo.applicationInfo.packageName
3928                                    .equals(ai.applicationInfo.packageName)) {
3929                                continue;
3930                            }
3931                            if (!ri.activityInfo.name.equals(ai.name)) {
3932                                continue;
3933                            }
3934
3935                            if (removeMatches) {
3936                                pir.removeFilter(pa);
3937                                changed = true;
3938                                if (DEBUG_PREFERRED) {
3939                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3940                                }
3941                                break;
3942                            }
3943
3944                            // Okay we found a previously set preferred or last chosen app.
3945                            // If the result set is different from when this
3946                            // was created, we need to clear it and re-ask the
3947                            // user their preference, if we're looking for an "always" type entry.
3948                            if (always && !pa.mPref.sameSet(query)) {
3949                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3950                                        + intent + " type " + resolvedType);
3951                                if (DEBUG_PREFERRED) {
3952                                    Slog.v(TAG, "Removing preferred activity since set changed "
3953                                            + pa.mPref.mComponent);
3954                                }
3955                                pir.removeFilter(pa);
3956                                // Re-add the filter as a "last chosen" entry (!always)
3957                                PreferredActivity lastChosen = new PreferredActivity(
3958                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3959                                pir.addFilter(lastChosen);
3960                                changed = true;
3961                                return null;
3962                            }
3963
3964                            // Yay! Either the set matched or we're looking for the last chosen
3965                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3966                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3967                            return ri;
3968                        }
3969                    }
3970                } finally {
3971                    if (changed) {
3972                        if (DEBUG_PREFERRED) {
3973                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3974                        }
3975                        scheduleWritePackageRestrictionsLocked(userId);
3976                    }
3977                }
3978            }
3979        }
3980        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3981        return null;
3982    }
3983
3984    /*
3985     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3986     */
3987    @Override
3988    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3989            int targetUserId) {
3990        mContext.enforceCallingOrSelfPermission(
3991                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3992        List<CrossProfileIntentFilter> matches =
3993                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3994        if (matches != null) {
3995            int size = matches.size();
3996            for (int i = 0; i < size; i++) {
3997                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3998            }
3999        }
4000        return false;
4001    }
4002
4003    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
4004            String resolvedType, int userId) {
4005        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
4006        if (resolver != null) {
4007            return resolver.queryIntent(intent, resolvedType, false, userId);
4008        }
4009        return null;
4010    }
4011
4012    @Override
4013    public List<ResolveInfo> queryIntentActivities(Intent intent,
4014            String resolvedType, int flags, int userId) {
4015        if (!sUserManager.exists(userId)) return Collections.emptyList();
4016        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
4017        ComponentName comp = intent.getComponent();
4018        if (comp == null) {
4019            if (intent.getSelector() != null) {
4020                intent = intent.getSelector();
4021                comp = intent.getComponent();
4022            }
4023        }
4024
4025        if (comp != null) {
4026            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4027            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
4028            if (ai != null) {
4029                final ResolveInfo ri = new ResolveInfo();
4030                ri.activityInfo = ai;
4031                list.add(ri);
4032            }
4033            return list;
4034        }
4035
4036        // reader
4037        synchronized (mPackages) {
4038            final String pkgName = intent.getPackage();
4039            if (pkgName == null) {
4040                List<CrossProfileIntentFilter> matchingFilters =
4041                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
4042                // Check for results that need to skip the current profile.
4043                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
4044                        resolvedType, flags, userId);
4045                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4046                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
4047                    result.add(resolveInfo);
4048                    return filterIfNotPrimaryUser(result, userId);
4049                }
4050
4051                // Check for results in the current profile.
4052                List<ResolveInfo> result = mActivities.queryIntent(
4053                        intent, resolvedType, flags, userId);
4054
4055                // Check for cross profile results.
4056                resolveInfo = queryCrossProfileIntents(
4057                        matchingFilters, intent, resolvedType, flags, userId);
4058                if (resolveInfo != null && isUserEnabled(resolveInfo.targetUserId)) {
4059                    result.add(resolveInfo);
4060                    Collections.sort(result, mResolvePrioritySorter);
4061                }
4062                result = filterIfNotPrimaryUser(result, userId);
4063                if (result.size() > 1 && hasWebURI(intent)) {
4064                    return filterCandidatesWithDomainPreferedActivitiesLPr(flags, result);
4065                }
4066                return result;
4067            }
4068            final PackageParser.Package pkg = mPackages.get(pkgName);
4069            if (pkg != null) {
4070                return filterIfNotPrimaryUser(
4071                        mActivities.queryIntentForPackage(
4072                                intent, resolvedType, flags, pkg.activities, userId),
4073                        userId);
4074            }
4075            return new ArrayList<ResolveInfo>();
4076        }
4077    }
4078
4079    private boolean isUserEnabled(int userId) {
4080        long callingId = Binder.clearCallingIdentity();
4081        try {
4082            UserInfo userInfo = sUserManager.getUserInfo(userId);
4083            return userInfo != null && userInfo.isEnabled();
4084        } finally {
4085            Binder.restoreCallingIdentity(callingId);
4086        }
4087    }
4088
4089    /**
4090     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
4091     *
4092     * @return filtered list
4093     */
4094    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
4095        if (userId == UserHandle.USER_OWNER) {
4096            return resolveInfos;
4097        }
4098        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
4099            ResolveInfo info = resolveInfos.get(i);
4100            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
4101                resolveInfos.remove(i);
4102            }
4103        }
4104        return resolveInfos;
4105    }
4106
4107    private static boolean hasWebURI(Intent intent) {
4108        if (intent.getData() == null) {
4109            return false;
4110        }
4111        final String scheme = intent.getScheme();
4112        if (TextUtils.isEmpty(scheme)) {
4113            return false;
4114        }
4115        return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS);
4116    }
4117
4118    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPr(
4119            int flags, List<ResolveInfo> candidates) {
4120        if (DEBUG_PREFERRED) {
4121            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
4122                    candidates.size());
4123        }
4124
4125        final int userId = UserHandle.getCallingUserId();
4126        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>();
4127        ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>();
4128        ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>();
4129        ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>();
4130
4131        synchronized (mPackages) {
4132            final int count = candidates.size();
4133            // First, try to use the domain prefered App. Partition the candidates into four lists:
4134            // one for the final results, one for the "do not use ever", one for "undefined status"
4135            // and finally one for "Browser App type".
4136            for (int n=0; n<count; n++) {
4137                ResolveInfo info = candidates.get(n);
4138                String packageName = info.activityInfo.packageName;
4139                PackageSetting ps = mSettings.mPackages.get(packageName);
4140                if (ps != null) {
4141                    // Add to the special match all list (Browser use case)
4142                    if (info.handleAllWebDataURI) {
4143                        matchAllList.add(info);
4144                        continue;
4145                    }
4146                    // Try to get the status from User settings first
4147                    int status = getDomainVerificationStatusLPr(ps, userId);
4148                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
4149                        result.add(info);
4150                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
4151                        neverList.add(info);
4152                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4153                        undefinedList.add(info);
4154                    }
4155                }
4156            }
4157            // Add all undefined Apps as we want them to appear in the Disambiguation dialog.
4158            result.addAll(undefinedList);
4159            // If there is nothing selected, add all candidates and remove the ones that the User
4160            // has explicitely put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state and
4161            // also remove Browser Apps ones.
4162            // If there is still none after this pass, add all Browser Apps and
4163            // let the User decide with the Disambiguation dialog if there are several ones.
4164            if (result.size() == 0) {
4165                result.addAll(candidates);
4166            }
4167            result.removeAll(neverList);
4168            result.removeAll(matchAllList);
4169            if (result.size() == 0) {
4170                if ((flags & MATCH_ALL) != 0) {
4171                    result.addAll(matchAllList);
4172                } else {
4173                    // Try to add the Default Browser if we can
4174                    final String defaultBrowserPackageName = getDefaultBrowserPackageName(
4175                            UserHandle.myUserId());
4176                    if (!TextUtils.isEmpty(defaultBrowserPackageName)) {
4177                        boolean defaultBrowserFound = false;
4178                        final int browserCount = matchAllList.size();
4179                        for (int n=0; n<browserCount; n++) {
4180                            ResolveInfo browser = matchAllList.get(n);
4181                            if (browser.activityInfo.packageName.equals(defaultBrowserPackageName)) {
4182                                result.add(browser);
4183                                defaultBrowserFound = true;
4184                                break;
4185                            }
4186                        }
4187                        if (!defaultBrowserFound) {
4188                            result.addAll(matchAllList);
4189                        }
4190                    } else {
4191                        result.addAll(matchAllList);
4192                    }
4193                }
4194            }
4195        }
4196        if (DEBUG_PREFERRED) {
4197            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
4198                    result.size());
4199        }
4200        return result;
4201    }
4202
4203    private int getDomainVerificationStatusLPr(PackageSetting ps, int userId) {
4204        int status = ps.getDomainVerificationStatusForUser(userId);
4205        // if none available, get the master status
4206        if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
4207            if (ps.getIntentFilterVerificationInfo() != null) {
4208                status = ps.getIntentFilterVerificationInfo().getStatus();
4209            }
4210        }
4211        return status;
4212    }
4213
4214    private ResolveInfo querySkipCurrentProfileIntents(
4215            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4216            int flags, int sourceUserId) {
4217        if (matchingFilters != null) {
4218            int size = matchingFilters.size();
4219            for (int i = 0; i < size; i ++) {
4220                CrossProfileIntentFilter filter = matchingFilters.get(i);
4221                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
4222                    // Checking if there are activities in the target user that can handle the
4223                    // intent.
4224                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4225                            flags, sourceUserId);
4226                    if (resolveInfo != null) {
4227                        return resolveInfo;
4228                    }
4229                }
4230            }
4231        }
4232        return null;
4233    }
4234
4235    // Return matching ResolveInfo if any for skip current profile intent filters.
4236    private ResolveInfo queryCrossProfileIntents(
4237            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
4238            int flags, int sourceUserId) {
4239        if (matchingFilters != null) {
4240            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
4241            // match the same intent. For performance reasons, it is better not to
4242            // run queryIntent twice for the same userId
4243            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
4244            int size = matchingFilters.size();
4245            for (int i = 0; i < size; i++) {
4246                CrossProfileIntentFilter filter = matchingFilters.get(i);
4247                int targetUserId = filter.getTargetUserId();
4248                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4249                        && !alreadyTriedUserIds.get(targetUserId)) {
4250                    // Checking if there are activities in the target user that can handle the
4251                    // intent.
4252                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4253                            flags, sourceUserId);
4254                    if (resolveInfo != null) return resolveInfo;
4255                    alreadyTriedUserIds.put(targetUserId, true);
4256                }
4257            }
4258        }
4259        return null;
4260    }
4261
4262    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4263            String resolvedType, int flags, int sourceUserId) {
4264        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4265                resolvedType, flags, filter.getTargetUserId());
4266        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4267            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4268        }
4269        return null;
4270    }
4271
4272    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4273            int sourceUserId, int targetUserId) {
4274        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4275        String className;
4276        if (targetUserId == UserHandle.USER_OWNER) {
4277            className = FORWARD_INTENT_TO_USER_OWNER;
4278        } else {
4279            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4280        }
4281        ComponentName forwardingActivityComponentName = new ComponentName(
4282                mAndroidApplication.packageName, className);
4283        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4284                sourceUserId);
4285        if (targetUserId == UserHandle.USER_OWNER) {
4286            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4287            forwardingResolveInfo.noResourceId = true;
4288        }
4289        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4290        forwardingResolveInfo.priority = 0;
4291        forwardingResolveInfo.preferredOrder = 0;
4292        forwardingResolveInfo.match = 0;
4293        forwardingResolveInfo.isDefault = true;
4294        forwardingResolveInfo.filter = filter;
4295        forwardingResolveInfo.targetUserId = targetUserId;
4296        return forwardingResolveInfo;
4297    }
4298
4299    @Override
4300    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4301            Intent[] specifics, String[] specificTypes, Intent intent,
4302            String resolvedType, int flags, int userId) {
4303        if (!sUserManager.exists(userId)) return Collections.emptyList();
4304        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4305                false, "query intent activity options");
4306        final String resultsAction = intent.getAction();
4307
4308        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4309                | PackageManager.GET_RESOLVED_FILTER, userId);
4310
4311        if (DEBUG_INTENT_MATCHING) {
4312            Log.v(TAG, "Query " + intent + ": " + results);
4313        }
4314
4315        int specificsPos = 0;
4316        int N;
4317
4318        // todo: note that the algorithm used here is O(N^2).  This
4319        // isn't a problem in our current environment, but if we start running
4320        // into situations where we have more than 5 or 10 matches then this
4321        // should probably be changed to something smarter...
4322
4323        // First we go through and resolve each of the specific items
4324        // that were supplied, taking care of removing any corresponding
4325        // duplicate items in the generic resolve list.
4326        if (specifics != null) {
4327            for (int i=0; i<specifics.length; i++) {
4328                final Intent sintent = specifics[i];
4329                if (sintent == null) {
4330                    continue;
4331                }
4332
4333                if (DEBUG_INTENT_MATCHING) {
4334                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4335                }
4336
4337                String action = sintent.getAction();
4338                if (resultsAction != null && resultsAction.equals(action)) {
4339                    // If this action was explicitly requested, then don't
4340                    // remove things that have it.
4341                    action = null;
4342                }
4343
4344                ResolveInfo ri = null;
4345                ActivityInfo ai = null;
4346
4347                ComponentName comp = sintent.getComponent();
4348                if (comp == null) {
4349                    ri = resolveIntent(
4350                        sintent,
4351                        specificTypes != null ? specificTypes[i] : null,
4352                            flags, userId);
4353                    if (ri == null) {
4354                        continue;
4355                    }
4356                    if (ri == mResolveInfo) {
4357                        // ACK!  Must do something better with this.
4358                    }
4359                    ai = ri.activityInfo;
4360                    comp = new ComponentName(ai.applicationInfo.packageName,
4361                            ai.name);
4362                } else {
4363                    ai = getActivityInfo(comp, flags, userId);
4364                    if (ai == null) {
4365                        continue;
4366                    }
4367                }
4368
4369                // Look for any generic query activities that are duplicates
4370                // of this specific one, and remove them from the results.
4371                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4372                N = results.size();
4373                int j;
4374                for (j=specificsPos; j<N; j++) {
4375                    ResolveInfo sri = results.get(j);
4376                    if ((sri.activityInfo.name.equals(comp.getClassName())
4377                            && sri.activityInfo.applicationInfo.packageName.equals(
4378                                    comp.getPackageName()))
4379                        || (action != null && sri.filter.matchAction(action))) {
4380                        results.remove(j);
4381                        if (DEBUG_INTENT_MATCHING) Log.v(
4382                            TAG, "Removing duplicate item from " + j
4383                            + " due to specific " + specificsPos);
4384                        if (ri == null) {
4385                            ri = sri;
4386                        }
4387                        j--;
4388                        N--;
4389                    }
4390                }
4391
4392                // Add this specific item to its proper place.
4393                if (ri == null) {
4394                    ri = new ResolveInfo();
4395                    ri.activityInfo = ai;
4396                }
4397                results.add(specificsPos, ri);
4398                ri.specificIndex = i;
4399                specificsPos++;
4400            }
4401        }
4402
4403        // Now we go through the remaining generic results and remove any
4404        // duplicate actions that are found here.
4405        N = results.size();
4406        for (int i=specificsPos; i<N-1; i++) {
4407            final ResolveInfo rii = results.get(i);
4408            if (rii.filter == null) {
4409                continue;
4410            }
4411
4412            // Iterate over all of the actions of this result's intent
4413            // filter...  typically this should be just one.
4414            final Iterator<String> it = rii.filter.actionsIterator();
4415            if (it == null) {
4416                continue;
4417            }
4418            while (it.hasNext()) {
4419                final String action = it.next();
4420                if (resultsAction != null && resultsAction.equals(action)) {
4421                    // If this action was explicitly requested, then don't
4422                    // remove things that have it.
4423                    continue;
4424                }
4425                for (int j=i+1; j<N; j++) {
4426                    final ResolveInfo rij = results.get(j);
4427                    if (rij.filter != null && rij.filter.hasAction(action)) {
4428                        results.remove(j);
4429                        if (DEBUG_INTENT_MATCHING) Log.v(
4430                            TAG, "Removing duplicate item from " + j
4431                            + " due to action " + action + " at " + i);
4432                        j--;
4433                        N--;
4434                    }
4435                }
4436            }
4437
4438            // If the caller didn't request filter information, drop it now
4439            // so we don't have to marshall/unmarshall it.
4440            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4441                rii.filter = null;
4442            }
4443        }
4444
4445        // Filter out the caller activity if so requested.
4446        if (caller != null) {
4447            N = results.size();
4448            for (int i=0; i<N; i++) {
4449                ActivityInfo ainfo = results.get(i).activityInfo;
4450                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4451                        && caller.getClassName().equals(ainfo.name)) {
4452                    results.remove(i);
4453                    break;
4454                }
4455            }
4456        }
4457
4458        // If the caller didn't request filter information,
4459        // drop them now so we don't have to
4460        // marshall/unmarshall it.
4461        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4462            N = results.size();
4463            for (int i=0; i<N; i++) {
4464                results.get(i).filter = null;
4465            }
4466        }
4467
4468        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4469        return results;
4470    }
4471
4472    @Override
4473    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4474            int userId) {
4475        if (!sUserManager.exists(userId)) return Collections.emptyList();
4476        ComponentName comp = intent.getComponent();
4477        if (comp == null) {
4478            if (intent.getSelector() != null) {
4479                intent = intent.getSelector();
4480                comp = intent.getComponent();
4481            }
4482        }
4483        if (comp != null) {
4484            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4485            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4486            if (ai != null) {
4487                ResolveInfo ri = new ResolveInfo();
4488                ri.activityInfo = ai;
4489                list.add(ri);
4490            }
4491            return list;
4492        }
4493
4494        // reader
4495        synchronized (mPackages) {
4496            String pkgName = intent.getPackage();
4497            if (pkgName == null) {
4498                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4499            }
4500            final PackageParser.Package pkg = mPackages.get(pkgName);
4501            if (pkg != null) {
4502                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4503                        userId);
4504            }
4505            return null;
4506        }
4507    }
4508
4509    @Override
4510    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4511        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4512        if (!sUserManager.exists(userId)) return null;
4513        if (query != null) {
4514            if (query.size() >= 1) {
4515                // If there is more than one service with the same priority,
4516                // just arbitrarily pick the first one.
4517                return query.get(0);
4518            }
4519        }
4520        return null;
4521    }
4522
4523    @Override
4524    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4525            int userId) {
4526        if (!sUserManager.exists(userId)) return Collections.emptyList();
4527        ComponentName comp = intent.getComponent();
4528        if (comp == null) {
4529            if (intent.getSelector() != null) {
4530                intent = intent.getSelector();
4531                comp = intent.getComponent();
4532            }
4533        }
4534        if (comp != null) {
4535            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4536            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4537            if (si != null) {
4538                final ResolveInfo ri = new ResolveInfo();
4539                ri.serviceInfo = si;
4540                list.add(ri);
4541            }
4542            return list;
4543        }
4544
4545        // reader
4546        synchronized (mPackages) {
4547            String pkgName = intent.getPackage();
4548            if (pkgName == null) {
4549                return mServices.queryIntent(intent, resolvedType, flags, userId);
4550            }
4551            final PackageParser.Package pkg = mPackages.get(pkgName);
4552            if (pkg != null) {
4553                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4554                        userId);
4555            }
4556            return null;
4557        }
4558    }
4559
4560    @Override
4561    public List<ResolveInfo> queryIntentContentProviders(
4562            Intent intent, String resolvedType, int flags, int userId) {
4563        if (!sUserManager.exists(userId)) return Collections.emptyList();
4564        ComponentName comp = intent.getComponent();
4565        if (comp == null) {
4566            if (intent.getSelector() != null) {
4567                intent = intent.getSelector();
4568                comp = intent.getComponent();
4569            }
4570        }
4571        if (comp != null) {
4572            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4573            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4574            if (pi != null) {
4575                final ResolveInfo ri = new ResolveInfo();
4576                ri.providerInfo = pi;
4577                list.add(ri);
4578            }
4579            return list;
4580        }
4581
4582        // reader
4583        synchronized (mPackages) {
4584            String pkgName = intent.getPackage();
4585            if (pkgName == null) {
4586                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4587            }
4588            final PackageParser.Package pkg = mPackages.get(pkgName);
4589            if (pkg != null) {
4590                return mProviders.queryIntentForPackage(
4591                        intent, resolvedType, flags, pkg.providers, userId);
4592            }
4593            return null;
4594        }
4595    }
4596
4597    @Override
4598    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4599        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4600
4601        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4602
4603        // writer
4604        synchronized (mPackages) {
4605            ArrayList<PackageInfo> list;
4606            if (listUninstalled) {
4607                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4608                for (PackageSetting ps : mSettings.mPackages.values()) {
4609                    PackageInfo pi;
4610                    if (ps.pkg != null) {
4611                        pi = generatePackageInfo(ps.pkg, flags, userId);
4612                    } else {
4613                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4614                    }
4615                    if (pi != null) {
4616                        list.add(pi);
4617                    }
4618                }
4619            } else {
4620                list = new ArrayList<PackageInfo>(mPackages.size());
4621                for (PackageParser.Package p : mPackages.values()) {
4622                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4623                    if (pi != null) {
4624                        list.add(pi);
4625                    }
4626                }
4627            }
4628
4629            return new ParceledListSlice<PackageInfo>(list);
4630        }
4631    }
4632
4633    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4634            String[] permissions, boolean[] tmp, int flags, int userId) {
4635        int numMatch = 0;
4636        final PermissionsState permissionsState = ps.getPermissionsState();
4637        for (int i=0; i<permissions.length; i++) {
4638            final String permission = permissions[i];
4639            if (permissionsState.hasPermission(permission, userId)) {
4640                tmp[i] = true;
4641                numMatch++;
4642            } else {
4643                tmp[i] = false;
4644            }
4645        }
4646        if (numMatch == 0) {
4647            return;
4648        }
4649        PackageInfo pi;
4650        if (ps.pkg != null) {
4651            pi = generatePackageInfo(ps.pkg, flags, userId);
4652        } else {
4653            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4654        }
4655        // The above might return null in cases of uninstalled apps or install-state
4656        // skew across users/profiles.
4657        if (pi != null) {
4658            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4659                if (numMatch == permissions.length) {
4660                    pi.requestedPermissions = permissions;
4661                } else {
4662                    pi.requestedPermissions = new String[numMatch];
4663                    numMatch = 0;
4664                    for (int i=0; i<permissions.length; i++) {
4665                        if (tmp[i]) {
4666                            pi.requestedPermissions[numMatch] = permissions[i];
4667                            numMatch++;
4668                        }
4669                    }
4670                }
4671            }
4672            list.add(pi);
4673        }
4674    }
4675
4676    @Override
4677    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4678            String[] permissions, int flags, int userId) {
4679        if (!sUserManager.exists(userId)) return null;
4680        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4681
4682        // writer
4683        synchronized (mPackages) {
4684            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4685            boolean[] tmpBools = new boolean[permissions.length];
4686            if (listUninstalled) {
4687                for (PackageSetting ps : mSettings.mPackages.values()) {
4688                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4689                }
4690            } else {
4691                for (PackageParser.Package pkg : mPackages.values()) {
4692                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4693                    if (ps != null) {
4694                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4695                                userId);
4696                    }
4697                }
4698            }
4699
4700            return new ParceledListSlice<PackageInfo>(list);
4701        }
4702    }
4703
4704    @Override
4705    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4706        if (!sUserManager.exists(userId)) return null;
4707        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4708
4709        // writer
4710        synchronized (mPackages) {
4711            ArrayList<ApplicationInfo> list;
4712            if (listUninstalled) {
4713                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4714                for (PackageSetting ps : mSettings.mPackages.values()) {
4715                    ApplicationInfo ai;
4716                    if (ps.pkg != null) {
4717                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4718                                ps.readUserState(userId), userId);
4719                    } else {
4720                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4721                    }
4722                    if (ai != null) {
4723                        list.add(ai);
4724                    }
4725                }
4726            } else {
4727                list = new ArrayList<ApplicationInfo>(mPackages.size());
4728                for (PackageParser.Package p : mPackages.values()) {
4729                    if (p.mExtras != null) {
4730                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4731                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4732                        if (ai != null) {
4733                            list.add(ai);
4734                        }
4735                    }
4736                }
4737            }
4738
4739            return new ParceledListSlice<ApplicationInfo>(list);
4740        }
4741    }
4742
4743    public List<ApplicationInfo> getPersistentApplications(int flags) {
4744        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4745
4746        // reader
4747        synchronized (mPackages) {
4748            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4749            final int userId = UserHandle.getCallingUserId();
4750            while (i.hasNext()) {
4751                final PackageParser.Package p = i.next();
4752                if (p.applicationInfo != null
4753                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4754                        && (!mSafeMode || isSystemApp(p))) {
4755                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4756                    if (ps != null) {
4757                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4758                                ps.readUserState(userId), userId);
4759                        if (ai != null) {
4760                            finalList.add(ai);
4761                        }
4762                    }
4763                }
4764            }
4765        }
4766
4767        return finalList;
4768    }
4769
4770    @Override
4771    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4772        if (!sUserManager.exists(userId)) return null;
4773        // reader
4774        synchronized (mPackages) {
4775            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4776            PackageSetting ps = provider != null
4777                    ? mSettings.mPackages.get(provider.owner.packageName)
4778                    : null;
4779            return ps != null
4780                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4781                    && (!mSafeMode || (provider.info.applicationInfo.flags
4782                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4783                    ? PackageParser.generateProviderInfo(provider, flags,
4784                            ps.readUserState(userId), userId)
4785                    : null;
4786        }
4787    }
4788
4789    /**
4790     * @deprecated
4791     */
4792    @Deprecated
4793    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4794        // reader
4795        synchronized (mPackages) {
4796            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4797                    .entrySet().iterator();
4798            final int userId = UserHandle.getCallingUserId();
4799            while (i.hasNext()) {
4800                Map.Entry<String, PackageParser.Provider> entry = i.next();
4801                PackageParser.Provider p = entry.getValue();
4802                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4803
4804                if (ps != null && p.syncable
4805                        && (!mSafeMode || (p.info.applicationInfo.flags
4806                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4807                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4808                            ps.readUserState(userId), userId);
4809                    if (info != null) {
4810                        outNames.add(entry.getKey());
4811                        outInfo.add(info);
4812                    }
4813                }
4814            }
4815        }
4816    }
4817
4818    @Override
4819    public List<ProviderInfo> queryContentProviders(String processName,
4820            int uid, int flags) {
4821        ArrayList<ProviderInfo> finalList = null;
4822        // reader
4823        synchronized (mPackages) {
4824            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4825            final int userId = processName != null ?
4826                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4827            while (i.hasNext()) {
4828                final PackageParser.Provider p = i.next();
4829                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4830                if (ps != null && p.info.authority != null
4831                        && (processName == null
4832                                || (p.info.processName.equals(processName)
4833                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4834                        && mSettings.isEnabledLPr(p.info, flags, userId)
4835                        && (!mSafeMode
4836                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4837                    if (finalList == null) {
4838                        finalList = new ArrayList<ProviderInfo>(3);
4839                    }
4840                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4841                            ps.readUserState(userId), userId);
4842                    if (info != null) {
4843                        finalList.add(info);
4844                    }
4845                }
4846            }
4847        }
4848
4849        if (finalList != null) {
4850            Collections.sort(finalList, mProviderInitOrderSorter);
4851        }
4852
4853        return finalList;
4854    }
4855
4856    @Override
4857    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4858            int flags) {
4859        // reader
4860        synchronized (mPackages) {
4861            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4862            return PackageParser.generateInstrumentationInfo(i, flags);
4863        }
4864    }
4865
4866    @Override
4867    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4868            int flags) {
4869        ArrayList<InstrumentationInfo> finalList =
4870            new ArrayList<InstrumentationInfo>();
4871
4872        // reader
4873        synchronized (mPackages) {
4874            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4875            while (i.hasNext()) {
4876                final PackageParser.Instrumentation p = i.next();
4877                if (targetPackage == null
4878                        || targetPackage.equals(p.info.targetPackage)) {
4879                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4880                            flags);
4881                    if (ii != null) {
4882                        finalList.add(ii);
4883                    }
4884                }
4885            }
4886        }
4887
4888        return finalList;
4889    }
4890
4891    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4892        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4893        if (overlays == null) {
4894            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4895            return;
4896        }
4897        for (PackageParser.Package opkg : overlays.values()) {
4898            // Not much to do if idmap fails: we already logged the error
4899            // and we certainly don't want to abort installation of pkg simply
4900            // because an overlay didn't fit properly. For these reasons,
4901            // ignore the return value of createIdmapForPackagePairLI.
4902            createIdmapForPackagePairLI(pkg, opkg);
4903        }
4904    }
4905
4906    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4907            PackageParser.Package opkg) {
4908        if (!opkg.mTrustedOverlay) {
4909            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4910                    opkg.baseCodePath + ": overlay not trusted");
4911            return false;
4912        }
4913        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4914        if (overlaySet == null) {
4915            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4916                    opkg.baseCodePath + " but target package has no known overlays");
4917            return false;
4918        }
4919        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4920        // TODO: generate idmap for split APKs
4921        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4922            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4923                    + opkg.baseCodePath);
4924            return false;
4925        }
4926        PackageParser.Package[] overlayArray =
4927            overlaySet.values().toArray(new PackageParser.Package[0]);
4928        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4929            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4930                return p1.mOverlayPriority - p2.mOverlayPriority;
4931            }
4932        };
4933        Arrays.sort(overlayArray, cmp);
4934
4935        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4936        int i = 0;
4937        for (PackageParser.Package p : overlayArray) {
4938            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4939        }
4940        return true;
4941    }
4942
4943    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4944        final File[] files = dir.listFiles();
4945        if (ArrayUtils.isEmpty(files)) {
4946            Log.d(TAG, "No files in app dir " + dir);
4947            return;
4948        }
4949
4950        if (DEBUG_PACKAGE_SCANNING) {
4951            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4952                    + " flags=0x" + Integer.toHexString(parseFlags));
4953        }
4954
4955        for (File file : files) {
4956            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4957                    && !PackageInstallerService.isStageName(file.getName());
4958            if (!isPackage) {
4959                // Ignore entries which are not packages
4960                continue;
4961            }
4962            try {
4963                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4964                        scanFlags, currentTime, null);
4965            } catch (PackageManagerException e) {
4966                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4967
4968                // Delete invalid userdata apps
4969                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4970                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4971                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4972                    if (file.isDirectory()) {
4973                        mInstaller.rmPackageDir(file.getAbsolutePath());
4974                    } else {
4975                        file.delete();
4976                    }
4977                }
4978            }
4979        }
4980    }
4981
4982    private static File getSettingsProblemFile() {
4983        File dataDir = Environment.getDataDirectory();
4984        File systemDir = new File(dataDir, "system");
4985        File fname = new File(systemDir, "uiderrors.txt");
4986        return fname;
4987    }
4988
4989    static void reportSettingsProblem(int priority, String msg) {
4990        logCriticalInfo(priority, msg);
4991    }
4992
4993    static void logCriticalInfo(int priority, String msg) {
4994        Slog.println(priority, TAG, msg);
4995        EventLogTags.writePmCriticalInfo(msg);
4996        try {
4997            File fname = getSettingsProblemFile();
4998            FileOutputStream out = new FileOutputStream(fname, true);
4999            PrintWriter pw = new FastPrintWriter(out);
5000            SimpleDateFormat formatter = new SimpleDateFormat();
5001            String dateString = formatter.format(new Date(System.currentTimeMillis()));
5002            pw.println(dateString + ": " + msg);
5003            pw.close();
5004            FileUtils.setPermissions(
5005                    fname.toString(),
5006                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
5007                    -1, -1);
5008        } catch (java.io.IOException e) {
5009        }
5010    }
5011
5012    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
5013            PackageParser.Package pkg, File srcFile, int parseFlags)
5014            throws PackageManagerException {
5015        if (ps != null
5016                && ps.codePath.equals(srcFile)
5017                && ps.timeStamp == srcFile.lastModified()
5018                && !isCompatSignatureUpdateNeeded(pkg)
5019                && !isRecoverSignatureUpdateNeeded(pkg)) {
5020            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
5021            if (ps.signatures.mSignatures != null
5022                    && ps.signatures.mSignatures.length != 0
5023                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
5024                // Optimization: reuse the existing cached certificates
5025                // if the package appears to be unchanged.
5026                pkg.mSignatures = ps.signatures.mSignatures;
5027                KeySetManagerService ksms = mSettings.mKeySetManagerService;
5028                synchronized (mPackages) {
5029                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
5030                }
5031                return;
5032            }
5033
5034            Slog.w(TAG, "PackageSetting for " + ps.name
5035                    + " is missing signatures.  Collecting certs again to recover them.");
5036        } else {
5037            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
5038        }
5039
5040        try {
5041            pp.collectCertificates(pkg, parseFlags);
5042            pp.collectManifestDigest(pkg);
5043        } catch (PackageParserException e) {
5044            throw PackageManagerException.from(e);
5045        }
5046    }
5047
5048    /*
5049     *  Scan a package and return the newly parsed package.
5050     *  Returns null in case of errors and the error code is stored in mLastScanError
5051     */
5052    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
5053            long currentTime, UserHandle user) throws PackageManagerException {
5054        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
5055        parseFlags |= mDefParseFlags;
5056        PackageParser pp = new PackageParser();
5057        pp.setSeparateProcesses(mSeparateProcesses);
5058        pp.setOnlyCoreApps(mOnlyCore);
5059        pp.setDisplayMetrics(mMetrics);
5060
5061        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
5062            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
5063        }
5064
5065        final PackageParser.Package pkg;
5066        try {
5067            pkg = pp.parsePackage(scanFile, parseFlags);
5068        } catch (PackageParserException e) {
5069            throw PackageManagerException.from(e);
5070        }
5071
5072        PackageSetting ps = null;
5073        PackageSetting updatedPkg;
5074        // reader
5075        synchronized (mPackages) {
5076            // Look to see if we already know about this package.
5077            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
5078            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
5079                // This package has been renamed to its original name.  Let's
5080                // use that.
5081                ps = mSettings.peekPackageLPr(oldName);
5082            }
5083            // If there was no original package, see one for the real package name.
5084            if (ps == null) {
5085                ps = mSettings.peekPackageLPr(pkg.packageName);
5086            }
5087            // Check to see if this package could be hiding/updating a system
5088            // package.  Must look for it either under the original or real
5089            // package name depending on our state.
5090            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
5091            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
5092        }
5093        boolean updatedPkgBetter = false;
5094        // First check if this is a system package that may involve an update
5095        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5096            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
5097            // it needs to drop FLAG_PRIVILEGED.
5098            if (locationIsPrivileged(scanFile)) {
5099                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5100            } else {
5101                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5102            }
5103
5104            if (ps != null && !ps.codePath.equals(scanFile)) {
5105                // The path has changed from what was last scanned...  check the
5106                // version of the new path against what we have stored to determine
5107                // what to do.
5108                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
5109                if (pkg.mVersionCode <= ps.versionCode) {
5110                    // The system package has been updated and the code path does not match
5111                    // Ignore entry. Skip it.
5112                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
5113                            + " ignored: updated version " + ps.versionCode
5114                            + " better than this " + pkg.mVersionCode);
5115                    if (!updatedPkg.codePath.equals(scanFile)) {
5116                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
5117                                + ps.name + " changing from " + updatedPkg.codePathString
5118                                + " to " + scanFile);
5119                        updatedPkg.codePath = scanFile;
5120                        updatedPkg.codePathString = scanFile.toString();
5121                        updatedPkg.resourcePath = scanFile;
5122                        updatedPkg.resourcePathString = scanFile.toString();
5123                    }
5124                    updatedPkg.pkg = pkg;
5125                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
5126                } else {
5127                    // The current app on the system partition is better than
5128                    // what we have updated to on the data partition; switch
5129                    // back to the system partition version.
5130                    // At this point, its safely assumed that package installation for
5131                    // apps in system partition will go through. If not there won't be a working
5132                    // version of the app
5133                    // writer
5134                    synchronized (mPackages) {
5135                        // Just remove the loaded entries from package lists.
5136                        mPackages.remove(ps.name);
5137                    }
5138
5139                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5140                            + " reverting from " + ps.codePathString
5141                            + ": new version " + pkg.mVersionCode
5142                            + " better than installed " + ps.versionCode);
5143
5144                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5145                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5146                    synchronized (mInstallLock) {
5147                        args.cleanUpResourcesLI();
5148                    }
5149                    synchronized (mPackages) {
5150                        mSettings.enableSystemPackageLPw(ps.name);
5151                    }
5152                    updatedPkgBetter = true;
5153                }
5154            }
5155        }
5156
5157        if (updatedPkg != null) {
5158            // An updated system app will not have the PARSE_IS_SYSTEM flag set
5159            // initially
5160            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
5161
5162            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
5163            // flag set initially
5164            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
5165                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
5166            }
5167        }
5168
5169        // Verify certificates against what was last scanned
5170        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
5171
5172        /*
5173         * A new system app appeared, but we already had a non-system one of the
5174         * same name installed earlier.
5175         */
5176        boolean shouldHideSystemApp = false;
5177        if (updatedPkg == null && ps != null
5178                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
5179            /*
5180             * Check to make sure the signatures match first. If they don't,
5181             * wipe the installed application and its data.
5182             */
5183            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
5184                    != PackageManager.SIGNATURE_MATCH) {
5185                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
5186                        + " signatures don't match existing userdata copy; removing");
5187                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
5188                ps = null;
5189            } else {
5190                /*
5191                 * If the newly-added system app is an older version than the
5192                 * already installed version, hide it. It will be scanned later
5193                 * and re-added like an update.
5194                 */
5195                if (pkg.mVersionCode <= ps.versionCode) {
5196                    shouldHideSystemApp = true;
5197                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
5198                            + " but new version " + pkg.mVersionCode + " better than installed "
5199                            + ps.versionCode + "; hiding system");
5200                } else {
5201                    /*
5202                     * The newly found system app is a newer version that the
5203                     * one previously installed. Simply remove the
5204                     * already-installed application and replace it with our own
5205                     * while keeping the application data.
5206                     */
5207                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
5208                            + " reverting from " + ps.codePathString + ": new version "
5209                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
5210                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
5211                            ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
5212                    synchronized (mInstallLock) {
5213                        args.cleanUpResourcesLI();
5214                    }
5215                }
5216            }
5217        }
5218
5219        // The apk is forward locked (not public) if its code and resources
5220        // are kept in different files. (except for app in either system or
5221        // vendor path).
5222        // TODO grab this value from PackageSettings
5223        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5224            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
5225                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
5226            }
5227        }
5228
5229        // TODO: extend to support forward-locked splits
5230        String resourcePath = null;
5231        String baseResourcePath = null;
5232        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
5233            if (ps != null && ps.resourcePathString != null) {
5234                resourcePath = ps.resourcePathString;
5235                baseResourcePath = ps.resourcePathString;
5236            } else {
5237                // Should not happen at all. Just log an error.
5238                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
5239            }
5240        } else {
5241            resourcePath = pkg.codePath;
5242            baseResourcePath = pkg.baseCodePath;
5243        }
5244
5245        // Set application objects path explicitly.
5246        pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
5247        pkg.applicationInfo.setCodePath(pkg.codePath);
5248        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5249        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5250        pkg.applicationInfo.setResourcePath(resourcePath);
5251        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5252        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5253
5254        // Note that we invoke the following method only if we are about to unpack an application
5255        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5256                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5257
5258        /*
5259         * If the system app should be overridden by a previously installed
5260         * data, hide the system app now and let the /data/app scan pick it up
5261         * again.
5262         */
5263        if (shouldHideSystemApp) {
5264            synchronized (mPackages) {
5265                /*
5266                 * We have to grant systems permissions before we hide, because
5267                 * grantPermissions will assume the package update is trying to
5268                 * expand its permissions.
5269                 */
5270                grantPermissionsLPw(pkg, true, pkg.packageName);
5271                mSettings.disableSystemPackageLPw(pkg.packageName);
5272            }
5273        }
5274
5275        return scannedPkg;
5276    }
5277
5278    private static String fixProcessName(String defProcessName,
5279            String processName, int uid) {
5280        if (processName == null) {
5281            return defProcessName;
5282        }
5283        return processName;
5284    }
5285
5286    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5287            throws PackageManagerException {
5288        if (pkgSetting.signatures.mSignatures != null) {
5289            // Already existing package. Make sure signatures match
5290            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5291                    == PackageManager.SIGNATURE_MATCH;
5292            if (!match) {
5293                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5294                        == PackageManager.SIGNATURE_MATCH;
5295            }
5296            if (!match) {
5297                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5298                        == PackageManager.SIGNATURE_MATCH;
5299            }
5300            if (!match) {
5301                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5302                        + pkg.packageName + " signatures do not match the "
5303                        + "previously installed version; ignoring!");
5304            }
5305        }
5306
5307        // Check for shared user signatures
5308        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5309            // Already existing package. Make sure signatures match
5310            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5311                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5312            if (!match) {
5313                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5314                        == PackageManager.SIGNATURE_MATCH;
5315            }
5316            if (!match) {
5317                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5318                        == PackageManager.SIGNATURE_MATCH;
5319            }
5320            if (!match) {
5321                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5322                        "Package " + pkg.packageName
5323                        + " has no signatures that match those in shared user "
5324                        + pkgSetting.sharedUser.name + "; ignoring!");
5325            }
5326        }
5327    }
5328
5329    /**
5330     * Enforces that only the system UID or root's UID can call a method exposed
5331     * via Binder.
5332     *
5333     * @param message used as message if SecurityException is thrown
5334     * @throws SecurityException if the caller is not system or root
5335     */
5336    private static final void enforceSystemOrRoot(String message) {
5337        final int uid = Binder.getCallingUid();
5338        if (uid != Process.SYSTEM_UID && uid != 0) {
5339            throw new SecurityException(message);
5340        }
5341    }
5342
5343    @Override
5344    public void performBootDexOpt() {
5345        enforceSystemOrRoot("Only the system can request dexopt be performed");
5346
5347        // Before everything else, see whether we need to fstrim.
5348        try {
5349            IMountService ms = PackageHelper.getMountService();
5350            if (ms != null) {
5351                final boolean isUpgrade = isUpgrade();
5352                boolean doTrim = isUpgrade;
5353                if (doTrim) {
5354                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5355                } else {
5356                    final long interval = android.provider.Settings.Global.getLong(
5357                            mContext.getContentResolver(),
5358                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5359                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5360                    if (interval > 0) {
5361                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5362                        if (timeSinceLast > interval) {
5363                            doTrim = true;
5364                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5365                                    + "; running immediately");
5366                        }
5367                    }
5368                }
5369                if (doTrim) {
5370                    if (!isFirstBoot()) {
5371                        try {
5372                            ActivityManagerNative.getDefault().showBootMessage(
5373                                    mContext.getResources().getString(
5374                                            R.string.android_upgrading_fstrim), true);
5375                        } catch (RemoteException e) {
5376                        }
5377                    }
5378                    ms.runMaintenance();
5379                }
5380            } else {
5381                Slog.e(TAG, "Mount service unavailable!");
5382            }
5383        } catch (RemoteException e) {
5384            // Can't happen; MountService is local
5385        }
5386
5387        final ArraySet<PackageParser.Package> pkgs;
5388        synchronized (mPackages) {
5389            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5390        }
5391
5392        if (pkgs != null) {
5393            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5394            // in case the device runs out of space.
5395            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5396            // Give priority to core apps.
5397            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5398                PackageParser.Package pkg = it.next();
5399                if (pkg.coreApp) {
5400                    if (DEBUG_DEXOPT) {
5401                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5402                    }
5403                    sortedPkgs.add(pkg);
5404                    it.remove();
5405                }
5406            }
5407            // Give priority to system apps that listen for pre boot complete.
5408            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5409            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5410            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5411                PackageParser.Package pkg = it.next();
5412                if (pkgNames.contains(pkg.packageName)) {
5413                    if (DEBUG_DEXOPT) {
5414                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5415                    }
5416                    sortedPkgs.add(pkg);
5417                    it.remove();
5418                }
5419            }
5420            // Give priority to system apps.
5421            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5422                PackageParser.Package pkg = it.next();
5423                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5424                    if (DEBUG_DEXOPT) {
5425                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5426                    }
5427                    sortedPkgs.add(pkg);
5428                    it.remove();
5429                }
5430            }
5431            // Give priority to updated system apps.
5432            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5433                PackageParser.Package pkg = it.next();
5434                if (pkg.isUpdatedSystemApp()) {
5435                    if (DEBUG_DEXOPT) {
5436                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5437                    }
5438                    sortedPkgs.add(pkg);
5439                    it.remove();
5440                }
5441            }
5442            // Give priority to apps that listen for boot complete.
5443            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5444            pkgNames = getPackageNamesForIntent(intent);
5445            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5446                PackageParser.Package pkg = it.next();
5447                if (pkgNames.contains(pkg.packageName)) {
5448                    if (DEBUG_DEXOPT) {
5449                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5450                    }
5451                    sortedPkgs.add(pkg);
5452                    it.remove();
5453                }
5454            }
5455            // Filter out packages that aren't recently used.
5456            filterRecentlyUsedApps(pkgs);
5457            // Add all remaining apps.
5458            for (PackageParser.Package pkg : pkgs) {
5459                if (DEBUG_DEXOPT) {
5460                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5461                }
5462                sortedPkgs.add(pkg);
5463            }
5464
5465            // If we want to be lazy, filter everything that wasn't recently used.
5466            if (mLazyDexOpt) {
5467                filterRecentlyUsedApps(sortedPkgs);
5468            }
5469
5470            int i = 0;
5471            int total = sortedPkgs.size();
5472            File dataDir = Environment.getDataDirectory();
5473            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5474            if (lowThreshold == 0) {
5475                throw new IllegalStateException("Invalid low memory threshold");
5476            }
5477            for (PackageParser.Package pkg : sortedPkgs) {
5478                long usableSpace = dataDir.getUsableSpace();
5479                if (usableSpace < lowThreshold) {
5480                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5481                    break;
5482                }
5483                performBootDexOpt(pkg, ++i, total);
5484            }
5485        }
5486    }
5487
5488    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5489        // Filter out packages that aren't recently used.
5490        //
5491        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5492        // should do a full dexopt.
5493        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5494            int total = pkgs.size();
5495            int skipped = 0;
5496            long now = System.currentTimeMillis();
5497            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5498                PackageParser.Package pkg = i.next();
5499                long then = pkg.mLastPackageUsageTimeInMills;
5500                if (then + mDexOptLRUThresholdInMills < now) {
5501                    if (DEBUG_DEXOPT) {
5502                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5503                              ((then == 0) ? "never" : new Date(then)));
5504                    }
5505                    i.remove();
5506                    skipped++;
5507                }
5508            }
5509            if (DEBUG_DEXOPT) {
5510                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5511            }
5512        }
5513    }
5514
5515    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5516        List<ResolveInfo> ris = null;
5517        try {
5518            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5519                    intent, null, 0, UserHandle.USER_OWNER);
5520        } catch (RemoteException e) {
5521        }
5522        ArraySet<String> pkgNames = new ArraySet<String>();
5523        if (ris != null) {
5524            for (ResolveInfo ri : ris) {
5525                pkgNames.add(ri.activityInfo.packageName);
5526            }
5527        }
5528        return pkgNames;
5529    }
5530
5531    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5532        if (DEBUG_DEXOPT) {
5533            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5534        }
5535        if (!isFirstBoot()) {
5536            try {
5537                ActivityManagerNative.getDefault().showBootMessage(
5538                        mContext.getResources().getString(R.string.android_upgrading_apk,
5539                                curr, total), true);
5540            } catch (RemoteException e) {
5541            }
5542        }
5543        PackageParser.Package p = pkg;
5544        synchronized (mInstallLock) {
5545            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5546                    false /* force dex */, false /* defer */, true /* include dependencies */);
5547        }
5548    }
5549
5550    @Override
5551    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5552        return performDexOpt(packageName, instructionSet, false);
5553    }
5554
5555    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5556        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5557        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5558        if (!dexopt && !updateUsage) {
5559            // We aren't going to dexopt or update usage, so bail early.
5560            return false;
5561        }
5562        PackageParser.Package p;
5563        final String targetInstructionSet;
5564        synchronized (mPackages) {
5565            p = mPackages.get(packageName);
5566            if (p == null) {
5567                return false;
5568            }
5569            if (updateUsage) {
5570                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5571            }
5572            mPackageUsage.write(false);
5573            if (!dexopt) {
5574                // We aren't going to dexopt, so bail early.
5575                return false;
5576            }
5577
5578            targetInstructionSet = instructionSet != null ? instructionSet :
5579                    getPrimaryInstructionSet(p.applicationInfo);
5580            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5581                return false;
5582            }
5583        }
5584
5585        synchronized (mInstallLock) {
5586            final String[] instructionSets = new String[] { targetInstructionSet };
5587            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5588                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5589            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5590        }
5591    }
5592
5593    public ArraySet<String> getPackagesThatNeedDexOpt() {
5594        ArraySet<String> pkgs = null;
5595        synchronized (mPackages) {
5596            for (PackageParser.Package p : mPackages.values()) {
5597                if (DEBUG_DEXOPT) {
5598                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5599                }
5600                if (!p.mDexOptPerformed.isEmpty()) {
5601                    continue;
5602                }
5603                if (pkgs == null) {
5604                    pkgs = new ArraySet<String>();
5605                }
5606                pkgs.add(p.packageName);
5607            }
5608        }
5609        return pkgs;
5610    }
5611
5612    public void shutdown() {
5613        mPackageUsage.write(true);
5614    }
5615
5616    @Override
5617    public void forceDexOpt(String packageName) {
5618        enforceSystemOrRoot("forceDexOpt");
5619
5620        PackageParser.Package pkg;
5621        synchronized (mPackages) {
5622            pkg = mPackages.get(packageName);
5623            if (pkg == null) {
5624                throw new IllegalArgumentException("Missing package: " + packageName);
5625            }
5626        }
5627
5628        synchronized (mInstallLock) {
5629            final String[] instructionSets = new String[] {
5630                    getPrimaryInstructionSet(pkg.applicationInfo) };
5631            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5632                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5633            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5634                throw new IllegalStateException("Failed to dexopt: " + res);
5635            }
5636        }
5637    }
5638
5639    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5640        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5641            Slog.w(TAG, "Unable to update from " + oldPkg.name
5642                    + " to " + newPkg.packageName
5643                    + ": old package not in system partition");
5644            return false;
5645        } else if (mPackages.get(oldPkg.name) != null) {
5646            Slog.w(TAG, "Unable to update from " + oldPkg.name
5647                    + " to " + newPkg.packageName
5648                    + ": old package still exists");
5649            return false;
5650        }
5651        return true;
5652    }
5653
5654    private int createDataDirsLI(String volumeUuid, String packageName, int uid, String seinfo) {
5655        int[] users = sUserManager.getUserIds();
5656        int res = mInstaller.install(volumeUuid, packageName, uid, uid, seinfo);
5657        if (res < 0) {
5658            return res;
5659        }
5660        for (int user : users) {
5661            if (user != 0) {
5662                res = mInstaller.createUserData(volumeUuid, packageName,
5663                        UserHandle.getUid(user, uid), user, seinfo);
5664                if (res < 0) {
5665                    return res;
5666                }
5667            }
5668        }
5669        return res;
5670    }
5671
5672    private int removeDataDirsLI(String volumeUuid, String packageName) {
5673        int[] users = sUserManager.getUserIds();
5674        int res = 0;
5675        for (int user : users) {
5676            int resInner = mInstaller.remove(volumeUuid, packageName, user);
5677            if (resInner < 0) {
5678                res = resInner;
5679            }
5680        }
5681
5682        return res;
5683    }
5684
5685    private int deleteCodeCacheDirsLI(String volumeUuid, String packageName) {
5686        int[] users = sUserManager.getUserIds();
5687        int res = 0;
5688        for (int user : users) {
5689            int resInner = mInstaller.deleteCodeCacheFiles(volumeUuid, packageName, user);
5690            if (resInner < 0) {
5691                res = resInner;
5692            }
5693        }
5694        return res;
5695    }
5696
5697    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5698            PackageParser.Package changingLib) {
5699        if (file.path != null) {
5700            usesLibraryFiles.add(file.path);
5701            return;
5702        }
5703        PackageParser.Package p = mPackages.get(file.apk);
5704        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5705            // If we are doing this while in the middle of updating a library apk,
5706            // then we need to make sure to use that new apk for determining the
5707            // dependencies here.  (We haven't yet finished committing the new apk
5708            // to the package manager state.)
5709            if (p == null || p.packageName.equals(changingLib.packageName)) {
5710                p = changingLib;
5711            }
5712        }
5713        if (p != null) {
5714            usesLibraryFiles.addAll(p.getAllCodePaths());
5715        }
5716    }
5717
5718    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5719            PackageParser.Package changingLib) throws PackageManagerException {
5720        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5721            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5722            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5723            for (int i=0; i<N; i++) {
5724                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5725                if (file == null) {
5726                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5727                            "Package " + pkg.packageName + " requires unavailable shared library "
5728                            + pkg.usesLibraries.get(i) + "; failing!");
5729                }
5730                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5731            }
5732            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5733            for (int i=0; i<N; i++) {
5734                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5735                if (file == null) {
5736                    Slog.w(TAG, "Package " + pkg.packageName
5737                            + " desires unavailable shared library "
5738                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5739                } else {
5740                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5741                }
5742            }
5743            N = usesLibraryFiles.size();
5744            if (N > 0) {
5745                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5746            } else {
5747                pkg.usesLibraryFiles = null;
5748            }
5749        }
5750    }
5751
5752    private static boolean hasString(List<String> list, List<String> which) {
5753        if (list == null) {
5754            return false;
5755        }
5756        for (int i=list.size()-1; i>=0; i--) {
5757            for (int j=which.size()-1; j>=0; j--) {
5758                if (which.get(j).equals(list.get(i))) {
5759                    return true;
5760                }
5761            }
5762        }
5763        return false;
5764    }
5765
5766    private void updateAllSharedLibrariesLPw() {
5767        for (PackageParser.Package pkg : mPackages.values()) {
5768            try {
5769                updateSharedLibrariesLPw(pkg, null);
5770            } catch (PackageManagerException e) {
5771                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5772            }
5773        }
5774    }
5775
5776    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5777            PackageParser.Package changingPkg) {
5778        ArrayList<PackageParser.Package> res = null;
5779        for (PackageParser.Package pkg : mPackages.values()) {
5780            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5781                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5782                if (res == null) {
5783                    res = new ArrayList<PackageParser.Package>();
5784                }
5785                res.add(pkg);
5786                try {
5787                    updateSharedLibrariesLPw(pkg, changingPkg);
5788                } catch (PackageManagerException e) {
5789                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5790                }
5791            }
5792        }
5793        return res;
5794    }
5795
5796    /**
5797     * Derive the value of the {@code cpuAbiOverride} based on the provided
5798     * value and an optional stored value from the package settings.
5799     */
5800    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5801        String cpuAbiOverride = null;
5802
5803        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5804            cpuAbiOverride = null;
5805        } else if (abiOverride != null) {
5806            cpuAbiOverride = abiOverride;
5807        } else if (settings != null) {
5808            cpuAbiOverride = settings.cpuAbiOverrideString;
5809        }
5810
5811        return cpuAbiOverride;
5812    }
5813
5814    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5815            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5816        boolean success = false;
5817        try {
5818            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5819                    currentTime, user);
5820            success = true;
5821            return res;
5822        } finally {
5823            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5824                removeDataDirsLI(pkg.volumeUuid, pkg.packageName);
5825            }
5826        }
5827    }
5828
5829    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5830            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5831        final File scanFile = new File(pkg.codePath);
5832        if (pkg.applicationInfo.getCodePath() == null ||
5833                pkg.applicationInfo.getResourcePath() == null) {
5834            // Bail out. The resource and code paths haven't been set.
5835            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5836                    "Code and resource paths haven't been set correctly");
5837        }
5838
5839        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5840            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5841        } else {
5842            // Only allow system apps to be flagged as core apps.
5843            pkg.coreApp = false;
5844        }
5845
5846        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5847            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5848        }
5849
5850        if (mCustomResolverComponentName != null &&
5851                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5852            setUpCustomResolverActivity(pkg);
5853        }
5854
5855        if (pkg.packageName.equals("android")) {
5856            synchronized (mPackages) {
5857                if (mAndroidApplication != null) {
5858                    Slog.w(TAG, "*************************************************");
5859                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5860                    Slog.w(TAG, " file=" + scanFile);
5861                    Slog.w(TAG, "*************************************************");
5862                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5863                            "Core android package being redefined.  Skipping.");
5864                }
5865
5866                // Set up information for our fall-back user intent resolution activity.
5867                mPlatformPackage = pkg;
5868                pkg.mVersionCode = mSdkVersion;
5869                mAndroidApplication = pkg.applicationInfo;
5870
5871                if (!mResolverReplaced) {
5872                    mResolveActivity.applicationInfo = mAndroidApplication;
5873                    mResolveActivity.name = ResolverActivity.class.getName();
5874                    mResolveActivity.packageName = mAndroidApplication.packageName;
5875                    mResolveActivity.processName = "system:ui";
5876                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5877                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5878                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5879                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5880                    mResolveActivity.exported = true;
5881                    mResolveActivity.enabled = true;
5882                    mResolveInfo.activityInfo = mResolveActivity;
5883                    mResolveInfo.priority = 0;
5884                    mResolveInfo.preferredOrder = 0;
5885                    mResolveInfo.match = 0;
5886                    mResolveComponentName = new ComponentName(
5887                            mAndroidApplication.packageName, mResolveActivity.name);
5888                }
5889            }
5890        }
5891
5892        if (DEBUG_PACKAGE_SCANNING) {
5893            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5894                Log.d(TAG, "Scanning package " + pkg.packageName);
5895        }
5896
5897        if (mPackages.containsKey(pkg.packageName)
5898                || mSharedLibraries.containsKey(pkg.packageName)) {
5899            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5900                    "Application package " + pkg.packageName
5901                    + " already installed.  Skipping duplicate.");
5902        }
5903
5904        // If we're only installing presumed-existing packages, require that the
5905        // scanned APK is both already known and at the path previously established
5906        // for it.  Previously unknown packages we pick up normally, but if we have an
5907        // a priori expectation about this package's install presence, enforce it.
5908        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5909            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5910            if (known != null) {
5911                if (DEBUG_PACKAGE_SCANNING) {
5912                    Log.d(TAG, "Examining " + pkg.codePath
5913                            + " and requiring known paths " + known.codePathString
5914                            + " & " + known.resourcePathString);
5915                }
5916                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5917                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5918                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5919                            "Application package " + pkg.packageName
5920                            + " found at " + pkg.applicationInfo.getCodePath()
5921                            + " but expected at " + known.codePathString + "; ignoring.");
5922                }
5923            }
5924        }
5925
5926        // Initialize package source and resource directories
5927        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5928        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5929
5930        SharedUserSetting suid = null;
5931        PackageSetting pkgSetting = null;
5932
5933        if (!isSystemApp(pkg)) {
5934            // Only system apps can use these features.
5935            pkg.mOriginalPackages = null;
5936            pkg.mRealPackage = null;
5937            pkg.mAdoptPermissions = null;
5938        }
5939
5940        // writer
5941        synchronized (mPackages) {
5942            if (pkg.mSharedUserId != null) {
5943                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5944                if (suid == null) {
5945                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5946                            "Creating application package " + pkg.packageName
5947                            + " for shared user failed");
5948                }
5949                if (DEBUG_PACKAGE_SCANNING) {
5950                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5951                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5952                                + "): packages=" + suid.packages);
5953                }
5954            }
5955
5956            // Check if we are renaming from an original package name.
5957            PackageSetting origPackage = null;
5958            String realName = null;
5959            if (pkg.mOriginalPackages != null) {
5960                // This package may need to be renamed to a previously
5961                // installed name.  Let's check on that...
5962                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5963                if (pkg.mOriginalPackages.contains(renamed)) {
5964                    // This package had originally been installed as the
5965                    // original name, and we have already taken care of
5966                    // transitioning to the new one.  Just update the new
5967                    // one to continue using the old name.
5968                    realName = pkg.mRealPackage;
5969                    if (!pkg.packageName.equals(renamed)) {
5970                        // Callers into this function may have already taken
5971                        // care of renaming the package; only do it here if
5972                        // it is not already done.
5973                        pkg.setPackageName(renamed);
5974                    }
5975
5976                } else {
5977                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5978                        if ((origPackage = mSettings.peekPackageLPr(
5979                                pkg.mOriginalPackages.get(i))) != null) {
5980                            // We do have the package already installed under its
5981                            // original name...  should we use it?
5982                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5983                                // New package is not compatible with original.
5984                                origPackage = null;
5985                                continue;
5986                            } else if (origPackage.sharedUser != null) {
5987                                // Make sure uid is compatible between packages.
5988                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5989                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5990                                            + " to " + pkg.packageName + ": old uid "
5991                                            + origPackage.sharedUser.name
5992                                            + " differs from " + pkg.mSharedUserId);
5993                                    origPackage = null;
5994                                    continue;
5995                                }
5996                            } else {
5997                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5998                                        + pkg.packageName + " to old name " + origPackage.name);
5999                            }
6000                            break;
6001                        }
6002                    }
6003                }
6004            }
6005
6006            if (mTransferedPackages.contains(pkg.packageName)) {
6007                Slog.w(TAG, "Package " + pkg.packageName
6008                        + " was transferred to another, but its .apk remains");
6009            }
6010
6011            // Just create the setting, don't add it yet. For already existing packages
6012            // the PkgSetting exists already and doesn't have to be created.
6013            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
6014                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
6015                    pkg.applicationInfo.primaryCpuAbi,
6016                    pkg.applicationInfo.secondaryCpuAbi,
6017                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
6018                    user, false);
6019            if (pkgSetting == null) {
6020                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6021                        "Creating application package " + pkg.packageName + " failed");
6022            }
6023
6024            if (pkgSetting.origPackage != null) {
6025                // If we are first transitioning from an original package,
6026                // fix up the new package's name now.  We need to do this after
6027                // looking up the package under its new name, so getPackageLP
6028                // can take care of fiddling things correctly.
6029                pkg.setPackageName(origPackage.name);
6030
6031                // File a report about this.
6032                String msg = "New package " + pkgSetting.realName
6033                        + " renamed to replace old package " + pkgSetting.name;
6034                reportSettingsProblem(Log.WARN, msg);
6035
6036                // Make a note of it.
6037                mTransferedPackages.add(origPackage.name);
6038
6039                // No longer need to retain this.
6040                pkgSetting.origPackage = null;
6041            }
6042
6043            if (realName != null) {
6044                // Make a note of it.
6045                mTransferedPackages.add(pkg.packageName);
6046            }
6047
6048            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
6049                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
6050            }
6051
6052            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6053                // Check all shared libraries and map to their actual file path.
6054                // We only do this here for apps not on a system dir, because those
6055                // are the only ones that can fail an install due to this.  We
6056                // will take care of the system apps by updating all of their
6057                // library paths after the scan is done.
6058                updateSharedLibrariesLPw(pkg, null);
6059            }
6060
6061            if (mFoundPolicyFile) {
6062                SELinuxMMAC.assignSeinfoValue(pkg);
6063            }
6064
6065            pkg.applicationInfo.uid = pkgSetting.appId;
6066            pkg.mExtras = pkgSetting;
6067            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
6068                try {
6069                    verifySignaturesLP(pkgSetting, pkg);
6070                    // We just determined the app is signed correctly, so bring
6071                    // over the latest parsed certs.
6072                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6073                } catch (PackageManagerException e) {
6074                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
6075                        throw e;
6076                    }
6077                    // The signature has changed, but this package is in the system
6078                    // image...  let's recover!
6079                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6080                    // However...  if this package is part of a shared user, but it
6081                    // doesn't match the signature of the shared user, let's fail.
6082                    // What this means is that you can't change the signatures
6083                    // associated with an overall shared user, which doesn't seem all
6084                    // that unreasonable.
6085                    if (pkgSetting.sharedUser != null) {
6086                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
6087                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
6088                            throw new PackageManagerException(
6089                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
6090                                            "Signature mismatch for shared user : "
6091                                            + pkgSetting.sharedUser);
6092                        }
6093                    }
6094                    // File a report about this.
6095                    String msg = "System package " + pkg.packageName
6096                        + " signature changed; retaining data.";
6097                    reportSettingsProblem(Log.WARN, msg);
6098                }
6099            } else {
6100                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
6101                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
6102                            + pkg.packageName + " upgrade keys do not match the "
6103                            + "previously installed version");
6104                } else {
6105                    // We just determined the app is signed correctly, so bring
6106                    // over the latest parsed certs.
6107                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
6108                }
6109            }
6110            // Verify that this new package doesn't have any content providers
6111            // that conflict with existing packages.  Only do this if the
6112            // package isn't already installed, since we don't want to break
6113            // things that are installed.
6114            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
6115                final int N = pkg.providers.size();
6116                int i;
6117                for (i=0; i<N; i++) {
6118                    PackageParser.Provider p = pkg.providers.get(i);
6119                    if (p.info.authority != null) {
6120                        String names[] = p.info.authority.split(";");
6121                        for (int j = 0; j < names.length; j++) {
6122                            if (mProvidersByAuthority.containsKey(names[j])) {
6123                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6124                                final String otherPackageName =
6125                                        ((other != null && other.getComponentName() != null) ?
6126                                                other.getComponentName().getPackageName() : "?");
6127                                throw new PackageManagerException(
6128                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
6129                                                "Can't install because provider name " + names[j]
6130                                                + " (in package " + pkg.applicationInfo.packageName
6131                                                + ") is already used by " + otherPackageName);
6132                            }
6133                        }
6134                    }
6135                }
6136            }
6137
6138            if (pkg.mAdoptPermissions != null) {
6139                // This package wants to adopt ownership of permissions from
6140                // another package.
6141                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
6142                    final String origName = pkg.mAdoptPermissions.get(i);
6143                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
6144                    if (orig != null) {
6145                        if (verifyPackageUpdateLPr(orig, pkg)) {
6146                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
6147                                    + pkg.packageName);
6148                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
6149                        }
6150                    }
6151                }
6152            }
6153        }
6154
6155        final String pkgName = pkg.packageName;
6156
6157        final long scanFileTime = scanFile.lastModified();
6158        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
6159        pkg.applicationInfo.processName = fixProcessName(
6160                pkg.applicationInfo.packageName,
6161                pkg.applicationInfo.processName,
6162                pkg.applicationInfo.uid);
6163
6164        File dataPath;
6165        if (mPlatformPackage == pkg) {
6166            // The system package is special.
6167            dataPath = new File(Environment.getDataDirectory(), "system");
6168
6169            pkg.applicationInfo.dataDir = dataPath.getPath();
6170
6171        } else {
6172            // This is a normal package, need to make its data directory.
6173            dataPath = PackageManager.getDataDirForUser(pkg.volumeUuid, pkg.packageName,
6174                    UserHandle.USER_OWNER);
6175
6176            boolean uidError = false;
6177            if (dataPath.exists()) {
6178                int currentUid = 0;
6179                try {
6180                    StructStat stat = Os.stat(dataPath.getPath());
6181                    currentUid = stat.st_uid;
6182                } catch (ErrnoException e) {
6183                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
6184                }
6185
6186                // If we have mismatched owners for the data path, we have a problem.
6187                if (currentUid != pkg.applicationInfo.uid) {
6188                    boolean recovered = false;
6189                    if (currentUid == 0) {
6190                        // The directory somehow became owned by root.  Wow.
6191                        // This is probably because the system was stopped while
6192                        // installd was in the middle of messing with its libs
6193                        // directory.  Ask installd to fix that.
6194                        int ret = mInstaller.fixUid(pkg.volumeUuid, pkgName,
6195                                pkg.applicationInfo.uid, pkg.applicationInfo.uid);
6196                        if (ret >= 0) {
6197                            recovered = true;
6198                            String msg = "Package " + pkg.packageName
6199                                    + " unexpectedly changed to uid 0; recovered to " +
6200                                    + pkg.applicationInfo.uid;
6201                            reportSettingsProblem(Log.WARN, msg);
6202                        }
6203                    }
6204                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6205                            || (scanFlags&SCAN_BOOTING) != 0)) {
6206                        // If this is a system app, we can at least delete its
6207                        // current data so the application will still work.
6208                        int ret = removeDataDirsLI(pkg.volumeUuid, pkgName);
6209                        if (ret >= 0) {
6210                            // TODO: Kill the processes first
6211                            // Old data gone!
6212                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
6213                                    ? "System package " : "Third party package ";
6214                            String msg = prefix + pkg.packageName
6215                                    + " has changed from uid: "
6216                                    + currentUid + " to "
6217                                    + pkg.applicationInfo.uid + "; old data erased";
6218                            reportSettingsProblem(Log.WARN, msg);
6219                            recovered = true;
6220
6221                            // And now re-install the app.
6222                            ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6223                                    pkg.applicationInfo.seinfo);
6224                            if (ret == -1) {
6225                                // Ack should not happen!
6226                                msg = prefix + pkg.packageName
6227                                        + " could not have data directory re-created after delete.";
6228                                reportSettingsProblem(Log.WARN, msg);
6229                                throw new PackageManagerException(
6230                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
6231                            }
6232                        }
6233                        if (!recovered) {
6234                            mHasSystemUidErrors = true;
6235                        }
6236                    } else if (!recovered) {
6237                        // If we allow this install to proceed, we will be broken.
6238                        // Abort, abort!
6239                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6240                                "scanPackageLI");
6241                    }
6242                    if (!recovered) {
6243                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6244                            + pkg.applicationInfo.uid + "/fs_"
6245                            + currentUid;
6246                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6247                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6248                        String msg = "Package " + pkg.packageName
6249                                + " has mismatched uid: "
6250                                + currentUid + " on disk, "
6251                                + pkg.applicationInfo.uid + " in settings";
6252                        // writer
6253                        synchronized (mPackages) {
6254                            mSettings.mReadMessages.append(msg);
6255                            mSettings.mReadMessages.append('\n');
6256                            uidError = true;
6257                            if (!pkgSetting.uidError) {
6258                                reportSettingsProblem(Log.ERROR, msg);
6259                            }
6260                        }
6261                    }
6262                }
6263                pkg.applicationInfo.dataDir = dataPath.getPath();
6264                if (mShouldRestoreconData) {
6265                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6266                    mInstaller.restoreconData(pkg.volumeUuid, pkg.packageName,
6267                            pkg.applicationInfo.seinfo, pkg.applicationInfo.uid);
6268                }
6269            } else {
6270                if (DEBUG_PACKAGE_SCANNING) {
6271                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6272                        Log.v(TAG, "Want this data dir: " + dataPath);
6273                }
6274                //invoke installer to do the actual installation
6275                int ret = createDataDirsLI(pkg.volumeUuid, pkgName, pkg.applicationInfo.uid,
6276                        pkg.applicationInfo.seinfo);
6277                if (ret < 0) {
6278                    // Error from installer
6279                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6280                            "Unable to create data dirs [errorCode=" + ret + "]");
6281                }
6282
6283                if (dataPath.exists()) {
6284                    pkg.applicationInfo.dataDir = dataPath.getPath();
6285                } else {
6286                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6287                    pkg.applicationInfo.dataDir = null;
6288                }
6289            }
6290
6291            pkgSetting.uidError = uidError;
6292        }
6293
6294        final String path = scanFile.getPath();
6295        final String codePath = pkg.applicationInfo.getCodePath();
6296        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6297        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6298            setBundledAppAbisAndRoots(pkg, pkgSetting);
6299
6300            // If we haven't found any native libraries for the app, check if it has
6301            // renderscript code. We'll need to force the app to 32 bit if it has
6302            // renderscript bitcode.
6303            if (pkg.applicationInfo.primaryCpuAbi == null
6304                    && pkg.applicationInfo.secondaryCpuAbi == null
6305                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6306                NativeLibraryHelper.Handle handle = null;
6307                try {
6308                    handle = NativeLibraryHelper.Handle.create(scanFile);
6309                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6310                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6311                    }
6312                } catch (IOException ioe) {
6313                    Slog.w(TAG, "Error scanning system app : " + ioe);
6314                } finally {
6315                    IoUtils.closeQuietly(handle);
6316                }
6317            }
6318
6319            setNativeLibraryPaths(pkg);
6320        } else {
6321            // TODO: We can probably be smarter about this stuff. For installed apps,
6322            // we can calculate this information at install time once and for all. For
6323            // system apps, we can probably assume that this information doesn't change
6324            // after the first boot scan. As things stand, we do lots of unnecessary work.
6325
6326            // Give ourselves some initial paths; we'll come back for another
6327            // pass once we've determined ABI below.
6328            setNativeLibraryPaths(pkg);
6329
6330            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6331            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6332            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6333
6334            NativeLibraryHelper.Handle handle = null;
6335            try {
6336                handle = NativeLibraryHelper.Handle.create(scanFile);
6337                // TODO(multiArch): This can be null for apps that didn't go through the
6338                // usual installation process. We can calculate it again, like we
6339                // do during install time.
6340                //
6341                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6342                // unnecessary.
6343                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6344
6345                // Null out the abis so that they can be recalculated.
6346                pkg.applicationInfo.primaryCpuAbi = null;
6347                pkg.applicationInfo.secondaryCpuAbi = null;
6348                if (isMultiArch(pkg.applicationInfo)) {
6349                    // Warn if we've set an abiOverride for multi-lib packages..
6350                    // By definition, we need to copy both 32 and 64 bit libraries for
6351                    // such packages.
6352                    if (pkg.cpuAbiOverride != null
6353                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6354                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6355                    }
6356
6357                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6358                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6359                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6360                        if (isAsec) {
6361                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6362                        } else {
6363                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6364                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6365                                    useIsaSpecificSubdirs);
6366                        }
6367                    }
6368
6369                    maybeThrowExceptionForMultiArchCopy(
6370                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6371
6372                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6373                        if (isAsec) {
6374                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6375                        } else {
6376                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6377                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6378                                    useIsaSpecificSubdirs);
6379                        }
6380                    }
6381
6382                    maybeThrowExceptionForMultiArchCopy(
6383                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6384
6385                    if (abi64 >= 0) {
6386                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6387                    }
6388
6389                    if (abi32 >= 0) {
6390                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6391                        if (abi64 >= 0) {
6392                            pkg.applicationInfo.secondaryCpuAbi = abi;
6393                        } else {
6394                            pkg.applicationInfo.primaryCpuAbi = abi;
6395                        }
6396                    }
6397                } else {
6398                    String[] abiList = (cpuAbiOverride != null) ?
6399                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6400
6401                    // Enable gross and lame hacks for apps that are built with old
6402                    // SDK tools. We must scan their APKs for renderscript bitcode and
6403                    // not launch them if it's present. Don't bother checking on devices
6404                    // that don't have 64 bit support.
6405                    boolean needsRenderScriptOverride = false;
6406                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6407                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6408                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6409                        needsRenderScriptOverride = true;
6410                    }
6411
6412                    final int copyRet;
6413                    if (isAsec) {
6414                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6415                    } else {
6416                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6417                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6418                    }
6419
6420                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6421                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6422                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6423                    }
6424
6425                    if (copyRet >= 0) {
6426                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6427                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6428                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6429                    } else if (needsRenderScriptOverride) {
6430                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6431                    }
6432                }
6433            } catch (IOException ioe) {
6434                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6435            } finally {
6436                IoUtils.closeQuietly(handle);
6437            }
6438
6439            // Now that we've calculated the ABIs and determined if it's an internal app,
6440            // we will go ahead and populate the nativeLibraryPath.
6441            setNativeLibraryPaths(pkg);
6442
6443            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6444            final int[] userIds = sUserManager.getUserIds();
6445            synchronized (mInstallLock) {
6446                // Create a native library symlink only if we have native libraries
6447                // and if the native libraries are 32 bit libraries. We do not provide
6448                // this symlink for 64 bit libraries.
6449                if (pkg.applicationInfo.primaryCpuAbi != null &&
6450                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6451                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6452                    for (int userId : userIds) {
6453                        if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
6454                                nativeLibPath, userId) < 0) {
6455                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6456                                    "Failed linking native library dir (user=" + userId + ")");
6457                        }
6458                    }
6459                }
6460            }
6461        }
6462
6463        // This is a special case for the "system" package, where the ABI is
6464        // dictated by the zygote configuration (and init.rc). We should keep track
6465        // of this ABI so that we can deal with "normal" applications that run under
6466        // the same UID correctly.
6467        if (mPlatformPackage == pkg) {
6468            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6469                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6470        }
6471
6472        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6473        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6474        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6475        // Copy the derived override back to the parsed package, so that we can
6476        // update the package settings accordingly.
6477        pkg.cpuAbiOverride = cpuAbiOverride;
6478
6479        if (DEBUG_ABI_SELECTION) {
6480            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6481                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6482                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6483        }
6484
6485        // Push the derived path down into PackageSettings so we know what to
6486        // clean up at uninstall time.
6487        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6488
6489        if (DEBUG_ABI_SELECTION) {
6490            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6491                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6492                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6493        }
6494
6495        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6496            // We don't do this here during boot because we can do it all
6497            // at once after scanning all existing packages.
6498            //
6499            // We also do this *before* we perform dexopt on this package, so that
6500            // we can avoid redundant dexopts, and also to make sure we've got the
6501            // code and package path correct.
6502            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6503                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6504        }
6505
6506        if ((scanFlags & SCAN_NO_DEX) == 0) {
6507            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6508                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6509            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6510                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6511            }
6512        }
6513        if (mFactoryTest && pkg.requestedPermissions.contains(
6514                android.Manifest.permission.FACTORY_TEST)) {
6515            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6516        }
6517
6518        ArrayList<PackageParser.Package> clientLibPkgs = null;
6519
6520        // writer
6521        synchronized (mPackages) {
6522            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6523                // Only system apps can add new shared libraries.
6524                if (pkg.libraryNames != null) {
6525                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6526                        String name = pkg.libraryNames.get(i);
6527                        boolean allowed = false;
6528                        if (pkg.isUpdatedSystemApp()) {
6529                            // New library entries can only be added through the
6530                            // system image.  This is important to get rid of a lot
6531                            // of nasty edge cases: for example if we allowed a non-
6532                            // system update of the app to add a library, then uninstalling
6533                            // the update would make the library go away, and assumptions
6534                            // we made such as through app install filtering would now
6535                            // have allowed apps on the device which aren't compatible
6536                            // with it.  Better to just have the restriction here, be
6537                            // conservative, and create many fewer cases that can negatively
6538                            // impact the user experience.
6539                            final PackageSetting sysPs = mSettings
6540                                    .getDisabledSystemPkgLPr(pkg.packageName);
6541                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6542                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6543                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6544                                        allowed = true;
6545                                        allowed = true;
6546                                        break;
6547                                    }
6548                                }
6549                            }
6550                        } else {
6551                            allowed = true;
6552                        }
6553                        if (allowed) {
6554                            if (!mSharedLibraries.containsKey(name)) {
6555                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6556                            } else if (!name.equals(pkg.packageName)) {
6557                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6558                                        + name + " already exists; skipping");
6559                            }
6560                        } else {
6561                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6562                                    + name + " that is not declared on system image; skipping");
6563                        }
6564                    }
6565                    if ((scanFlags&SCAN_BOOTING) == 0) {
6566                        // If we are not booting, we need to update any applications
6567                        // that are clients of our shared library.  If we are booting,
6568                        // this will all be done once the scan is complete.
6569                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6570                    }
6571                }
6572            }
6573        }
6574
6575        // We also need to dexopt any apps that are dependent on this library.  Note that
6576        // if these fail, we should abort the install since installing the library will
6577        // result in some apps being broken.
6578        if (clientLibPkgs != null) {
6579            if ((scanFlags & SCAN_NO_DEX) == 0) {
6580                for (int i = 0; i < clientLibPkgs.size(); i++) {
6581                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6582                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6583                            null /* instruction sets */, forceDex,
6584                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6585                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6586                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6587                                "scanPackageLI failed to dexopt clientLibPkgs");
6588                    }
6589                }
6590            }
6591        }
6592
6593        // Also need to kill any apps that are dependent on the library.
6594        if (clientLibPkgs != null) {
6595            for (int i=0; i<clientLibPkgs.size(); i++) {
6596                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6597                killApplication(clientPkg.applicationInfo.packageName,
6598                        clientPkg.applicationInfo.uid, "update lib");
6599            }
6600        }
6601
6602        // writer
6603        synchronized (mPackages) {
6604            // We don't expect installation to fail beyond this point
6605
6606            // Add the new setting to mSettings
6607            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6608            // Add the new setting to mPackages
6609            mPackages.put(pkg.applicationInfo.packageName, pkg);
6610            // Make sure we don't accidentally delete its data.
6611            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6612            while (iter.hasNext()) {
6613                PackageCleanItem item = iter.next();
6614                if (pkgName.equals(item.packageName)) {
6615                    iter.remove();
6616                }
6617            }
6618
6619            // Take care of first install / last update times.
6620            if (currentTime != 0) {
6621                if (pkgSetting.firstInstallTime == 0) {
6622                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6623                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6624                    pkgSetting.lastUpdateTime = currentTime;
6625                }
6626            } else if (pkgSetting.firstInstallTime == 0) {
6627                // We need *something*.  Take time time stamp of the file.
6628                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6629            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6630                if (scanFileTime != pkgSetting.timeStamp) {
6631                    // A package on the system image has changed; consider this
6632                    // to be an update.
6633                    pkgSetting.lastUpdateTime = scanFileTime;
6634                }
6635            }
6636
6637            // Add the package's KeySets to the global KeySetManagerService
6638            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6639            try {
6640                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6641                if (pkg.mKeySetMapping != null) {
6642                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6643                    if (pkg.mUpgradeKeySets != null) {
6644                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6645                    }
6646                }
6647            } catch (NullPointerException e) {
6648                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6649            } catch (IllegalArgumentException e) {
6650                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6651            }
6652
6653            int N = pkg.providers.size();
6654            StringBuilder r = null;
6655            int i;
6656            for (i=0; i<N; i++) {
6657                PackageParser.Provider p = pkg.providers.get(i);
6658                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6659                        p.info.processName, pkg.applicationInfo.uid);
6660                mProviders.addProvider(p);
6661                p.syncable = p.info.isSyncable;
6662                if (p.info.authority != null) {
6663                    String names[] = p.info.authority.split(";");
6664                    p.info.authority = null;
6665                    for (int j = 0; j < names.length; j++) {
6666                        if (j == 1 && p.syncable) {
6667                            // We only want the first authority for a provider to possibly be
6668                            // syncable, so if we already added this provider using a different
6669                            // authority clear the syncable flag. We copy the provider before
6670                            // changing it because the mProviders object contains a reference
6671                            // to a provider that we don't want to change.
6672                            // Only do this for the second authority since the resulting provider
6673                            // object can be the same for all future authorities for this provider.
6674                            p = new PackageParser.Provider(p);
6675                            p.syncable = false;
6676                        }
6677                        if (!mProvidersByAuthority.containsKey(names[j])) {
6678                            mProvidersByAuthority.put(names[j], p);
6679                            if (p.info.authority == null) {
6680                                p.info.authority = names[j];
6681                            } else {
6682                                p.info.authority = p.info.authority + ";" + names[j];
6683                            }
6684                            if (DEBUG_PACKAGE_SCANNING) {
6685                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6686                                    Log.d(TAG, "Registered content provider: " + names[j]
6687                                            + ", className = " + p.info.name + ", isSyncable = "
6688                                            + p.info.isSyncable);
6689                            }
6690                        } else {
6691                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6692                            Slog.w(TAG, "Skipping provider name " + names[j] +
6693                                    " (in package " + pkg.applicationInfo.packageName +
6694                                    "): name already used by "
6695                                    + ((other != null && other.getComponentName() != null)
6696                                            ? other.getComponentName().getPackageName() : "?"));
6697                        }
6698                    }
6699                }
6700                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6701                    if (r == null) {
6702                        r = new StringBuilder(256);
6703                    } else {
6704                        r.append(' ');
6705                    }
6706                    r.append(p.info.name);
6707                }
6708            }
6709            if (r != null) {
6710                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6711            }
6712
6713            N = pkg.services.size();
6714            r = null;
6715            for (i=0; i<N; i++) {
6716                PackageParser.Service s = pkg.services.get(i);
6717                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6718                        s.info.processName, pkg.applicationInfo.uid);
6719                mServices.addService(s);
6720                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6721                    if (r == null) {
6722                        r = new StringBuilder(256);
6723                    } else {
6724                        r.append(' ');
6725                    }
6726                    r.append(s.info.name);
6727                }
6728            }
6729            if (r != null) {
6730                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6731            }
6732
6733            N = pkg.receivers.size();
6734            r = null;
6735            for (i=0; i<N; i++) {
6736                PackageParser.Activity a = pkg.receivers.get(i);
6737                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6738                        a.info.processName, pkg.applicationInfo.uid);
6739                mReceivers.addActivity(a, "receiver");
6740                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6741                    if (r == null) {
6742                        r = new StringBuilder(256);
6743                    } else {
6744                        r.append(' ');
6745                    }
6746                    r.append(a.info.name);
6747                }
6748            }
6749            if (r != null) {
6750                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6751            }
6752
6753            N = pkg.activities.size();
6754            r = null;
6755            for (i=0; i<N; i++) {
6756                PackageParser.Activity a = pkg.activities.get(i);
6757                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6758                        a.info.processName, pkg.applicationInfo.uid);
6759                mActivities.addActivity(a, "activity");
6760                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6761                    if (r == null) {
6762                        r = new StringBuilder(256);
6763                    } else {
6764                        r.append(' ');
6765                    }
6766                    r.append(a.info.name);
6767                }
6768            }
6769            if (r != null) {
6770                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6771            }
6772
6773            N = pkg.permissionGroups.size();
6774            r = null;
6775            for (i=0; i<N; i++) {
6776                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6777                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6778                if (cur == null) {
6779                    mPermissionGroups.put(pg.info.name, pg);
6780                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6781                        if (r == null) {
6782                            r = new StringBuilder(256);
6783                        } else {
6784                            r.append(' ');
6785                        }
6786                        r.append(pg.info.name);
6787                    }
6788                } else {
6789                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6790                            + pg.info.packageName + " ignored: original from "
6791                            + cur.info.packageName);
6792                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6793                        if (r == null) {
6794                            r = new StringBuilder(256);
6795                        } else {
6796                            r.append(' ');
6797                        }
6798                        r.append("DUP:");
6799                        r.append(pg.info.name);
6800                    }
6801                }
6802            }
6803            if (r != null) {
6804                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6805            }
6806
6807            N = pkg.permissions.size();
6808            r = null;
6809            for (i=0; i<N; i++) {
6810                PackageParser.Permission p = pkg.permissions.get(i);
6811
6812                // Now that permission groups have a special meaning, we ignore permission
6813                // groups for legacy apps to prevent unexpected behavior. In particular,
6814                // permissions for one app being granted to someone just becuase they happen
6815                // to be in a group defined by another app (before this had no implications).
6816                if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) {
6817                    p.group = mPermissionGroups.get(p.info.group);
6818                    // Warn for a permission in an unknown group.
6819                    if (p.info.group != null && p.group == null) {
6820                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6821                                + p.info.packageName + " in an unknown group " + p.info.group);
6822                    }
6823                }
6824
6825                ArrayMap<String, BasePermission> permissionMap =
6826                        p.tree ? mSettings.mPermissionTrees
6827                                : mSettings.mPermissions;
6828                BasePermission bp = permissionMap.get(p.info.name);
6829
6830                // Allow system apps to redefine non-system permissions
6831                if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6832                    final boolean currentOwnerIsSystem = (bp.perm != null
6833                            && isSystemApp(bp.perm.owner));
6834                    if (isSystemApp(p.owner)) {
6835                        if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6836                            // It's a built-in permission and no owner, take ownership now
6837                            bp.packageSetting = pkgSetting;
6838                            bp.perm = p;
6839                            bp.uid = pkg.applicationInfo.uid;
6840                            bp.sourcePackage = p.info.packageName;
6841                        } else if (!currentOwnerIsSystem) {
6842                            String msg = "New decl " + p.owner + " of permission  "
6843                                    + p.info.name + " is system; overriding " + bp.sourcePackage;
6844                            reportSettingsProblem(Log.WARN, msg);
6845                            bp = null;
6846                        }
6847                    }
6848                }
6849
6850                if (bp == null) {
6851                    bp = new BasePermission(p.info.name, p.info.packageName,
6852                            BasePermission.TYPE_NORMAL);
6853                    permissionMap.put(p.info.name, bp);
6854                }
6855
6856                if (bp.perm == null) {
6857                    if (bp.sourcePackage == null
6858                            || bp.sourcePackage.equals(p.info.packageName)) {
6859                        BasePermission tree = findPermissionTreeLP(p.info.name);
6860                        if (tree == null
6861                                || tree.sourcePackage.equals(p.info.packageName)) {
6862                            bp.packageSetting = pkgSetting;
6863                            bp.perm = p;
6864                            bp.uid = pkg.applicationInfo.uid;
6865                            bp.sourcePackage = p.info.packageName;
6866                            if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6867                                if (r == null) {
6868                                    r = new StringBuilder(256);
6869                                } else {
6870                                    r.append(' ');
6871                                }
6872                                r.append(p.info.name);
6873                            }
6874                        } else {
6875                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6876                                    + p.info.packageName + " ignored: base tree "
6877                                    + tree.name + " is from package "
6878                                    + tree.sourcePackage);
6879                        }
6880                    } else {
6881                        Slog.w(TAG, "Permission " + p.info.name + " from package "
6882                                + p.info.packageName + " ignored: original from "
6883                                + bp.sourcePackage);
6884                    }
6885                } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6886                    if (r == null) {
6887                        r = new StringBuilder(256);
6888                    } else {
6889                        r.append(' ');
6890                    }
6891                    r.append("DUP:");
6892                    r.append(p.info.name);
6893                }
6894                if (bp.perm == p) {
6895                    bp.protectionLevel = p.info.protectionLevel;
6896                }
6897            }
6898
6899            if (r != null) {
6900                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6901            }
6902
6903            N = pkg.instrumentation.size();
6904            r = null;
6905            for (i=0; i<N; i++) {
6906                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6907                a.info.packageName = pkg.applicationInfo.packageName;
6908                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6909                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6910                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6911                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6912                a.info.dataDir = pkg.applicationInfo.dataDir;
6913
6914                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6915                // need other information about the application, like the ABI and what not ?
6916                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6917                mInstrumentation.put(a.getComponentName(), a);
6918                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6919                    if (r == null) {
6920                        r = new StringBuilder(256);
6921                    } else {
6922                        r.append(' ');
6923                    }
6924                    r.append(a.info.name);
6925                }
6926            }
6927            if (r != null) {
6928                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6929            }
6930
6931            if (pkg.protectedBroadcasts != null) {
6932                N = pkg.protectedBroadcasts.size();
6933                for (i=0; i<N; i++) {
6934                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6935                }
6936            }
6937
6938            pkgSetting.setTimeStamp(scanFileTime);
6939
6940            // Create idmap files for pairs of (packages, overlay packages).
6941            // Note: "android", ie framework-res.apk, is handled by native layers.
6942            if (pkg.mOverlayTarget != null) {
6943                // This is an overlay package.
6944                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6945                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6946                        mOverlays.put(pkg.mOverlayTarget,
6947                                new ArrayMap<String, PackageParser.Package>());
6948                    }
6949                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6950                    map.put(pkg.packageName, pkg);
6951                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6952                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6953                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6954                                "scanPackageLI failed to createIdmap");
6955                    }
6956                }
6957            } else if (mOverlays.containsKey(pkg.packageName) &&
6958                    !pkg.packageName.equals("android")) {
6959                // This is a regular package, with one or more known overlay packages.
6960                createIdmapsForPackageLI(pkg);
6961            }
6962        }
6963
6964        return pkg;
6965    }
6966
6967    /**
6968     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6969     * i.e, so that all packages can be run inside a single process if required.
6970     *
6971     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6972     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6973     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6974     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6975     * updating a package that belongs to a shared user.
6976     *
6977     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6978     * adds unnecessary complexity.
6979     */
6980    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6981            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6982        String requiredInstructionSet = null;
6983        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6984            requiredInstructionSet = VMRuntime.getInstructionSet(
6985                     scannedPackage.applicationInfo.primaryCpuAbi);
6986        }
6987
6988        PackageSetting requirer = null;
6989        for (PackageSetting ps : packagesForUser) {
6990            // If packagesForUser contains scannedPackage, we skip it. This will happen
6991            // when scannedPackage is an update of an existing package. Without this check,
6992            // we will never be able to change the ABI of any package belonging to a shared
6993            // user, even if it's compatible with other packages.
6994            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6995                if (ps.primaryCpuAbiString == null) {
6996                    continue;
6997                }
6998
6999                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
7000                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
7001                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
7002                    // this but there's not much we can do.
7003                    String errorMessage = "Instruction set mismatch, "
7004                            + ((requirer == null) ? "[caller]" : requirer)
7005                            + " requires " + requiredInstructionSet + " whereas " + ps
7006                            + " requires " + instructionSet;
7007                    Slog.w(TAG, errorMessage);
7008                }
7009
7010                if (requiredInstructionSet == null) {
7011                    requiredInstructionSet = instructionSet;
7012                    requirer = ps;
7013                }
7014            }
7015        }
7016
7017        if (requiredInstructionSet != null) {
7018            String adjustedAbi;
7019            if (requirer != null) {
7020                // requirer != null implies that either scannedPackage was null or that scannedPackage
7021                // did not require an ABI, in which case we have to adjust scannedPackage to match
7022                // the ABI of the set (which is the same as requirer's ABI)
7023                adjustedAbi = requirer.primaryCpuAbiString;
7024                if (scannedPackage != null) {
7025                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
7026                }
7027            } else {
7028                // requirer == null implies that we're updating all ABIs in the set to
7029                // match scannedPackage.
7030                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
7031            }
7032
7033            for (PackageSetting ps : packagesForUser) {
7034                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
7035                    if (ps.primaryCpuAbiString != null) {
7036                        continue;
7037                    }
7038
7039                    ps.primaryCpuAbiString = adjustedAbi;
7040                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
7041                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
7042                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
7043
7044                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
7045                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
7046                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
7047                            ps.primaryCpuAbiString = null;
7048                            ps.pkg.applicationInfo.primaryCpuAbi = null;
7049                            return;
7050                        } else {
7051                            mInstaller.rmdex(ps.codePathString,
7052                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
7053                        }
7054                    }
7055                }
7056            }
7057        }
7058    }
7059
7060    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
7061        synchronized (mPackages) {
7062            mResolverReplaced = true;
7063            // Set up information for custom user intent resolution activity.
7064            mResolveActivity.applicationInfo = pkg.applicationInfo;
7065            mResolveActivity.name = mCustomResolverComponentName.getClassName();
7066            mResolveActivity.packageName = pkg.applicationInfo.packageName;
7067            mResolveActivity.processName = pkg.applicationInfo.packageName;
7068            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
7069            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
7070                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
7071            mResolveActivity.theme = 0;
7072            mResolveActivity.exported = true;
7073            mResolveActivity.enabled = true;
7074            mResolveInfo.activityInfo = mResolveActivity;
7075            mResolveInfo.priority = 0;
7076            mResolveInfo.preferredOrder = 0;
7077            mResolveInfo.match = 0;
7078            mResolveComponentName = mCustomResolverComponentName;
7079            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
7080                    mResolveComponentName);
7081        }
7082    }
7083
7084    private static String calculateBundledApkRoot(final String codePathString) {
7085        final File codePath = new File(codePathString);
7086        final File codeRoot;
7087        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
7088            codeRoot = Environment.getRootDirectory();
7089        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
7090            codeRoot = Environment.getOemDirectory();
7091        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
7092            codeRoot = Environment.getVendorDirectory();
7093        } else {
7094            // Unrecognized code path; take its top real segment as the apk root:
7095            // e.g. /something/app/blah.apk => /something
7096            try {
7097                File f = codePath.getCanonicalFile();
7098                File parent = f.getParentFile();    // non-null because codePath is a file
7099                File tmp;
7100                while ((tmp = parent.getParentFile()) != null) {
7101                    f = parent;
7102                    parent = tmp;
7103                }
7104                codeRoot = f;
7105                Slog.w(TAG, "Unrecognized code path "
7106                        + codePath + " - using " + codeRoot);
7107            } catch (IOException e) {
7108                // Can't canonicalize the code path -- shenanigans?
7109                Slog.w(TAG, "Can't canonicalize code path " + codePath);
7110                return Environment.getRootDirectory().getPath();
7111            }
7112        }
7113        return codeRoot.getPath();
7114    }
7115
7116    /**
7117     * Derive and set the location of native libraries for the given package,
7118     * which varies depending on where and how the package was installed.
7119     */
7120    private void setNativeLibraryPaths(PackageParser.Package pkg) {
7121        final ApplicationInfo info = pkg.applicationInfo;
7122        final String codePath = pkg.codePath;
7123        final File codeFile = new File(codePath);
7124        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
7125        final boolean asecApp = info.isForwardLocked() || isExternal(info);
7126
7127        info.nativeLibraryRootDir = null;
7128        info.nativeLibraryRootRequiresIsa = false;
7129        info.nativeLibraryDir = null;
7130        info.secondaryNativeLibraryDir = null;
7131
7132        if (isApkFile(codeFile)) {
7133            // Monolithic install
7134            if (bundledApp) {
7135                // If "/system/lib64/apkname" exists, assume that is the per-package
7136                // native library directory to use; otherwise use "/system/lib/apkname".
7137                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
7138                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
7139                        getPrimaryInstructionSet(info));
7140
7141                // This is a bundled system app so choose the path based on the ABI.
7142                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
7143                // is just the default path.
7144                final String apkName = deriveCodePathName(codePath);
7145                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
7146                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
7147                        apkName).getAbsolutePath();
7148
7149                if (info.secondaryCpuAbi != null) {
7150                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
7151                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
7152                            secondaryLibDir, apkName).getAbsolutePath();
7153                }
7154            } else if (asecApp) {
7155                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
7156                        .getAbsolutePath();
7157            } else {
7158                final String apkName = deriveCodePathName(codePath);
7159                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
7160                        .getAbsolutePath();
7161            }
7162
7163            info.nativeLibraryRootRequiresIsa = false;
7164            info.nativeLibraryDir = info.nativeLibraryRootDir;
7165        } else {
7166            // Cluster install
7167            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
7168            info.nativeLibraryRootRequiresIsa = true;
7169
7170            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
7171                    getPrimaryInstructionSet(info)).getAbsolutePath();
7172
7173            if (info.secondaryCpuAbi != null) {
7174                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
7175                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
7176            }
7177        }
7178    }
7179
7180    /**
7181     * Calculate the abis and roots for a bundled app. These can uniquely
7182     * be determined from the contents of the system partition, i.e whether
7183     * it contains 64 or 32 bit shared libraries etc. We do not validate any
7184     * of this information, and instead assume that the system was built
7185     * sensibly.
7186     */
7187    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
7188                                           PackageSetting pkgSetting) {
7189        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
7190
7191        // If "/system/lib64/apkname" exists, assume that is the per-package
7192        // native library directory to use; otherwise use "/system/lib/apkname".
7193        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
7194        setBundledAppAbi(pkg, apkRoot, apkName);
7195        // pkgSetting might be null during rescan following uninstall of updates
7196        // to a bundled app, so accommodate that possibility.  The settings in
7197        // that case will be established later from the parsed package.
7198        //
7199        // If the settings aren't null, sync them up with what we've just derived.
7200        // note that apkRoot isn't stored in the package settings.
7201        if (pkgSetting != null) {
7202            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
7203            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
7204        }
7205    }
7206
7207    /**
7208     * Deduces the ABI of a bundled app and sets the relevant fields on the
7209     * parsed pkg object.
7210     *
7211     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
7212     *        under which system libraries are installed.
7213     * @param apkName the name of the installed package.
7214     */
7215    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
7216        final File codeFile = new File(pkg.codePath);
7217
7218        final boolean has64BitLibs;
7219        final boolean has32BitLibs;
7220        if (isApkFile(codeFile)) {
7221            // Monolithic install
7222            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
7223            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
7224        } else {
7225            // Cluster install
7226            final File rootDir = new File(codeFile, LIB_DIR_NAME);
7227            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
7228                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
7229                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
7230                has64BitLibs = (new File(rootDir, isa)).exists();
7231            } else {
7232                has64BitLibs = false;
7233            }
7234            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7235                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7236                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7237                has32BitLibs = (new File(rootDir, isa)).exists();
7238            } else {
7239                has32BitLibs = false;
7240            }
7241        }
7242
7243        if (has64BitLibs && !has32BitLibs) {
7244            // The package has 64 bit libs, but not 32 bit libs. Its primary
7245            // ABI should be 64 bit. We can safely assume here that the bundled
7246            // native libraries correspond to the most preferred ABI in the list.
7247
7248            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7249            pkg.applicationInfo.secondaryCpuAbi = null;
7250        } else if (has32BitLibs && !has64BitLibs) {
7251            // The package has 32 bit libs but not 64 bit libs. Its primary
7252            // ABI should be 32 bit.
7253
7254            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7255            pkg.applicationInfo.secondaryCpuAbi = null;
7256        } else if (has32BitLibs && has64BitLibs) {
7257            // The application has both 64 and 32 bit bundled libraries. We check
7258            // here that the app declares multiArch support, and warn if it doesn't.
7259            //
7260            // We will be lenient here and record both ABIs. The primary will be the
7261            // ABI that's higher on the list, i.e, a device that's configured to prefer
7262            // 64 bit apps will see a 64 bit primary ABI,
7263
7264            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7265                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7266            }
7267
7268            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7269                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7270                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7271            } else {
7272                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7273                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7274            }
7275        } else {
7276            pkg.applicationInfo.primaryCpuAbi = null;
7277            pkg.applicationInfo.secondaryCpuAbi = null;
7278        }
7279    }
7280
7281    private void killApplication(String pkgName, int appId, String reason) {
7282        // Request the ActivityManager to kill the process(only for existing packages)
7283        // so that we do not end up in a confused state while the user is still using the older
7284        // version of the application while the new one gets installed.
7285        IActivityManager am = ActivityManagerNative.getDefault();
7286        if (am != null) {
7287            try {
7288                am.killApplicationWithAppId(pkgName, appId, reason);
7289            } catch (RemoteException e) {
7290            }
7291        }
7292    }
7293
7294    void removePackageLI(PackageSetting ps, boolean chatty) {
7295        if (DEBUG_INSTALL) {
7296            if (chatty)
7297                Log.d(TAG, "Removing package " + ps.name);
7298        }
7299
7300        // writer
7301        synchronized (mPackages) {
7302            mPackages.remove(ps.name);
7303            final PackageParser.Package pkg = ps.pkg;
7304            if (pkg != null) {
7305                cleanPackageDataStructuresLILPw(pkg, chatty);
7306            }
7307        }
7308    }
7309
7310    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7311        if (DEBUG_INSTALL) {
7312            if (chatty)
7313                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7314        }
7315
7316        // writer
7317        synchronized (mPackages) {
7318            mPackages.remove(pkg.applicationInfo.packageName);
7319            cleanPackageDataStructuresLILPw(pkg, chatty);
7320        }
7321    }
7322
7323    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7324        int N = pkg.providers.size();
7325        StringBuilder r = null;
7326        int i;
7327        for (i=0; i<N; i++) {
7328            PackageParser.Provider p = pkg.providers.get(i);
7329            mProviders.removeProvider(p);
7330            if (p.info.authority == null) {
7331
7332                /* There was another ContentProvider with this authority when
7333                 * this app was installed so this authority is null,
7334                 * Ignore it as we don't have to unregister the provider.
7335                 */
7336                continue;
7337            }
7338            String names[] = p.info.authority.split(";");
7339            for (int j = 0; j < names.length; j++) {
7340                if (mProvidersByAuthority.get(names[j]) == p) {
7341                    mProvidersByAuthority.remove(names[j]);
7342                    if (DEBUG_REMOVE) {
7343                        if (chatty)
7344                            Log.d(TAG, "Unregistered content provider: " + names[j]
7345                                    + ", className = " + p.info.name + ", isSyncable = "
7346                                    + p.info.isSyncable);
7347                    }
7348                }
7349            }
7350            if (DEBUG_REMOVE && chatty) {
7351                if (r == null) {
7352                    r = new StringBuilder(256);
7353                } else {
7354                    r.append(' ');
7355                }
7356                r.append(p.info.name);
7357            }
7358        }
7359        if (r != null) {
7360            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7361        }
7362
7363        N = pkg.services.size();
7364        r = null;
7365        for (i=0; i<N; i++) {
7366            PackageParser.Service s = pkg.services.get(i);
7367            mServices.removeService(s);
7368            if (chatty) {
7369                if (r == null) {
7370                    r = new StringBuilder(256);
7371                } else {
7372                    r.append(' ');
7373                }
7374                r.append(s.info.name);
7375            }
7376        }
7377        if (r != null) {
7378            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7379        }
7380
7381        N = pkg.receivers.size();
7382        r = null;
7383        for (i=0; i<N; i++) {
7384            PackageParser.Activity a = pkg.receivers.get(i);
7385            mReceivers.removeActivity(a, "receiver");
7386            if (DEBUG_REMOVE && chatty) {
7387                if (r == null) {
7388                    r = new StringBuilder(256);
7389                } else {
7390                    r.append(' ');
7391                }
7392                r.append(a.info.name);
7393            }
7394        }
7395        if (r != null) {
7396            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7397        }
7398
7399        N = pkg.activities.size();
7400        r = null;
7401        for (i=0; i<N; i++) {
7402            PackageParser.Activity a = pkg.activities.get(i);
7403            mActivities.removeActivity(a, "activity");
7404            if (DEBUG_REMOVE && chatty) {
7405                if (r == null) {
7406                    r = new StringBuilder(256);
7407                } else {
7408                    r.append(' ');
7409                }
7410                r.append(a.info.name);
7411            }
7412        }
7413        if (r != null) {
7414            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7415        }
7416
7417        N = pkg.permissions.size();
7418        r = null;
7419        for (i=0; i<N; i++) {
7420            PackageParser.Permission p = pkg.permissions.get(i);
7421            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7422            if (bp == null) {
7423                bp = mSettings.mPermissionTrees.get(p.info.name);
7424            }
7425            if (bp != null && bp.perm == p) {
7426                bp.perm = null;
7427                if (DEBUG_REMOVE && chatty) {
7428                    if (r == null) {
7429                        r = new StringBuilder(256);
7430                    } else {
7431                        r.append(' ');
7432                    }
7433                    r.append(p.info.name);
7434                }
7435            }
7436            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7437                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7438                if (appOpPerms != null) {
7439                    appOpPerms.remove(pkg.packageName);
7440                }
7441            }
7442        }
7443        if (r != null) {
7444            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7445        }
7446
7447        N = pkg.requestedPermissions.size();
7448        r = null;
7449        for (i=0; i<N; i++) {
7450            String perm = pkg.requestedPermissions.get(i);
7451            BasePermission bp = mSettings.mPermissions.get(perm);
7452            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7453                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7454                if (appOpPerms != null) {
7455                    appOpPerms.remove(pkg.packageName);
7456                    if (appOpPerms.isEmpty()) {
7457                        mAppOpPermissionPackages.remove(perm);
7458                    }
7459                }
7460            }
7461        }
7462        if (r != null) {
7463            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7464        }
7465
7466        N = pkg.instrumentation.size();
7467        r = null;
7468        for (i=0; i<N; i++) {
7469            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7470            mInstrumentation.remove(a.getComponentName());
7471            if (DEBUG_REMOVE && chatty) {
7472                if (r == null) {
7473                    r = new StringBuilder(256);
7474                } else {
7475                    r.append(' ');
7476                }
7477                r.append(a.info.name);
7478            }
7479        }
7480        if (r != null) {
7481            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7482        }
7483
7484        r = null;
7485        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7486            // Only system apps can hold shared libraries.
7487            if (pkg.libraryNames != null) {
7488                for (i=0; i<pkg.libraryNames.size(); i++) {
7489                    String name = pkg.libraryNames.get(i);
7490                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7491                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7492                        mSharedLibraries.remove(name);
7493                        if (DEBUG_REMOVE && chatty) {
7494                            if (r == null) {
7495                                r = new StringBuilder(256);
7496                            } else {
7497                                r.append(' ');
7498                            }
7499                            r.append(name);
7500                        }
7501                    }
7502                }
7503            }
7504        }
7505        if (r != null) {
7506            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7507        }
7508    }
7509
7510    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7511        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7512            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7513                return true;
7514            }
7515        }
7516        return false;
7517    }
7518
7519    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7520    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7521    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7522
7523    private void updatePermissionsLPw(String changingPkg,
7524            PackageParser.Package pkgInfo, int flags) {
7525        // Make sure there are no dangling permission trees.
7526        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7527        while (it.hasNext()) {
7528            final BasePermission bp = it.next();
7529            if (bp.packageSetting == null) {
7530                // We may not yet have parsed the package, so just see if
7531                // we still know about its settings.
7532                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7533            }
7534            if (bp.packageSetting == null) {
7535                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7536                        + " from package " + bp.sourcePackage);
7537                it.remove();
7538            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7539                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7540                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7541                            + " from package " + bp.sourcePackage);
7542                    flags |= UPDATE_PERMISSIONS_ALL;
7543                    it.remove();
7544                }
7545            }
7546        }
7547
7548        // Make sure all dynamic permissions have been assigned to a package,
7549        // and make sure there are no dangling permissions.
7550        it = mSettings.mPermissions.values().iterator();
7551        while (it.hasNext()) {
7552            final BasePermission bp = it.next();
7553            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7554                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7555                        + bp.name + " pkg=" + bp.sourcePackage
7556                        + " info=" + bp.pendingInfo);
7557                if (bp.packageSetting == null && bp.pendingInfo != null) {
7558                    final BasePermission tree = findPermissionTreeLP(bp.name);
7559                    if (tree != null && tree.perm != null) {
7560                        bp.packageSetting = tree.packageSetting;
7561                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7562                                new PermissionInfo(bp.pendingInfo));
7563                        bp.perm.info.packageName = tree.perm.info.packageName;
7564                        bp.perm.info.name = bp.name;
7565                        bp.uid = tree.uid;
7566                    }
7567                }
7568            }
7569            if (bp.packageSetting == null) {
7570                // We may not yet have parsed the package, so just see if
7571                // we still know about its settings.
7572                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7573            }
7574            if (bp.packageSetting == null) {
7575                Slog.w(TAG, "Removing dangling permission: " + bp.name
7576                        + " from package " + bp.sourcePackage);
7577                it.remove();
7578            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7579                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7580                    Slog.i(TAG, "Removing old permission: " + bp.name
7581                            + " from package " + bp.sourcePackage);
7582                    flags |= UPDATE_PERMISSIONS_ALL;
7583                    it.remove();
7584                }
7585            }
7586        }
7587
7588        // Now update the permissions for all packages, in particular
7589        // replace the granted permissions of the system packages.
7590        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7591            for (PackageParser.Package pkg : mPackages.values()) {
7592                if (pkg != pkgInfo) {
7593                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7594                            changingPkg);
7595                }
7596            }
7597        }
7598
7599        if (pkgInfo != null) {
7600            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7601        }
7602    }
7603
7604    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7605            String packageOfInterest) {
7606        // IMPORTANT: There are two types of permissions: install and runtime.
7607        // Install time permissions are granted when the app is installed to
7608        // all device users and users added in the future. Runtime permissions
7609        // are granted at runtime explicitly to specific users. Normal and signature
7610        // protected permissions are install time permissions. Dangerous permissions
7611        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7612        // otherwise they are runtime permissions. This function does not manage
7613        // runtime permissions except for the case an app targeting Lollipop MR1
7614        // being upgraded to target a newer SDK, in which case dangerous permissions
7615        // are transformed from install time to runtime ones.
7616
7617        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7618        if (ps == null) {
7619            return;
7620        }
7621
7622        PermissionsState permissionsState = ps.getPermissionsState();
7623        PermissionsState origPermissions = permissionsState;
7624
7625        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7626
7627        int[] upgradeUserIds = EMPTY_INT_ARRAY;
7628        int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY;
7629
7630        boolean changedInstallPermission = false;
7631
7632        if (replace) {
7633            ps.installPermissionsFixed = false;
7634            if (!ps.isSharedUser()) {
7635                origPermissions = new PermissionsState(permissionsState);
7636                permissionsState.reset();
7637            }
7638        }
7639
7640        permissionsState.setGlobalGids(mGlobalGids);
7641
7642        final int N = pkg.requestedPermissions.size();
7643        for (int i=0; i<N; i++) {
7644            final String name = pkg.requestedPermissions.get(i);
7645            final BasePermission bp = mSettings.mPermissions.get(name);
7646
7647            if (DEBUG_INSTALL) {
7648                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7649            }
7650
7651            if (bp == null || bp.packageSetting == null) {
7652                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7653                    Slog.w(TAG, "Unknown permission " + name
7654                            + " in package " + pkg.packageName);
7655                }
7656                continue;
7657            }
7658
7659            final String perm = bp.name;
7660            boolean allowedSig = false;
7661            int grant = GRANT_DENIED;
7662
7663            // Keep track of app op permissions.
7664            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7665                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7666                if (pkgs == null) {
7667                    pkgs = new ArraySet<>();
7668                    mAppOpPermissionPackages.put(bp.name, pkgs);
7669                }
7670                pkgs.add(pkg.packageName);
7671            }
7672
7673            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7674            switch (level) {
7675                case PermissionInfo.PROTECTION_NORMAL: {
7676                    // For all apps normal permissions are install time ones.
7677                    grant = GRANT_INSTALL;
7678                } break;
7679
7680                case PermissionInfo.PROTECTION_DANGEROUS: {
7681                    if (pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7682                        // For legacy apps dangerous permissions are install time ones.
7683                        grant = GRANT_INSTALL;
7684                    } else if (ps.isSystem()) {
7685                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7686                        if (origPermissions.hasInstallPermission(bp.name)) {
7687                            // If a system app had an install permission, then the app was
7688                            // upgraded and we grant the permissions as runtime to all users.
7689                            grant = GRANT_UPGRADE;
7690                            upgradeUserIds = currentUserIds;
7691                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7692                            // If users changed since the last permissions update for a
7693                            // system app, we grant the permission as runtime to the new users.
7694                            grant = GRANT_UPGRADE;
7695                            upgradeUserIds = currentUserIds;
7696                            for (int userId : updatedUserIds) {
7697                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7698                            }
7699                        } else {
7700                            // Otherwise, we grant the permission as runtime if the app
7701                            // already had it, i.e. we preserve runtime permissions.
7702                            grant = GRANT_RUNTIME;
7703                        }
7704                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7705                        // For legacy apps that became modern, install becomes runtime.
7706                        grant = GRANT_UPGRADE;
7707                        upgradeUserIds = currentUserIds;
7708                    } else if (replace) {
7709                        // For upgraded modern apps keep runtime permissions unchanged.
7710                        grant = GRANT_RUNTIME;
7711                    }
7712                } break;
7713
7714                case PermissionInfo.PROTECTION_SIGNATURE: {
7715                    // For all apps signature permissions are install time ones.
7716                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7717                    if (allowedSig) {
7718                        grant = GRANT_INSTALL;
7719                    }
7720                } break;
7721            }
7722
7723            if (DEBUG_INSTALL) {
7724                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7725            }
7726
7727            if (grant != GRANT_DENIED) {
7728                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7729                    // If this is an existing, non-system package, then
7730                    // we can't add any new permissions to it.
7731                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7732                        // Except...  if this is a permission that was added
7733                        // to the platform (note: need to only do this when
7734                        // updating the platform).
7735                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7736                            grant = GRANT_DENIED;
7737                        }
7738                    }
7739                }
7740
7741                switch (grant) {
7742                    case GRANT_INSTALL: {
7743                        // Grant an install permission.
7744                        if (permissionsState.grantInstallPermission(bp) !=
7745                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7746                            changedInstallPermission = true;
7747                        }
7748                    } break;
7749
7750                    case GRANT_RUNTIME: {
7751                        // Grant previously granted runtime permissions.
7752                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7753                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7754                                PermissionState permissionState = origPermissions
7755                                        .getRuntimePermissionState(bp.name, userId);
7756                                final int flags = permissionState.getFlags();
7757                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7758                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7759                                    // If we cannot put the permission as it was, we have to write.
7760                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7761                                            changedRuntimePermissionUserIds, userId);
7762                                } else {
7763                                    // Propagate the permission flags.
7764                                    permissionsState.updatePermissionFlags(bp, userId,
7765                                            flags, flags);
7766                                }
7767                            }
7768                        }
7769                    } break;
7770
7771                    case GRANT_UPGRADE: {
7772                        // Grant runtime permissions for a previously held install permission.
7773                        PermissionState permissionState = origPermissions
7774                                .getInstallPermissionState(bp.name);
7775                        final int flags = permissionState != null ? permissionState.getFlags() : 0;
7776
7777                        origPermissions.revokeInstallPermission(bp);
7778                        // We will be transferring the permission flags, so clear them.
7779                        origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL,
7780                                PackageManager.MASK_PERMISSION_FLAGS, 0);
7781
7782                        // If the permission is not to be promoted to runtime we ignore it and
7783                        // also its other flags as they are not applicable to install permissions.
7784                        if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) {
7785                            for (int userId : upgradeUserIds) {
7786                                if (permissionsState.grantRuntimePermission(bp, userId) !=
7787                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7788                                    // Transfer the permission flags.
7789                                    permissionsState.updatePermissionFlags(bp, userId,
7790                                            flags, flags);
7791                                    // If we granted the permission, we have to write.
7792                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7793                                            changedRuntimePermissionUserIds, userId);
7794                                }
7795                            }
7796                        }
7797                    } break;
7798
7799                    default: {
7800                        if (packageOfInterest == null
7801                                || packageOfInterest.equals(pkg.packageName)) {
7802                            Slog.w(TAG, "Not granting permission " + perm
7803                                    + " to package " + pkg.packageName
7804                                    + " because it was previously installed without");
7805                        }
7806                    } break;
7807                }
7808            } else {
7809                if (permissionsState.revokeInstallPermission(bp) !=
7810                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7811                    // Also drop the permission flags.
7812                    permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL,
7813                            PackageManager.MASK_PERMISSION_FLAGS, 0);
7814                    changedInstallPermission = true;
7815                    Slog.i(TAG, "Un-granting permission " + perm
7816                            + " from package " + pkg.packageName
7817                            + " (protectionLevel=" + bp.protectionLevel
7818                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7819                            + ")");
7820                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7821                    // Don't print warning for app op permissions, since it is fine for them
7822                    // not to be granted, there is a UI for the user to decide.
7823                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7824                        Slog.w(TAG, "Not granting permission " + perm
7825                                + " to package " + pkg.packageName
7826                                + " (protectionLevel=" + bp.protectionLevel
7827                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7828                                + ")");
7829                    }
7830                }
7831            }
7832        }
7833
7834        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7835                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7836            // This is the first that we have heard about this package, so the
7837            // permissions we have now selected are fixed until explicitly
7838            // changed.
7839            ps.installPermissionsFixed = true;
7840        }
7841
7842        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7843
7844        // Persist the runtime permissions state for users with changes.
7845        for (int userId : changedRuntimePermissionUserIds) {
7846            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7847        }
7848    }
7849
7850    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7851        boolean allowed = false;
7852        final int NP = PackageParser.NEW_PERMISSIONS.length;
7853        for (int ip=0; ip<NP; ip++) {
7854            final PackageParser.NewPermissionInfo npi
7855                    = PackageParser.NEW_PERMISSIONS[ip];
7856            if (npi.name.equals(perm)
7857                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7858                allowed = true;
7859                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7860                        + pkg.packageName);
7861                break;
7862            }
7863        }
7864        return allowed;
7865    }
7866
7867    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7868            BasePermission bp, PermissionsState origPermissions) {
7869        boolean allowed;
7870        allowed = (compareSignatures(
7871                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7872                        == PackageManager.SIGNATURE_MATCH)
7873                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7874                        == PackageManager.SIGNATURE_MATCH);
7875        if (!allowed && (bp.protectionLevel
7876                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7877            if (isSystemApp(pkg)) {
7878                // For updated system applications, a system permission
7879                // is granted only if it had been defined by the original application.
7880                if (pkg.isUpdatedSystemApp()) {
7881                    final PackageSetting sysPs = mSettings
7882                            .getDisabledSystemPkgLPr(pkg.packageName);
7883                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7884                        // If the original was granted this permission, we take
7885                        // that grant decision as read and propagate it to the
7886                        // update.
7887                        if (sysPs.isPrivileged()) {
7888                            allowed = true;
7889                        }
7890                    } else {
7891                        // The system apk may have been updated with an older
7892                        // version of the one on the data partition, but which
7893                        // granted a new system permission that it didn't have
7894                        // before.  In this case we do want to allow the app to
7895                        // now get the new permission if the ancestral apk is
7896                        // privileged to get it.
7897                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7898                            for (int j=0;
7899                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7900                                if (perm.equals(
7901                                        sysPs.pkg.requestedPermissions.get(j))) {
7902                                    allowed = true;
7903                                    break;
7904                                }
7905                            }
7906                        }
7907                    }
7908                } else {
7909                    allowed = isPrivilegedApp(pkg);
7910                }
7911            }
7912        }
7913        if (!allowed && (bp.protectionLevel
7914                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7915            // For development permissions, a development permission
7916            // is granted only if it was already granted.
7917            allowed = origPermissions.hasInstallPermission(perm);
7918        }
7919        return allowed;
7920    }
7921
7922    final class ActivityIntentResolver
7923            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7924        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7925                boolean defaultOnly, int userId) {
7926            if (!sUserManager.exists(userId)) return null;
7927            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7928            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7929        }
7930
7931        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7932                int userId) {
7933            if (!sUserManager.exists(userId)) return null;
7934            mFlags = flags;
7935            return super.queryIntent(intent, resolvedType,
7936                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7937        }
7938
7939        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7940                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7941            if (!sUserManager.exists(userId)) return null;
7942            if (packageActivities == null) {
7943                return null;
7944            }
7945            mFlags = flags;
7946            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7947            final int N = packageActivities.size();
7948            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7949                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7950
7951            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7952            for (int i = 0; i < N; ++i) {
7953                intentFilters = packageActivities.get(i).intents;
7954                if (intentFilters != null && intentFilters.size() > 0) {
7955                    PackageParser.ActivityIntentInfo[] array =
7956                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7957                    intentFilters.toArray(array);
7958                    listCut.add(array);
7959                }
7960            }
7961            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7962        }
7963
7964        public final void addActivity(PackageParser.Activity a, String type) {
7965            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7966            mActivities.put(a.getComponentName(), a);
7967            if (DEBUG_SHOW_INFO)
7968                Log.v(
7969                TAG, "  " + type + " " +
7970                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7971            if (DEBUG_SHOW_INFO)
7972                Log.v(TAG, "    Class=" + a.info.name);
7973            final int NI = a.intents.size();
7974            for (int j=0; j<NI; j++) {
7975                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7976                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7977                    intent.setPriority(0);
7978                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7979                            + a.className + " with priority > 0, forcing to 0");
7980                }
7981                if (DEBUG_SHOW_INFO) {
7982                    Log.v(TAG, "    IntentFilter:");
7983                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7984                }
7985                if (!intent.debugCheck()) {
7986                    Log.w(TAG, "==> For Activity " + a.info.name);
7987                }
7988                addFilter(intent);
7989            }
7990        }
7991
7992        public final void removeActivity(PackageParser.Activity a, String type) {
7993            mActivities.remove(a.getComponentName());
7994            if (DEBUG_SHOW_INFO) {
7995                Log.v(TAG, "  " + type + " "
7996                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7997                                : a.info.name) + ":");
7998                Log.v(TAG, "    Class=" + a.info.name);
7999            }
8000            final int NI = a.intents.size();
8001            for (int j=0; j<NI; j++) {
8002                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
8003                if (DEBUG_SHOW_INFO) {
8004                    Log.v(TAG, "    IntentFilter:");
8005                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8006                }
8007                removeFilter(intent);
8008            }
8009        }
8010
8011        @Override
8012        protected boolean allowFilterResult(
8013                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
8014            ActivityInfo filterAi = filter.activity.info;
8015            for (int i=dest.size()-1; i>=0; i--) {
8016                ActivityInfo destAi = dest.get(i).activityInfo;
8017                if (destAi.name == filterAi.name
8018                        && destAi.packageName == filterAi.packageName) {
8019                    return false;
8020                }
8021            }
8022            return true;
8023        }
8024
8025        @Override
8026        protected ActivityIntentInfo[] newArray(int size) {
8027            return new ActivityIntentInfo[size];
8028        }
8029
8030        @Override
8031        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
8032            if (!sUserManager.exists(userId)) return true;
8033            PackageParser.Package p = filter.activity.owner;
8034            if (p != null) {
8035                PackageSetting ps = (PackageSetting)p.mExtras;
8036                if (ps != null) {
8037                    // System apps are never considered stopped for purposes of
8038                    // filtering, because there may be no way for the user to
8039                    // actually re-launch them.
8040                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
8041                            && ps.getStopped(userId);
8042                }
8043            }
8044            return false;
8045        }
8046
8047        @Override
8048        protected boolean isPackageForFilter(String packageName,
8049                PackageParser.ActivityIntentInfo info) {
8050            return packageName.equals(info.activity.owner.packageName);
8051        }
8052
8053        @Override
8054        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
8055                int match, int userId) {
8056            if (!sUserManager.exists(userId)) return null;
8057            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
8058                return null;
8059            }
8060            final PackageParser.Activity activity = info.activity;
8061            if (mSafeMode && (activity.info.applicationInfo.flags
8062                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8063                return null;
8064            }
8065            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
8066            if (ps == null) {
8067                return null;
8068            }
8069            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
8070                    ps.readUserState(userId), userId);
8071            if (ai == null) {
8072                return null;
8073            }
8074            final ResolveInfo res = new ResolveInfo();
8075            res.activityInfo = ai;
8076            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8077                res.filter = info;
8078            }
8079            if (info != null) {
8080                res.handleAllWebDataURI = info.handleAllWebDataURI();
8081            }
8082            res.priority = info.getPriority();
8083            res.preferredOrder = activity.owner.mPreferredOrder;
8084            //System.out.println("Result: " + res.activityInfo.className +
8085            //                   " = " + res.priority);
8086            res.match = match;
8087            res.isDefault = info.hasDefault;
8088            res.labelRes = info.labelRes;
8089            res.nonLocalizedLabel = info.nonLocalizedLabel;
8090            if (userNeedsBadging(userId)) {
8091                res.noResourceId = true;
8092            } else {
8093                res.icon = info.icon;
8094            }
8095            res.system = res.activityInfo.applicationInfo.isSystemApp();
8096            return res;
8097        }
8098
8099        @Override
8100        protected void sortResults(List<ResolveInfo> results) {
8101            Collections.sort(results, mResolvePrioritySorter);
8102        }
8103
8104        @Override
8105        protected void dumpFilter(PrintWriter out, String prefix,
8106                PackageParser.ActivityIntentInfo filter) {
8107            out.print(prefix); out.print(
8108                    Integer.toHexString(System.identityHashCode(filter.activity)));
8109                    out.print(' ');
8110                    filter.activity.printComponentShortName(out);
8111                    out.print(" filter ");
8112                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8113        }
8114
8115        @Override
8116        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
8117            return filter.activity;
8118        }
8119
8120        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8121            PackageParser.Activity activity = (PackageParser.Activity)label;
8122            out.print(prefix); out.print(
8123                    Integer.toHexString(System.identityHashCode(activity)));
8124                    out.print(' ');
8125                    activity.printComponentShortName(out);
8126            if (count > 1) {
8127                out.print(" ("); out.print(count); out.print(" filters)");
8128            }
8129            out.println();
8130        }
8131
8132//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8133//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8134//            final List<ResolveInfo> retList = Lists.newArrayList();
8135//            while (i.hasNext()) {
8136//                final ResolveInfo resolveInfo = i.next();
8137//                if (isEnabledLP(resolveInfo.activityInfo)) {
8138//                    retList.add(resolveInfo);
8139//                }
8140//            }
8141//            return retList;
8142//        }
8143
8144        // Keys are String (activity class name), values are Activity.
8145        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
8146                = new ArrayMap<ComponentName, PackageParser.Activity>();
8147        private int mFlags;
8148    }
8149
8150    private final class ServiceIntentResolver
8151            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
8152        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8153                boolean defaultOnly, int userId) {
8154            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8155            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8156        }
8157
8158        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8159                int userId) {
8160            if (!sUserManager.exists(userId)) return null;
8161            mFlags = flags;
8162            return super.queryIntent(intent, resolvedType,
8163                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8164        }
8165
8166        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8167                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
8168            if (!sUserManager.exists(userId)) return null;
8169            if (packageServices == null) {
8170                return null;
8171            }
8172            mFlags = flags;
8173            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
8174            final int N = packageServices.size();
8175            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
8176                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
8177
8178            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
8179            for (int i = 0; i < N; ++i) {
8180                intentFilters = packageServices.get(i).intents;
8181                if (intentFilters != null && intentFilters.size() > 0) {
8182                    PackageParser.ServiceIntentInfo[] array =
8183                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
8184                    intentFilters.toArray(array);
8185                    listCut.add(array);
8186                }
8187            }
8188            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8189        }
8190
8191        public final void addService(PackageParser.Service s) {
8192            mServices.put(s.getComponentName(), s);
8193            if (DEBUG_SHOW_INFO) {
8194                Log.v(TAG, "  "
8195                        + (s.info.nonLocalizedLabel != null
8196                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8197                Log.v(TAG, "    Class=" + s.info.name);
8198            }
8199            final int NI = s.intents.size();
8200            int j;
8201            for (j=0; j<NI; j++) {
8202                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8203                if (DEBUG_SHOW_INFO) {
8204                    Log.v(TAG, "    IntentFilter:");
8205                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8206                }
8207                if (!intent.debugCheck()) {
8208                    Log.w(TAG, "==> For Service " + s.info.name);
8209                }
8210                addFilter(intent);
8211            }
8212        }
8213
8214        public final void removeService(PackageParser.Service s) {
8215            mServices.remove(s.getComponentName());
8216            if (DEBUG_SHOW_INFO) {
8217                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
8218                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
8219                Log.v(TAG, "    Class=" + s.info.name);
8220            }
8221            final int NI = s.intents.size();
8222            int j;
8223            for (j=0; j<NI; j++) {
8224                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
8225                if (DEBUG_SHOW_INFO) {
8226                    Log.v(TAG, "    IntentFilter:");
8227                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8228                }
8229                removeFilter(intent);
8230            }
8231        }
8232
8233        @Override
8234        protected boolean allowFilterResult(
8235                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
8236            ServiceInfo filterSi = filter.service.info;
8237            for (int i=dest.size()-1; i>=0; i--) {
8238                ServiceInfo destAi = dest.get(i).serviceInfo;
8239                if (destAi.name == filterSi.name
8240                        && destAi.packageName == filterSi.packageName) {
8241                    return false;
8242                }
8243            }
8244            return true;
8245        }
8246
8247        @Override
8248        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
8249            return new PackageParser.ServiceIntentInfo[size];
8250        }
8251
8252        @Override
8253        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8254            if (!sUserManager.exists(userId)) return true;
8255            PackageParser.Package p = filter.service.owner;
8256            if (p != null) {
8257                PackageSetting ps = (PackageSetting)p.mExtras;
8258                if (ps != null) {
8259                    // System apps are never considered stopped for purposes of
8260                    // filtering, because there may be no way for the user to
8261                    // actually re-launch them.
8262                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8263                            && ps.getStopped(userId);
8264                }
8265            }
8266            return false;
8267        }
8268
8269        @Override
8270        protected boolean isPackageForFilter(String packageName,
8271                PackageParser.ServiceIntentInfo info) {
8272            return packageName.equals(info.service.owner.packageName);
8273        }
8274
8275        @Override
8276        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8277                int match, int userId) {
8278            if (!sUserManager.exists(userId)) return null;
8279            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8280            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8281                return null;
8282            }
8283            final PackageParser.Service service = info.service;
8284            if (mSafeMode && (service.info.applicationInfo.flags
8285                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8286                return null;
8287            }
8288            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8289            if (ps == null) {
8290                return null;
8291            }
8292            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8293                    ps.readUserState(userId), userId);
8294            if (si == null) {
8295                return null;
8296            }
8297            final ResolveInfo res = new ResolveInfo();
8298            res.serviceInfo = si;
8299            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8300                res.filter = filter;
8301            }
8302            res.priority = info.getPriority();
8303            res.preferredOrder = service.owner.mPreferredOrder;
8304            res.match = match;
8305            res.isDefault = info.hasDefault;
8306            res.labelRes = info.labelRes;
8307            res.nonLocalizedLabel = info.nonLocalizedLabel;
8308            res.icon = info.icon;
8309            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8310            return res;
8311        }
8312
8313        @Override
8314        protected void sortResults(List<ResolveInfo> results) {
8315            Collections.sort(results, mResolvePrioritySorter);
8316        }
8317
8318        @Override
8319        protected void dumpFilter(PrintWriter out, String prefix,
8320                PackageParser.ServiceIntentInfo filter) {
8321            out.print(prefix); out.print(
8322                    Integer.toHexString(System.identityHashCode(filter.service)));
8323                    out.print(' ');
8324                    filter.service.printComponentShortName(out);
8325                    out.print(" filter ");
8326                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8327        }
8328
8329        @Override
8330        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8331            return filter.service;
8332        }
8333
8334        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8335            PackageParser.Service service = (PackageParser.Service)label;
8336            out.print(prefix); out.print(
8337                    Integer.toHexString(System.identityHashCode(service)));
8338                    out.print(' ');
8339                    service.printComponentShortName(out);
8340            if (count > 1) {
8341                out.print(" ("); out.print(count); out.print(" filters)");
8342            }
8343            out.println();
8344        }
8345
8346//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8347//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8348//            final List<ResolveInfo> retList = Lists.newArrayList();
8349//            while (i.hasNext()) {
8350//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8351//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8352//                    retList.add(resolveInfo);
8353//                }
8354//            }
8355//            return retList;
8356//        }
8357
8358        // Keys are String (activity class name), values are Activity.
8359        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8360                = new ArrayMap<ComponentName, PackageParser.Service>();
8361        private int mFlags;
8362    };
8363
8364    private final class ProviderIntentResolver
8365            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8366        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8367                boolean defaultOnly, int userId) {
8368            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8369            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8370        }
8371
8372        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8373                int userId) {
8374            if (!sUserManager.exists(userId))
8375                return null;
8376            mFlags = flags;
8377            return super.queryIntent(intent, resolvedType,
8378                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8379        }
8380
8381        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8382                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8383            if (!sUserManager.exists(userId))
8384                return null;
8385            if (packageProviders == null) {
8386                return null;
8387            }
8388            mFlags = flags;
8389            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8390            final int N = packageProviders.size();
8391            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8392                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8393
8394            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8395            for (int i = 0; i < N; ++i) {
8396                intentFilters = packageProviders.get(i).intents;
8397                if (intentFilters != null && intentFilters.size() > 0) {
8398                    PackageParser.ProviderIntentInfo[] array =
8399                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8400                    intentFilters.toArray(array);
8401                    listCut.add(array);
8402                }
8403            }
8404            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8405        }
8406
8407        public final void addProvider(PackageParser.Provider p) {
8408            if (mProviders.containsKey(p.getComponentName())) {
8409                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8410                return;
8411            }
8412
8413            mProviders.put(p.getComponentName(), p);
8414            if (DEBUG_SHOW_INFO) {
8415                Log.v(TAG, "  "
8416                        + (p.info.nonLocalizedLabel != null
8417                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8418                Log.v(TAG, "    Class=" + p.info.name);
8419            }
8420            final int NI = p.intents.size();
8421            int j;
8422            for (j = 0; j < NI; j++) {
8423                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8424                if (DEBUG_SHOW_INFO) {
8425                    Log.v(TAG, "    IntentFilter:");
8426                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8427                }
8428                if (!intent.debugCheck()) {
8429                    Log.w(TAG, "==> For Provider " + p.info.name);
8430                }
8431                addFilter(intent);
8432            }
8433        }
8434
8435        public final void removeProvider(PackageParser.Provider p) {
8436            mProviders.remove(p.getComponentName());
8437            if (DEBUG_SHOW_INFO) {
8438                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8439                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8440                Log.v(TAG, "    Class=" + p.info.name);
8441            }
8442            final int NI = p.intents.size();
8443            int j;
8444            for (j = 0; j < NI; j++) {
8445                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8446                if (DEBUG_SHOW_INFO) {
8447                    Log.v(TAG, "    IntentFilter:");
8448                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8449                }
8450                removeFilter(intent);
8451            }
8452        }
8453
8454        @Override
8455        protected boolean allowFilterResult(
8456                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8457            ProviderInfo filterPi = filter.provider.info;
8458            for (int i = dest.size() - 1; i >= 0; i--) {
8459                ProviderInfo destPi = dest.get(i).providerInfo;
8460                if (destPi.name == filterPi.name
8461                        && destPi.packageName == filterPi.packageName) {
8462                    return false;
8463                }
8464            }
8465            return true;
8466        }
8467
8468        @Override
8469        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8470            return new PackageParser.ProviderIntentInfo[size];
8471        }
8472
8473        @Override
8474        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8475            if (!sUserManager.exists(userId))
8476                return true;
8477            PackageParser.Package p = filter.provider.owner;
8478            if (p != null) {
8479                PackageSetting ps = (PackageSetting) p.mExtras;
8480                if (ps != null) {
8481                    // System apps are never considered stopped for purposes of
8482                    // filtering, because there may be no way for the user to
8483                    // actually re-launch them.
8484                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8485                            && ps.getStopped(userId);
8486                }
8487            }
8488            return false;
8489        }
8490
8491        @Override
8492        protected boolean isPackageForFilter(String packageName,
8493                PackageParser.ProviderIntentInfo info) {
8494            return packageName.equals(info.provider.owner.packageName);
8495        }
8496
8497        @Override
8498        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8499                int match, int userId) {
8500            if (!sUserManager.exists(userId))
8501                return null;
8502            final PackageParser.ProviderIntentInfo info = filter;
8503            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8504                return null;
8505            }
8506            final PackageParser.Provider provider = info.provider;
8507            if (mSafeMode && (provider.info.applicationInfo.flags
8508                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8509                return null;
8510            }
8511            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8512            if (ps == null) {
8513                return null;
8514            }
8515            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8516                    ps.readUserState(userId), userId);
8517            if (pi == null) {
8518                return null;
8519            }
8520            final ResolveInfo res = new ResolveInfo();
8521            res.providerInfo = pi;
8522            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8523                res.filter = filter;
8524            }
8525            res.priority = info.getPriority();
8526            res.preferredOrder = provider.owner.mPreferredOrder;
8527            res.match = match;
8528            res.isDefault = info.hasDefault;
8529            res.labelRes = info.labelRes;
8530            res.nonLocalizedLabel = info.nonLocalizedLabel;
8531            res.icon = info.icon;
8532            res.system = res.providerInfo.applicationInfo.isSystemApp();
8533            return res;
8534        }
8535
8536        @Override
8537        protected void sortResults(List<ResolveInfo> results) {
8538            Collections.sort(results, mResolvePrioritySorter);
8539        }
8540
8541        @Override
8542        protected void dumpFilter(PrintWriter out, String prefix,
8543                PackageParser.ProviderIntentInfo filter) {
8544            out.print(prefix);
8545            out.print(
8546                    Integer.toHexString(System.identityHashCode(filter.provider)));
8547            out.print(' ');
8548            filter.provider.printComponentShortName(out);
8549            out.print(" filter ");
8550            out.println(Integer.toHexString(System.identityHashCode(filter)));
8551        }
8552
8553        @Override
8554        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8555            return filter.provider;
8556        }
8557
8558        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8559            PackageParser.Provider provider = (PackageParser.Provider)label;
8560            out.print(prefix); out.print(
8561                    Integer.toHexString(System.identityHashCode(provider)));
8562                    out.print(' ');
8563                    provider.printComponentShortName(out);
8564            if (count > 1) {
8565                out.print(" ("); out.print(count); out.print(" filters)");
8566            }
8567            out.println();
8568        }
8569
8570        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8571                = new ArrayMap<ComponentName, PackageParser.Provider>();
8572        private int mFlags;
8573    };
8574
8575    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8576            new Comparator<ResolveInfo>() {
8577        public int compare(ResolveInfo r1, ResolveInfo r2) {
8578            int v1 = r1.priority;
8579            int v2 = r2.priority;
8580            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8581            if (v1 != v2) {
8582                return (v1 > v2) ? -1 : 1;
8583            }
8584            v1 = r1.preferredOrder;
8585            v2 = r2.preferredOrder;
8586            if (v1 != v2) {
8587                return (v1 > v2) ? -1 : 1;
8588            }
8589            if (r1.isDefault != r2.isDefault) {
8590                return r1.isDefault ? -1 : 1;
8591            }
8592            v1 = r1.match;
8593            v2 = r2.match;
8594            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8595            if (v1 != v2) {
8596                return (v1 > v2) ? -1 : 1;
8597            }
8598            if (r1.system != r2.system) {
8599                return r1.system ? -1 : 1;
8600            }
8601            return 0;
8602        }
8603    };
8604
8605    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8606            new Comparator<ProviderInfo>() {
8607        public int compare(ProviderInfo p1, ProviderInfo p2) {
8608            final int v1 = p1.initOrder;
8609            final int v2 = p2.initOrder;
8610            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8611        }
8612    };
8613
8614    final void sendPackageBroadcast(final String action, final String pkg,
8615            final Bundle extras, final String targetPkg, final IIntentReceiver finishedReceiver,
8616            final int[] userIds) {
8617        mHandler.post(new Runnable() {
8618            @Override
8619            public void run() {
8620                try {
8621                    final IActivityManager am = ActivityManagerNative.getDefault();
8622                    if (am == null) return;
8623                    final int[] resolvedUserIds;
8624                    if (userIds == null) {
8625                        resolvedUserIds = am.getRunningUserIds();
8626                    } else {
8627                        resolvedUserIds = userIds;
8628                    }
8629                    for (int id : resolvedUserIds) {
8630                        final Intent intent = new Intent(action,
8631                                pkg != null ? Uri.fromParts("package", pkg, null) : null);
8632                        if (extras != null) {
8633                            intent.putExtras(extras);
8634                        }
8635                        if (targetPkg != null) {
8636                            intent.setPackage(targetPkg);
8637                        }
8638                        // Modify the UID when posting to other users
8639                        int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8640                        if (uid > 0 && UserHandle.getUserId(uid) != id) {
8641                            uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8642                            intent.putExtra(Intent.EXTRA_UID, uid);
8643                        }
8644                        intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8645                        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8646                        if (DEBUG_BROADCASTS) {
8647                            RuntimeException here = new RuntimeException("here");
8648                            here.fillInStackTrace();
8649                            Slog.d(TAG, "Sending to user " + id + ": "
8650                                    + intent.toShortString(false, true, false, false)
8651                                    + " " + intent.getExtras(), here);
8652                        }
8653                        am.broadcastIntent(null, intent, null, finishedReceiver,
8654                                0, null, null, null, android.app.AppOpsManager.OP_NONE,
8655                                finishedReceiver != null, false, id);
8656                    }
8657                } catch (RemoteException ex) {
8658                }
8659            }
8660        });
8661    }
8662
8663    /**
8664     * Check if the external storage media is available. This is true if there
8665     * is a mounted external storage medium or if the external storage is
8666     * emulated.
8667     */
8668    private boolean isExternalMediaAvailable() {
8669        return mMediaMounted || Environment.isExternalStorageEmulated();
8670    }
8671
8672    @Override
8673    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8674        // writer
8675        synchronized (mPackages) {
8676            if (!isExternalMediaAvailable()) {
8677                // If the external storage is no longer mounted at this point,
8678                // the caller may not have been able to delete all of this
8679                // packages files and can not delete any more.  Bail.
8680                return null;
8681            }
8682            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8683            if (lastPackage != null) {
8684                pkgs.remove(lastPackage);
8685            }
8686            if (pkgs.size() > 0) {
8687                return pkgs.get(0);
8688            }
8689        }
8690        return null;
8691    }
8692
8693    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8694        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8695                userId, andCode ? 1 : 0, packageName);
8696        if (mSystemReady) {
8697            msg.sendToTarget();
8698        } else {
8699            if (mPostSystemReadyMessages == null) {
8700                mPostSystemReadyMessages = new ArrayList<>();
8701            }
8702            mPostSystemReadyMessages.add(msg);
8703        }
8704    }
8705
8706    void startCleaningPackages() {
8707        // reader
8708        synchronized (mPackages) {
8709            if (!isExternalMediaAvailable()) {
8710                return;
8711            }
8712            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8713                return;
8714            }
8715        }
8716        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8717        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8718        IActivityManager am = ActivityManagerNative.getDefault();
8719        if (am != null) {
8720            try {
8721                am.startService(null, intent, null, UserHandle.USER_OWNER);
8722            } catch (RemoteException e) {
8723            }
8724        }
8725    }
8726
8727    @Override
8728    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8729            int installFlags, String installerPackageName, VerificationParams verificationParams,
8730            String packageAbiOverride) {
8731        installPackageAsUser(originPath, observer, installFlags, installerPackageName,
8732                verificationParams, packageAbiOverride, UserHandle.getCallingUserId());
8733    }
8734
8735    @Override
8736    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8737            int installFlags, String installerPackageName, VerificationParams verificationParams,
8738            String packageAbiOverride, int userId) {
8739        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8740
8741        final int callingUid = Binder.getCallingUid();
8742        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8743
8744        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8745            try {
8746                if (observer != null) {
8747                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8748                }
8749            } catch (RemoteException re) {
8750            }
8751            return;
8752        }
8753
8754        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8755            installFlags |= PackageManager.INSTALL_FROM_ADB;
8756
8757        } else {
8758            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8759            // about installerPackageName.
8760
8761            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8762            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8763        }
8764
8765        UserHandle user;
8766        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8767            user = UserHandle.ALL;
8768        } else {
8769            user = new UserHandle(userId);
8770        }
8771
8772        // Only system components can circumvent runtime permissions when installing.
8773        if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0
8774                && mContext.checkCallingOrSelfPermission(Manifest.permission
8775                .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) {
8776            throw new SecurityException("You need the "
8777                    + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission "
8778                    + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag");
8779        }
8780
8781        verificationParams.setInstallerUid(callingUid);
8782
8783        final File originFile = new File(originPath);
8784        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8785
8786        final Message msg = mHandler.obtainMessage(INIT_COPY);
8787        msg.obj = new InstallParams(origin, null, observer, installFlags, installerPackageName,
8788                null, verificationParams, user, packageAbiOverride);
8789        mHandler.sendMessage(msg);
8790    }
8791
8792    void installStage(String packageName, File stagedDir, String stagedCid,
8793            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8794            String installerPackageName, int installerUid, UserHandle user) {
8795        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8796                params.referrerUri, installerUid, null);
8797
8798        final OriginInfo origin;
8799        if (stagedDir != null) {
8800            origin = OriginInfo.fromStagedFile(stagedDir);
8801        } else {
8802            origin = OriginInfo.fromStagedContainer(stagedCid);
8803        }
8804
8805        final Message msg = mHandler.obtainMessage(INIT_COPY);
8806        msg.obj = new InstallParams(origin, null, observer, params.installFlags,
8807                installerPackageName, params.volumeUuid, verifParams, user, params.abiOverride);
8808        mHandler.sendMessage(msg);
8809    }
8810
8811    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8812        Bundle extras = new Bundle(1);
8813        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8814
8815        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8816                packageName, extras, null, null, new int[] {userId});
8817        try {
8818            IActivityManager am = ActivityManagerNative.getDefault();
8819            final boolean isSystem =
8820                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8821            if (isSystem && am.isUserRunning(userId, false)) {
8822                // The just-installed/enabled app is bundled on the system, so presumed
8823                // to be able to run automatically without needing an explicit launch.
8824                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8825                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8826                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8827                        .setPackage(packageName);
8828                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8829                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8830            }
8831        } catch (RemoteException e) {
8832            // shouldn't happen
8833            Slog.w(TAG, "Unable to bootstrap installed package", e);
8834        }
8835    }
8836
8837    @Override
8838    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8839            int userId) {
8840        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8841        PackageSetting pkgSetting;
8842        final int uid = Binder.getCallingUid();
8843        enforceCrossUserPermission(uid, userId, true, true,
8844                "setApplicationHiddenSetting for user " + userId);
8845
8846        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8847            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8848            return false;
8849        }
8850
8851        long callingId = Binder.clearCallingIdentity();
8852        try {
8853            boolean sendAdded = false;
8854            boolean sendRemoved = false;
8855            // writer
8856            synchronized (mPackages) {
8857                pkgSetting = mSettings.mPackages.get(packageName);
8858                if (pkgSetting == null) {
8859                    return false;
8860                }
8861                if (pkgSetting.getHidden(userId) != hidden) {
8862                    pkgSetting.setHidden(hidden, userId);
8863                    mSettings.writePackageRestrictionsLPr(userId);
8864                    if (hidden) {
8865                        sendRemoved = true;
8866                    } else {
8867                        sendAdded = true;
8868                    }
8869                }
8870            }
8871            if (sendAdded) {
8872                sendPackageAddedForUser(packageName, pkgSetting, userId);
8873                return true;
8874            }
8875            if (sendRemoved) {
8876                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8877                        "hiding pkg");
8878                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8879            }
8880        } finally {
8881            Binder.restoreCallingIdentity(callingId);
8882        }
8883        return false;
8884    }
8885
8886    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8887            int userId) {
8888        final PackageRemovedInfo info = new PackageRemovedInfo();
8889        info.removedPackage = packageName;
8890        info.removedUsers = new int[] {userId};
8891        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8892        info.sendBroadcast(false, false, false);
8893    }
8894
8895    /**
8896     * Returns true if application is not found or there was an error. Otherwise it returns
8897     * the hidden state of the package for the given user.
8898     */
8899    @Override
8900    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8901        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8902        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8903                false, "getApplicationHidden for user " + userId);
8904        PackageSetting pkgSetting;
8905        long callingId = Binder.clearCallingIdentity();
8906        try {
8907            // writer
8908            synchronized (mPackages) {
8909                pkgSetting = mSettings.mPackages.get(packageName);
8910                if (pkgSetting == null) {
8911                    return true;
8912                }
8913                return pkgSetting.getHidden(userId);
8914            }
8915        } finally {
8916            Binder.restoreCallingIdentity(callingId);
8917        }
8918    }
8919
8920    /**
8921     * @hide
8922     */
8923    @Override
8924    public int installExistingPackageAsUser(String packageName, int userId) {
8925        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8926                null);
8927        PackageSetting pkgSetting;
8928        final int uid = Binder.getCallingUid();
8929        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8930                + userId);
8931        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8932            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8933        }
8934
8935        long callingId = Binder.clearCallingIdentity();
8936        try {
8937            boolean sendAdded = false;
8938
8939            // writer
8940            synchronized (mPackages) {
8941                pkgSetting = mSettings.mPackages.get(packageName);
8942                if (pkgSetting == null) {
8943                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8944                }
8945                if (!pkgSetting.getInstalled(userId)) {
8946                    pkgSetting.setInstalled(true, userId);
8947                    pkgSetting.setHidden(false, userId);
8948                    mSettings.writePackageRestrictionsLPr(userId);
8949                    sendAdded = true;
8950                }
8951            }
8952
8953            if (sendAdded) {
8954                sendPackageAddedForUser(packageName, pkgSetting, userId);
8955            }
8956        } finally {
8957            Binder.restoreCallingIdentity(callingId);
8958        }
8959
8960        return PackageManager.INSTALL_SUCCEEDED;
8961    }
8962
8963    boolean isUserRestricted(int userId, String restrictionKey) {
8964        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8965        if (restrictions.getBoolean(restrictionKey, false)) {
8966            Log.w(TAG, "User is restricted: " + restrictionKey);
8967            return true;
8968        }
8969        return false;
8970    }
8971
8972    @Override
8973    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8974        mContext.enforceCallingOrSelfPermission(
8975                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8976                "Only package verification agents can verify applications");
8977
8978        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8979        final PackageVerificationResponse response = new PackageVerificationResponse(
8980                verificationCode, Binder.getCallingUid());
8981        msg.arg1 = id;
8982        msg.obj = response;
8983        mHandler.sendMessage(msg);
8984    }
8985
8986    @Override
8987    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8988            long millisecondsToDelay) {
8989        mContext.enforceCallingOrSelfPermission(
8990                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8991                "Only package verification agents can extend verification timeouts");
8992
8993        final PackageVerificationState state = mPendingVerification.get(id);
8994        final PackageVerificationResponse response = new PackageVerificationResponse(
8995                verificationCodeAtTimeout, Binder.getCallingUid());
8996
8997        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8998            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8999        }
9000        if (millisecondsToDelay < 0) {
9001            millisecondsToDelay = 0;
9002        }
9003        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
9004                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
9005            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
9006        }
9007
9008        if ((state != null) && !state.timeoutExtended()) {
9009            state.extendTimeout();
9010
9011            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
9012            msg.arg1 = id;
9013            msg.obj = response;
9014            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
9015        }
9016    }
9017
9018    private void broadcastPackageVerified(int verificationId, Uri packageUri,
9019            int verificationCode, UserHandle user) {
9020        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
9021        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
9022        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9023        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9024        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
9025
9026        mContext.sendBroadcastAsUser(intent, user,
9027                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
9028    }
9029
9030    private ComponentName matchComponentForVerifier(String packageName,
9031            List<ResolveInfo> receivers) {
9032        ActivityInfo targetReceiver = null;
9033
9034        final int NR = receivers.size();
9035        for (int i = 0; i < NR; i++) {
9036            final ResolveInfo info = receivers.get(i);
9037            if (info.activityInfo == null) {
9038                continue;
9039            }
9040
9041            if (packageName.equals(info.activityInfo.packageName)) {
9042                targetReceiver = info.activityInfo;
9043                break;
9044            }
9045        }
9046
9047        if (targetReceiver == null) {
9048            return null;
9049        }
9050
9051        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
9052    }
9053
9054    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
9055            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
9056        if (pkgInfo.verifiers.length == 0) {
9057            return null;
9058        }
9059
9060        final int N = pkgInfo.verifiers.length;
9061        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
9062        for (int i = 0; i < N; i++) {
9063            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
9064
9065            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
9066                    receivers);
9067            if (comp == null) {
9068                continue;
9069            }
9070
9071            final int verifierUid = getUidForVerifier(verifierInfo);
9072            if (verifierUid == -1) {
9073                continue;
9074            }
9075
9076            if (DEBUG_VERIFY) {
9077                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
9078                        + " with the correct signature");
9079            }
9080            sufficientVerifiers.add(comp);
9081            verificationState.addSufficientVerifier(verifierUid);
9082        }
9083
9084        return sufficientVerifiers;
9085    }
9086
9087    private int getUidForVerifier(VerifierInfo verifierInfo) {
9088        synchronized (mPackages) {
9089            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
9090            if (pkg == null) {
9091                return -1;
9092            } else if (pkg.mSignatures.length != 1) {
9093                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9094                        + " has more than one signature; ignoring");
9095                return -1;
9096            }
9097
9098            /*
9099             * If the public key of the package's signature does not match
9100             * our expected public key, then this is a different package and
9101             * we should skip.
9102             */
9103
9104            final byte[] expectedPublicKey;
9105            try {
9106                final Signature verifierSig = pkg.mSignatures[0];
9107                final PublicKey publicKey = verifierSig.getPublicKey();
9108                expectedPublicKey = publicKey.getEncoded();
9109            } catch (CertificateException e) {
9110                return -1;
9111            }
9112
9113            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
9114
9115            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
9116                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
9117                        + " does not have the expected public key; ignoring");
9118                return -1;
9119            }
9120
9121            return pkg.applicationInfo.uid;
9122        }
9123    }
9124
9125    @Override
9126    public void finishPackageInstall(int token) {
9127        enforceSystemOrRoot("Only the system is allowed to finish installs");
9128
9129        if (DEBUG_INSTALL) {
9130            Slog.v(TAG, "BM finishing package install for " + token);
9131        }
9132
9133        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9134        mHandler.sendMessage(msg);
9135    }
9136
9137    /**
9138     * Get the verification agent timeout.
9139     *
9140     * @return verification timeout in milliseconds
9141     */
9142    private long getVerificationTimeout() {
9143        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
9144                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
9145                DEFAULT_VERIFICATION_TIMEOUT);
9146    }
9147
9148    /**
9149     * Get the default verification agent response code.
9150     *
9151     * @return default verification response code
9152     */
9153    private int getDefaultVerificationResponse() {
9154        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9155                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
9156                DEFAULT_VERIFICATION_RESPONSE);
9157    }
9158
9159    /**
9160     * Check whether or not package verification has been enabled.
9161     *
9162     * @return true if verification should be performed
9163     */
9164    private boolean isVerificationEnabled(int userId, int installFlags) {
9165        if (!DEFAULT_VERIFY_ENABLE) {
9166            return false;
9167        }
9168
9169        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
9170
9171        // Check if installing from ADB
9172        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
9173            // Do not run verification in a test harness environment
9174            if (ActivityManager.isRunningInTestHarness()) {
9175                return false;
9176            }
9177            if (ensureVerifyAppsEnabled) {
9178                return true;
9179            }
9180            // Check if the developer does not want package verification for ADB installs
9181            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9182                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
9183                return false;
9184            }
9185        }
9186
9187        if (ensureVerifyAppsEnabled) {
9188            return true;
9189        }
9190
9191        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9192                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
9193    }
9194
9195    @Override
9196    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
9197            throws RemoteException {
9198        mContext.enforceCallingOrSelfPermission(
9199                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
9200                "Only intentfilter verification agents can verify applications");
9201
9202        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
9203        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
9204                Binder.getCallingUid(), verificationCode, failedDomains);
9205        msg.arg1 = id;
9206        msg.obj = response;
9207        mHandler.sendMessage(msg);
9208    }
9209
9210    @Override
9211    public int getIntentVerificationStatus(String packageName, int userId) {
9212        synchronized (mPackages) {
9213            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
9214        }
9215    }
9216
9217    @Override
9218    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
9219        boolean result = false;
9220        synchronized (mPackages) {
9221            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
9222        }
9223        if (result) {
9224            scheduleWritePackageRestrictionsLocked(userId);
9225        }
9226        return result;
9227    }
9228
9229    @Override
9230    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
9231        synchronized (mPackages) {
9232            return mSettings.getIntentFilterVerificationsLPr(packageName);
9233        }
9234    }
9235
9236    @Override
9237    public List<IntentFilter> getAllIntentFilters(String packageName) {
9238        if (TextUtils.isEmpty(packageName)) {
9239            return Collections.<IntentFilter>emptyList();
9240        }
9241        synchronized (mPackages) {
9242            PackageParser.Package pkg = mPackages.get(packageName);
9243            if (pkg == null || pkg.activities == null) {
9244                return Collections.<IntentFilter>emptyList();
9245            }
9246            final int count = pkg.activities.size();
9247            ArrayList<IntentFilter> result = new ArrayList<>();
9248            for (int n=0; n<count; n++) {
9249                PackageParser.Activity activity = pkg.activities.get(n);
9250                if (activity.intents != null || activity.intents.size() > 0) {
9251                    result.addAll(activity.intents);
9252                }
9253            }
9254            return result;
9255        }
9256    }
9257
9258    @Override
9259    public boolean setDefaultBrowserPackageName(String packageName, int userId) {
9260        synchronized (mPackages) {
9261            boolean result = mSettings.setDefaultBrowserPackageNameLPr(packageName, userId);
9262            if (packageName != null) {
9263                result |= updateIntentVerificationStatus(packageName,
9264                        PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS,
9265                        UserHandle.myUserId());
9266            }
9267            return result;
9268        }
9269    }
9270
9271    @Override
9272    public String getDefaultBrowserPackageName(int userId) {
9273        synchronized (mPackages) {
9274            return mSettings.getDefaultBrowserPackageNameLPw(userId);
9275        }
9276    }
9277
9278    /**
9279     * Get the "allow unknown sources" setting.
9280     *
9281     * @return the current "allow unknown sources" setting
9282     */
9283    private int getUnknownSourcesSettings() {
9284        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
9285                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
9286                -1);
9287    }
9288
9289    @Override
9290    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
9291        final int uid = Binder.getCallingUid();
9292        // writer
9293        synchronized (mPackages) {
9294            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
9295            if (targetPackageSetting == null) {
9296                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
9297            }
9298
9299            PackageSetting installerPackageSetting;
9300            if (installerPackageName != null) {
9301                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
9302                if (installerPackageSetting == null) {
9303                    throw new IllegalArgumentException("Unknown installer package: "
9304                            + installerPackageName);
9305                }
9306            } else {
9307                installerPackageSetting = null;
9308            }
9309
9310            Signature[] callerSignature;
9311            Object obj = mSettings.getUserIdLPr(uid);
9312            if (obj != null) {
9313                if (obj instanceof SharedUserSetting) {
9314                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9315                } else if (obj instanceof PackageSetting) {
9316                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9317                } else {
9318                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9319                }
9320            } else {
9321                throw new SecurityException("Unknown calling uid " + uid);
9322            }
9323
9324            // Verify: can't set installerPackageName to a package that is
9325            // not signed with the same cert as the caller.
9326            if (installerPackageSetting != null) {
9327                if (compareSignatures(callerSignature,
9328                        installerPackageSetting.signatures.mSignatures)
9329                        != PackageManager.SIGNATURE_MATCH) {
9330                    throw new SecurityException(
9331                            "Caller does not have same cert as new installer package "
9332                            + installerPackageName);
9333                }
9334            }
9335
9336            // Verify: if target already has an installer package, it must
9337            // be signed with the same cert as the caller.
9338            if (targetPackageSetting.installerPackageName != null) {
9339                PackageSetting setting = mSettings.mPackages.get(
9340                        targetPackageSetting.installerPackageName);
9341                // If the currently set package isn't valid, then it's always
9342                // okay to change it.
9343                if (setting != null) {
9344                    if (compareSignatures(callerSignature,
9345                            setting.signatures.mSignatures)
9346                            != PackageManager.SIGNATURE_MATCH) {
9347                        throw new SecurityException(
9348                                "Caller does not have same cert as old installer package "
9349                                + targetPackageSetting.installerPackageName);
9350                    }
9351                }
9352            }
9353
9354            // Okay!
9355            targetPackageSetting.installerPackageName = installerPackageName;
9356            scheduleWriteSettingsLocked();
9357        }
9358    }
9359
9360    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9361        // Queue up an async operation since the package installation may take a little while.
9362        mHandler.post(new Runnable() {
9363            public void run() {
9364                mHandler.removeCallbacks(this);
9365                 // Result object to be returned
9366                PackageInstalledInfo res = new PackageInstalledInfo();
9367                res.returnCode = currentStatus;
9368                res.uid = -1;
9369                res.pkg = null;
9370                res.removedInfo = new PackageRemovedInfo();
9371                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9372                    args.doPreInstall(res.returnCode);
9373                    synchronized (mInstallLock) {
9374                        installPackageLI(args, res);
9375                    }
9376                    args.doPostInstall(res.returnCode, res.uid);
9377                }
9378
9379                // A restore should be performed at this point if (a) the install
9380                // succeeded, (b) the operation is not an update, and (c) the new
9381                // package has not opted out of backup participation.
9382                final boolean update = res.removedInfo.removedPackage != null;
9383                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9384                boolean doRestore = !update
9385                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9386
9387                // Set up the post-install work request bookkeeping.  This will be used
9388                // and cleaned up by the post-install event handling regardless of whether
9389                // there's a restore pass performed.  Token values are >= 1.
9390                int token;
9391                if (mNextInstallToken < 0) mNextInstallToken = 1;
9392                token = mNextInstallToken++;
9393
9394                PostInstallData data = new PostInstallData(args, res);
9395                mRunningInstalls.put(token, data);
9396                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9397
9398                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9399                    // Pass responsibility to the Backup Manager.  It will perform a
9400                    // restore if appropriate, then pass responsibility back to the
9401                    // Package Manager to run the post-install observer callbacks
9402                    // and broadcasts.
9403                    IBackupManager bm = IBackupManager.Stub.asInterface(
9404                            ServiceManager.getService(Context.BACKUP_SERVICE));
9405                    if (bm != null) {
9406                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9407                                + " to BM for possible restore");
9408                        try {
9409                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9410                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9411                            } else {
9412                                doRestore = false;
9413                            }
9414                        } catch (RemoteException e) {
9415                            // can't happen; the backup manager is local
9416                        } catch (Exception e) {
9417                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9418                            doRestore = false;
9419                        }
9420                    } else {
9421                        Slog.e(TAG, "Backup Manager not found!");
9422                        doRestore = false;
9423                    }
9424                }
9425
9426                if (!doRestore) {
9427                    // No restore possible, or the Backup Manager was mysteriously not
9428                    // available -- just fire the post-install work request directly.
9429                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9430                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9431                    mHandler.sendMessage(msg);
9432                }
9433            }
9434        });
9435    }
9436
9437    private abstract class HandlerParams {
9438        private static final int MAX_RETRIES = 4;
9439
9440        /**
9441         * Number of times startCopy() has been attempted and had a non-fatal
9442         * error.
9443         */
9444        private int mRetries = 0;
9445
9446        /** User handle for the user requesting the information or installation. */
9447        private final UserHandle mUser;
9448
9449        HandlerParams(UserHandle user) {
9450            mUser = user;
9451        }
9452
9453        UserHandle getUser() {
9454            return mUser;
9455        }
9456
9457        final boolean startCopy() {
9458            boolean res;
9459            try {
9460                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9461
9462                if (++mRetries > MAX_RETRIES) {
9463                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9464                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9465                    handleServiceError();
9466                    return false;
9467                } else {
9468                    handleStartCopy();
9469                    res = true;
9470                }
9471            } catch (RemoteException e) {
9472                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9473                mHandler.sendEmptyMessage(MCS_RECONNECT);
9474                res = false;
9475            }
9476            handleReturnCode();
9477            return res;
9478        }
9479
9480        final void serviceError() {
9481            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9482            handleServiceError();
9483            handleReturnCode();
9484        }
9485
9486        abstract void handleStartCopy() throws RemoteException;
9487        abstract void handleServiceError();
9488        abstract void handleReturnCode();
9489    }
9490
9491    class MeasureParams extends HandlerParams {
9492        private final PackageStats mStats;
9493        private boolean mSuccess;
9494
9495        private final IPackageStatsObserver mObserver;
9496
9497        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9498            super(new UserHandle(stats.userHandle));
9499            mObserver = observer;
9500            mStats = stats;
9501        }
9502
9503        @Override
9504        public String toString() {
9505            return "MeasureParams{"
9506                + Integer.toHexString(System.identityHashCode(this))
9507                + " " + mStats.packageName + "}";
9508        }
9509
9510        @Override
9511        void handleStartCopy() throws RemoteException {
9512            synchronized (mInstallLock) {
9513                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9514            }
9515
9516            if (mSuccess) {
9517                final boolean mounted;
9518                if (Environment.isExternalStorageEmulated()) {
9519                    mounted = true;
9520                } else {
9521                    final String status = Environment.getExternalStorageState();
9522                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9523                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9524                }
9525
9526                if (mounted) {
9527                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9528
9529                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9530                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9531
9532                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9533                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9534
9535                    // Always subtract cache size, since it's a subdirectory
9536                    mStats.externalDataSize -= mStats.externalCacheSize;
9537
9538                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9539                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9540
9541                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9542                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9543                }
9544            }
9545        }
9546
9547        @Override
9548        void handleReturnCode() {
9549            if (mObserver != null) {
9550                try {
9551                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9552                } catch (RemoteException e) {
9553                    Slog.i(TAG, "Observer no longer exists.");
9554                }
9555            }
9556        }
9557
9558        @Override
9559        void handleServiceError() {
9560            Slog.e(TAG, "Could not measure application " + mStats.packageName
9561                            + " external storage");
9562        }
9563    }
9564
9565    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9566            throws RemoteException {
9567        long result = 0;
9568        for (File path : paths) {
9569            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9570        }
9571        return result;
9572    }
9573
9574    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9575        for (File path : paths) {
9576            try {
9577                mcs.clearDirectory(path.getAbsolutePath());
9578            } catch (RemoteException e) {
9579            }
9580        }
9581    }
9582
9583    static class OriginInfo {
9584        /**
9585         * Location where install is coming from, before it has been
9586         * copied/renamed into place. This could be a single monolithic APK
9587         * file, or a cluster directory. This location may be untrusted.
9588         */
9589        final File file;
9590        final String cid;
9591
9592        /**
9593         * Flag indicating that {@link #file} or {@link #cid} has already been
9594         * staged, meaning downstream users don't need to defensively copy the
9595         * contents.
9596         */
9597        final boolean staged;
9598
9599        /**
9600         * Flag indicating that {@link #file} or {@link #cid} is an already
9601         * installed app that is being moved.
9602         */
9603        final boolean existing;
9604
9605        final String resolvedPath;
9606        final File resolvedFile;
9607
9608        static OriginInfo fromNothing() {
9609            return new OriginInfo(null, null, false, false);
9610        }
9611
9612        static OriginInfo fromUntrustedFile(File file) {
9613            return new OriginInfo(file, null, false, false);
9614        }
9615
9616        static OriginInfo fromExistingFile(File file) {
9617            return new OriginInfo(file, null, false, true);
9618        }
9619
9620        static OriginInfo fromStagedFile(File file) {
9621            return new OriginInfo(file, null, true, false);
9622        }
9623
9624        static OriginInfo fromStagedContainer(String cid) {
9625            return new OriginInfo(null, cid, true, false);
9626        }
9627
9628        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9629            this.file = file;
9630            this.cid = cid;
9631            this.staged = staged;
9632            this.existing = existing;
9633
9634            if (cid != null) {
9635                resolvedPath = PackageHelper.getSdDir(cid);
9636                resolvedFile = new File(resolvedPath);
9637            } else if (file != null) {
9638                resolvedPath = file.getAbsolutePath();
9639                resolvedFile = file;
9640            } else {
9641                resolvedPath = null;
9642                resolvedFile = null;
9643            }
9644        }
9645    }
9646
9647    class MoveInfo {
9648        final int moveId;
9649        final String fromUuid;
9650        final String toUuid;
9651        final String packageName;
9652        final String dataAppName;
9653        final int appId;
9654        final String seinfo;
9655
9656        public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName,
9657                String dataAppName, int appId, String seinfo) {
9658            this.moveId = moveId;
9659            this.fromUuid = fromUuid;
9660            this.toUuid = toUuid;
9661            this.packageName = packageName;
9662            this.dataAppName = dataAppName;
9663            this.appId = appId;
9664            this.seinfo = seinfo;
9665        }
9666    }
9667
9668    class InstallParams extends HandlerParams {
9669        final OriginInfo origin;
9670        final MoveInfo move;
9671        final IPackageInstallObserver2 observer;
9672        int installFlags;
9673        final String installerPackageName;
9674        final String volumeUuid;
9675        final VerificationParams verificationParams;
9676        private InstallArgs mArgs;
9677        private int mRet;
9678        final String packageAbiOverride;
9679
9680        InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
9681                int installFlags, String installerPackageName, String volumeUuid,
9682                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
9683            super(user);
9684            this.origin = origin;
9685            this.move = move;
9686            this.observer = observer;
9687            this.installFlags = installFlags;
9688            this.installerPackageName = installerPackageName;
9689            this.volumeUuid = volumeUuid;
9690            this.verificationParams = verificationParams;
9691            this.packageAbiOverride = packageAbiOverride;
9692        }
9693
9694        @Override
9695        public String toString() {
9696            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9697                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9698        }
9699
9700        public ManifestDigest getManifestDigest() {
9701            if (verificationParams == null) {
9702                return null;
9703            }
9704            return verificationParams.getManifestDigest();
9705        }
9706
9707        private int installLocationPolicy(PackageInfoLite pkgLite) {
9708            String packageName = pkgLite.packageName;
9709            int installLocation = pkgLite.installLocation;
9710            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9711            // reader
9712            synchronized (mPackages) {
9713                PackageParser.Package pkg = mPackages.get(packageName);
9714                if (pkg != null) {
9715                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9716                        // Check for downgrading.
9717                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9718                            try {
9719                                checkDowngrade(pkg, pkgLite);
9720                            } catch (PackageManagerException e) {
9721                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9722                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9723                            }
9724                        }
9725                        // Check for updated system application.
9726                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9727                            if (onSd) {
9728                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9729                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9730                            }
9731                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9732                        } else {
9733                            if (onSd) {
9734                                // Install flag overrides everything.
9735                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9736                            }
9737                            // If current upgrade specifies particular preference
9738                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9739                                // Application explicitly specified internal.
9740                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9741                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9742                                // App explictly prefers external. Let policy decide
9743                            } else {
9744                                // Prefer previous location
9745                                if (isExternal(pkg)) {
9746                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9747                                }
9748                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9749                            }
9750                        }
9751                    } else {
9752                        // Invalid install. Return error code
9753                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9754                    }
9755                }
9756            }
9757            // All the special cases have been taken care of.
9758            // Return result based on recommended install location.
9759            if (onSd) {
9760                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9761            }
9762            return pkgLite.recommendedInstallLocation;
9763        }
9764
9765        /*
9766         * Invoke remote method to get package information and install
9767         * location values. Override install location based on default
9768         * policy if needed and then create install arguments based
9769         * on the install location.
9770         */
9771        public void handleStartCopy() throws RemoteException {
9772            int ret = PackageManager.INSTALL_SUCCEEDED;
9773
9774            // If we're already staged, we've firmly committed to an install location
9775            if (origin.staged) {
9776                if (origin.file != null) {
9777                    installFlags |= PackageManager.INSTALL_INTERNAL;
9778                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9779                } else if (origin.cid != null) {
9780                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9781                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9782                } else {
9783                    throw new IllegalStateException("Invalid stage location");
9784                }
9785            }
9786
9787            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9788            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9789
9790            PackageInfoLite pkgLite = null;
9791
9792            if (onInt && onSd) {
9793                // Check if both bits are set.
9794                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9795                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9796            } else {
9797                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9798                        packageAbiOverride);
9799
9800                /*
9801                 * If we have too little free space, try to free cache
9802                 * before giving up.
9803                 */
9804                if (!origin.staged && pkgLite.recommendedInstallLocation
9805                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9806                    // TODO: focus freeing disk space on the target device
9807                    final StorageManager storage = StorageManager.from(mContext);
9808                    final long lowThreshold = storage.getStorageLowBytes(
9809                            Environment.getDataDirectory());
9810
9811                    final long sizeBytes = mContainerService.calculateInstalledSize(
9812                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9813
9814                    if (mInstaller.freeCache(null, sizeBytes + lowThreshold) >= 0) {
9815                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9816                                installFlags, packageAbiOverride);
9817                    }
9818
9819                    /*
9820                     * The cache free must have deleted the file we
9821                     * downloaded to install.
9822                     *
9823                     * TODO: fix the "freeCache" call to not delete
9824                     *       the file we care about.
9825                     */
9826                    if (pkgLite.recommendedInstallLocation
9827                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9828                        pkgLite.recommendedInstallLocation
9829                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9830                    }
9831                }
9832            }
9833
9834            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9835                int loc = pkgLite.recommendedInstallLocation;
9836                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9837                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9838                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9839                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9840                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9841                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9842                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9843                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9844                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9845                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9846                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9847                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9848                } else {
9849                    // Override with defaults if needed.
9850                    loc = installLocationPolicy(pkgLite);
9851                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9852                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9853                    } else if (!onSd && !onInt) {
9854                        // Override install location with flags
9855                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9856                            // Set the flag to install on external media.
9857                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9858                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9859                        } else {
9860                            // Make sure the flag for installing on external
9861                            // media is unset
9862                            installFlags |= PackageManager.INSTALL_INTERNAL;
9863                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9864                        }
9865                    }
9866                }
9867            }
9868
9869            final InstallArgs args = createInstallArgs(this);
9870            mArgs = args;
9871
9872            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9873                 /*
9874                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9875                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9876                 */
9877                int userIdentifier = getUser().getIdentifier();
9878                if (userIdentifier == UserHandle.USER_ALL
9879                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9880                    userIdentifier = UserHandle.USER_OWNER;
9881                }
9882
9883                /*
9884                 * Determine if we have any installed package verifiers. If we
9885                 * do, then we'll defer to them to verify the packages.
9886                 */
9887                final int requiredUid = mRequiredVerifierPackage == null ? -1
9888                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9889                if (!origin.existing && requiredUid != -1
9890                        && isVerificationEnabled(userIdentifier, installFlags)) {
9891                    final Intent verification = new Intent(
9892                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9893                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9894                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9895                            PACKAGE_MIME_TYPE);
9896                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9897
9898                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9899                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9900                            0 /* TODO: Which userId? */);
9901
9902                    if (DEBUG_VERIFY) {
9903                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9904                                + verification.toString() + " with " + pkgLite.verifiers.length
9905                                + " optional verifiers");
9906                    }
9907
9908                    final int verificationId = mPendingVerificationToken++;
9909
9910                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9911
9912                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9913                            installerPackageName);
9914
9915                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9916                            installFlags);
9917
9918                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9919                            pkgLite.packageName);
9920
9921                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9922                            pkgLite.versionCode);
9923
9924                    if (verificationParams != null) {
9925                        if (verificationParams.getVerificationURI() != null) {
9926                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9927                                 verificationParams.getVerificationURI());
9928                        }
9929                        if (verificationParams.getOriginatingURI() != null) {
9930                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9931                                  verificationParams.getOriginatingURI());
9932                        }
9933                        if (verificationParams.getReferrer() != null) {
9934                            verification.putExtra(Intent.EXTRA_REFERRER,
9935                                  verificationParams.getReferrer());
9936                        }
9937                        if (verificationParams.getOriginatingUid() >= 0) {
9938                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9939                                  verificationParams.getOriginatingUid());
9940                        }
9941                        if (verificationParams.getInstallerUid() >= 0) {
9942                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9943                                  verificationParams.getInstallerUid());
9944                        }
9945                    }
9946
9947                    final PackageVerificationState verificationState = new PackageVerificationState(
9948                            requiredUid, args);
9949
9950                    mPendingVerification.append(verificationId, verificationState);
9951
9952                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9953                            receivers, verificationState);
9954
9955                    /*
9956                     * If any sufficient verifiers were listed in the package
9957                     * manifest, attempt to ask them.
9958                     */
9959                    if (sufficientVerifiers != null) {
9960                        final int N = sufficientVerifiers.size();
9961                        if (N == 0) {
9962                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9963                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9964                        } else {
9965                            for (int i = 0; i < N; i++) {
9966                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9967
9968                                final Intent sufficientIntent = new Intent(verification);
9969                                sufficientIntent.setComponent(verifierComponent);
9970
9971                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9972                            }
9973                        }
9974                    }
9975
9976                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9977                            mRequiredVerifierPackage, receivers);
9978                    if (ret == PackageManager.INSTALL_SUCCEEDED
9979                            && mRequiredVerifierPackage != null) {
9980                        /*
9981                         * Send the intent to the required verification agent,
9982                         * but only start the verification timeout after the
9983                         * target BroadcastReceivers have run.
9984                         */
9985                        verification.setComponent(requiredVerifierComponent);
9986                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9987                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9988                                new BroadcastReceiver() {
9989                                    @Override
9990                                    public void onReceive(Context context, Intent intent) {
9991                                        final Message msg = mHandler
9992                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9993                                        msg.arg1 = verificationId;
9994                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9995                                    }
9996                                }, null, 0, null, null);
9997
9998                        /*
9999                         * We don't want the copy to proceed until verification
10000                         * succeeds, so null out this field.
10001                         */
10002                        mArgs = null;
10003                    }
10004                } else {
10005                    /*
10006                     * No package verification is enabled, so immediately start
10007                     * the remote call to initiate copy using temporary file.
10008                     */
10009                    ret = args.copyApk(mContainerService, true);
10010                }
10011            }
10012
10013            mRet = ret;
10014        }
10015
10016        @Override
10017        void handleReturnCode() {
10018            // If mArgs is null, then MCS couldn't be reached. When it
10019            // reconnects, it will try again to install. At that point, this
10020            // will succeed.
10021            if (mArgs != null) {
10022                processPendingInstall(mArgs, mRet);
10023            }
10024        }
10025
10026        @Override
10027        void handleServiceError() {
10028            mArgs = createInstallArgs(this);
10029            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10030        }
10031
10032        public boolean isForwardLocked() {
10033            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10034        }
10035    }
10036
10037    /**
10038     * Used during creation of InstallArgs
10039     *
10040     * @param installFlags package installation flags
10041     * @return true if should be installed on external storage
10042     */
10043    private static boolean installOnExternalAsec(int installFlags) {
10044        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
10045            return false;
10046        }
10047        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
10048            return true;
10049        }
10050        return false;
10051    }
10052
10053    /**
10054     * Used during creation of InstallArgs
10055     *
10056     * @param installFlags package installation flags
10057     * @return true if should be installed as forward locked
10058     */
10059    private static boolean installForwardLocked(int installFlags) {
10060        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10061    }
10062
10063    private InstallArgs createInstallArgs(InstallParams params) {
10064        if (params.move != null) {
10065            return new MoveInstallArgs(params);
10066        } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) {
10067            return new AsecInstallArgs(params);
10068        } else {
10069            return new FileInstallArgs(params);
10070        }
10071    }
10072
10073    /**
10074     * Create args that describe an existing installed package. Typically used
10075     * when cleaning up old installs, or used as a move source.
10076     */
10077    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
10078            String resourcePath, String[] instructionSets) {
10079        final boolean isInAsec;
10080        if (installOnExternalAsec(installFlags)) {
10081            /* Apps on SD card are always in ASEC containers. */
10082            isInAsec = true;
10083        } else if (installForwardLocked(installFlags)
10084                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
10085            /*
10086             * Forward-locked apps are only in ASEC containers if they're the
10087             * new style
10088             */
10089            isInAsec = true;
10090        } else {
10091            isInAsec = false;
10092        }
10093
10094        if (isInAsec) {
10095            return new AsecInstallArgs(codePath, instructionSets,
10096                    installOnExternalAsec(installFlags), installForwardLocked(installFlags));
10097        } else {
10098            return new FileInstallArgs(codePath, resourcePath, instructionSets);
10099        }
10100    }
10101
10102    static abstract class InstallArgs {
10103        /** @see InstallParams#origin */
10104        final OriginInfo origin;
10105        /** @see InstallParams#move */
10106        final MoveInfo move;
10107
10108        final IPackageInstallObserver2 observer;
10109        // Always refers to PackageManager flags only
10110        final int installFlags;
10111        final String installerPackageName;
10112        final String volumeUuid;
10113        final ManifestDigest manifestDigest;
10114        final UserHandle user;
10115        final String abiOverride;
10116
10117        // The list of instruction sets supported by this app. This is currently
10118        // only used during the rmdex() phase to clean up resources. We can get rid of this
10119        // if we move dex files under the common app path.
10120        /* nullable */ String[] instructionSets;
10121
10122        InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer,
10123                int installFlags, String installerPackageName, String volumeUuid,
10124                ManifestDigest manifestDigest, UserHandle user, String[] instructionSets,
10125                String abiOverride) {
10126            this.origin = origin;
10127            this.move = move;
10128            this.installFlags = installFlags;
10129            this.observer = observer;
10130            this.installerPackageName = installerPackageName;
10131            this.volumeUuid = volumeUuid;
10132            this.manifestDigest = manifestDigest;
10133            this.user = user;
10134            this.instructionSets = instructionSets;
10135            this.abiOverride = abiOverride;
10136        }
10137
10138        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
10139        abstract int doPreInstall(int status);
10140
10141        /**
10142         * Rename package into final resting place. All paths on the given
10143         * scanned package should be updated to reflect the rename.
10144         */
10145        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
10146        abstract int doPostInstall(int status, int uid);
10147
10148        /** @see PackageSettingBase#codePathString */
10149        abstract String getCodePath();
10150        /** @see PackageSettingBase#resourcePathString */
10151        abstract String getResourcePath();
10152
10153        // Need installer lock especially for dex file removal.
10154        abstract void cleanUpResourcesLI();
10155        abstract boolean doPostDeleteLI(boolean delete);
10156
10157        /**
10158         * Called before the source arguments are copied. This is used mostly
10159         * for MoveParams when it needs to read the source file to put it in the
10160         * destination.
10161         */
10162        int doPreCopy() {
10163            return PackageManager.INSTALL_SUCCEEDED;
10164        }
10165
10166        /**
10167         * Called after the source arguments are copied. This is used mostly for
10168         * MoveParams when it needs to read the source file to put it in the
10169         * destination.
10170         *
10171         * @return
10172         */
10173        int doPostCopy(int uid) {
10174            return PackageManager.INSTALL_SUCCEEDED;
10175        }
10176
10177        protected boolean isFwdLocked() {
10178            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
10179        }
10180
10181        protected boolean isExternalAsec() {
10182            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
10183        }
10184
10185        UserHandle getUser() {
10186            return user;
10187        }
10188    }
10189
10190    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
10191        if (!allCodePaths.isEmpty()) {
10192            if (instructionSets == null) {
10193                throw new IllegalStateException("instructionSet == null");
10194            }
10195            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
10196            for (String codePath : allCodePaths) {
10197                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
10198                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
10199                    if (retCode < 0) {
10200                        Slog.w(TAG, "Couldn't remove dex file for package: "
10201                                + " at location " + codePath + ", retcode=" + retCode);
10202                        // we don't consider this to be a failure of the core package deletion
10203                    }
10204                }
10205            }
10206        }
10207    }
10208
10209    /**
10210     * Logic to handle installation of non-ASEC applications, including copying
10211     * and renaming logic.
10212     */
10213    class FileInstallArgs extends InstallArgs {
10214        private File codeFile;
10215        private File resourceFile;
10216
10217        // Example topology:
10218        // /data/app/com.example/base.apk
10219        // /data/app/com.example/split_foo.apk
10220        // /data/app/com.example/lib/arm/libfoo.so
10221        // /data/app/com.example/lib/arm64/libfoo.so
10222        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
10223
10224        /** New install */
10225        FileInstallArgs(InstallParams params) {
10226            super(params.origin, params.move, params.observer, params.installFlags,
10227                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10228                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10229            if (isFwdLocked()) {
10230                throw new IllegalArgumentException("Forward locking only supported in ASEC");
10231            }
10232        }
10233
10234        /** Existing install */
10235        FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) {
10236            super(OriginInfo.fromNothing(), null, null, 0, null, null, null, null, instructionSets,
10237                    null);
10238            this.codeFile = (codePath != null) ? new File(codePath) : null;
10239            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
10240        }
10241
10242        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10243            if (origin.staged) {
10244                Slog.d(TAG, origin.file + " already staged; skipping copy");
10245                codeFile = origin.file;
10246                resourceFile = origin.file;
10247                return PackageManager.INSTALL_SUCCEEDED;
10248            }
10249
10250            try {
10251                final File tempDir = mInstallerService.allocateStageDirLegacy(volumeUuid);
10252                codeFile = tempDir;
10253                resourceFile = tempDir;
10254            } catch (IOException e) {
10255                Slog.w(TAG, "Failed to create copy file: " + e);
10256                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10257            }
10258
10259            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
10260                @Override
10261                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
10262                    if (!FileUtils.isValidExtFilename(name)) {
10263                        throw new IllegalArgumentException("Invalid filename: " + name);
10264                    }
10265                    try {
10266                        final File file = new File(codeFile, name);
10267                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10268                                O_RDWR | O_CREAT, 0644);
10269                        Os.chmod(file.getAbsolutePath(), 0644);
10270                        return new ParcelFileDescriptor(fd);
10271                    } catch (ErrnoException e) {
10272                        throw new RemoteException("Failed to open: " + e.getMessage());
10273                    }
10274                }
10275            };
10276
10277            int ret = PackageManager.INSTALL_SUCCEEDED;
10278            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
10279            if (ret != PackageManager.INSTALL_SUCCEEDED) {
10280                Slog.e(TAG, "Failed to copy package");
10281                return ret;
10282            }
10283
10284            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
10285            NativeLibraryHelper.Handle handle = null;
10286            try {
10287                handle = NativeLibraryHelper.Handle.create(codeFile);
10288                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
10289                        abiOverride);
10290            } catch (IOException e) {
10291                Slog.e(TAG, "Copying native libraries failed", e);
10292                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10293            } finally {
10294                IoUtils.closeQuietly(handle);
10295            }
10296
10297            return ret;
10298        }
10299
10300        int doPreInstall(int status) {
10301            if (status != PackageManager.INSTALL_SUCCEEDED) {
10302                cleanUp();
10303            }
10304            return status;
10305        }
10306
10307        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10308            if (status != PackageManager.INSTALL_SUCCEEDED) {
10309                cleanUp();
10310                return false;
10311            }
10312
10313            final File targetDir = codeFile.getParentFile();
10314            final File beforeCodeFile = codeFile;
10315            final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName);
10316
10317            Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
10318            try {
10319                Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
10320            } catch (ErrnoException e) {
10321                Slog.d(TAG, "Failed to rename", e);
10322                return false;
10323            }
10324
10325            if (!SELinux.restoreconRecursive(afterCodeFile)) {
10326                Slog.d(TAG, "Failed to restorecon");
10327                return false;
10328            }
10329
10330            // Reflect the rename internally
10331            codeFile = afterCodeFile;
10332            resourceFile = afterCodeFile;
10333
10334            // Reflect the rename in scanned details
10335            pkg.codePath = afterCodeFile.getAbsolutePath();
10336            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10337                    pkg.baseCodePath);
10338            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10339                    pkg.splitCodePaths);
10340
10341            // Reflect the rename in app info
10342            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10343            pkg.applicationInfo.setCodePath(pkg.codePath);
10344            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10345            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10346            pkg.applicationInfo.setResourcePath(pkg.codePath);
10347            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10348            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10349
10350            return true;
10351        }
10352
10353        int doPostInstall(int status, int uid) {
10354            if (status != PackageManager.INSTALL_SUCCEEDED) {
10355                cleanUp();
10356            }
10357            return status;
10358        }
10359
10360        @Override
10361        String getCodePath() {
10362            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10363        }
10364
10365        @Override
10366        String getResourcePath() {
10367            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10368        }
10369
10370        private boolean cleanUp() {
10371            if (codeFile == null || !codeFile.exists()) {
10372                return false;
10373            }
10374
10375            if (codeFile.isDirectory()) {
10376                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10377            } else {
10378                codeFile.delete();
10379            }
10380
10381            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10382                resourceFile.delete();
10383            }
10384
10385            return true;
10386        }
10387
10388        void cleanUpResourcesLI() {
10389            // Try enumerating all code paths before deleting
10390            List<String> allCodePaths = Collections.EMPTY_LIST;
10391            if (codeFile != null && codeFile.exists()) {
10392                try {
10393                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10394                    allCodePaths = pkg.getAllCodePaths();
10395                } catch (PackageParserException e) {
10396                    // Ignored; we tried our best
10397                }
10398            }
10399
10400            cleanUp();
10401            removeDexFiles(allCodePaths, instructionSets);
10402        }
10403
10404        boolean doPostDeleteLI(boolean delete) {
10405            // XXX err, shouldn't we respect the delete flag?
10406            cleanUpResourcesLI();
10407            return true;
10408        }
10409    }
10410
10411    private boolean isAsecExternal(String cid) {
10412        final String asecPath = PackageHelper.getSdFilesystem(cid);
10413        return !asecPath.startsWith(mAsecInternalPath);
10414    }
10415
10416    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10417            PackageManagerException {
10418        if (copyRet < 0) {
10419            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10420                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10421                throw new PackageManagerException(copyRet, message);
10422            }
10423        }
10424    }
10425
10426    /**
10427     * Extract the MountService "container ID" from the full code path of an
10428     * .apk.
10429     */
10430    static String cidFromCodePath(String fullCodePath) {
10431        int eidx = fullCodePath.lastIndexOf("/");
10432        String subStr1 = fullCodePath.substring(0, eidx);
10433        int sidx = subStr1.lastIndexOf("/");
10434        return subStr1.substring(sidx+1, eidx);
10435    }
10436
10437    /**
10438     * Logic to handle installation of ASEC applications, including copying and
10439     * renaming logic.
10440     */
10441    class AsecInstallArgs extends InstallArgs {
10442        static final String RES_FILE_NAME = "pkg.apk";
10443        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10444
10445        String cid;
10446        String packagePath;
10447        String resourcePath;
10448
10449        /** New install */
10450        AsecInstallArgs(InstallParams params) {
10451            super(params.origin, params.move, params.observer, params.installFlags,
10452                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10453                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10454        }
10455
10456        /** Existing install */
10457        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10458                        boolean isExternal, boolean isForwardLocked) {
10459            super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0)
10460                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10461                    instructionSets, null);
10462            // Hackily pretend we're still looking at a full code path
10463            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10464                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10465            }
10466
10467            // Extract cid from fullCodePath
10468            int eidx = fullCodePath.lastIndexOf("/");
10469            String subStr1 = fullCodePath.substring(0, eidx);
10470            int sidx = subStr1.lastIndexOf("/");
10471            cid = subStr1.substring(sidx+1, eidx);
10472            setMountPath(subStr1);
10473        }
10474
10475        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10476            super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10477                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, null,
10478                    instructionSets, null);
10479            this.cid = cid;
10480            setMountPath(PackageHelper.getSdDir(cid));
10481        }
10482
10483        void createCopyFile() {
10484            cid = mInstallerService.allocateExternalStageCidLegacy();
10485        }
10486
10487        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10488            if (origin.staged) {
10489                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10490                cid = origin.cid;
10491                setMountPath(PackageHelper.getSdDir(cid));
10492                return PackageManager.INSTALL_SUCCEEDED;
10493            }
10494
10495            if (temp) {
10496                createCopyFile();
10497            } else {
10498                /*
10499                 * Pre-emptively destroy the container since it's destroyed if
10500                 * copying fails due to it existing anyway.
10501                 */
10502                PackageHelper.destroySdDir(cid);
10503            }
10504
10505            final String newMountPath = imcs.copyPackageToContainer(
10506                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(),
10507                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10508
10509            if (newMountPath != null) {
10510                setMountPath(newMountPath);
10511                return PackageManager.INSTALL_SUCCEEDED;
10512            } else {
10513                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10514            }
10515        }
10516
10517        @Override
10518        String getCodePath() {
10519            return packagePath;
10520        }
10521
10522        @Override
10523        String getResourcePath() {
10524            return resourcePath;
10525        }
10526
10527        int doPreInstall(int status) {
10528            if (status != PackageManager.INSTALL_SUCCEEDED) {
10529                // Destroy container
10530                PackageHelper.destroySdDir(cid);
10531            } else {
10532                boolean mounted = PackageHelper.isContainerMounted(cid);
10533                if (!mounted) {
10534                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10535                            Process.SYSTEM_UID);
10536                    if (newMountPath != null) {
10537                        setMountPath(newMountPath);
10538                    } else {
10539                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10540                    }
10541                }
10542            }
10543            return status;
10544        }
10545
10546        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10547            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10548            String newMountPath = null;
10549            if (PackageHelper.isContainerMounted(cid)) {
10550                // Unmount the container
10551                if (!PackageHelper.unMountSdDir(cid)) {
10552                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10553                    return false;
10554                }
10555            }
10556            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10557                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10558                        " which might be stale. Will try to clean up.");
10559                // Clean up the stale container and proceed to recreate.
10560                if (!PackageHelper.destroySdDir(newCacheId)) {
10561                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10562                    return false;
10563                }
10564                // Successfully cleaned up stale container. Try to rename again.
10565                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10566                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10567                            + " inspite of cleaning it up.");
10568                    return false;
10569                }
10570            }
10571            if (!PackageHelper.isContainerMounted(newCacheId)) {
10572                Slog.w(TAG, "Mounting container " + newCacheId);
10573                newMountPath = PackageHelper.mountSdDir(newCacheId,
10574                        getEncryptKey(), Process.SYSTEM_UID);
10575            } else {
10576                newMountPath = PackageHelper.getSdDir(newCacheId);
10577            }
10578            if (newMountPath == null) {
10579                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10580                return false;
10581            }
10582            Log.i(TAG, "Succesfully renamed " + cid +
10583                    " to " + newCacheId +
10584                    " at new path: " + newMountPath);
10585            cid = newCacheId;
10586
10587            final File beforeCodeFile = new File(packagePath);
10588            setMountPath(newMountPath);
10589            final File afterCodeFile = new File(packagePath);
10590
10591            // Reflect the rename in scanned details
10592            pkg.codePath = afterCodeFile.getAbsolutePath();
10593            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10594                    pkg.baseCodePath);
10595            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10596                    pkg.splitCodePaths);
10597
10598            // Reflect the rename in app info
10599            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10600            pkg.applicationInfo.setCodePath(pkg.codePath);
10601            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10602            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10603            pkg.applicationInfo.setResourcePath(pkg.codePath);
10604            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10605            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10606
10607            return true;
10608        }
10609
10610        private void setMountPath(String mountPath) {
10611            final File mountFile = new File(mountPath);
10612
10613            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10614            if (monolithicFile.exists()) {
10615                packagePath = monolithicFile.getAbsolutePath();
10616                if (isFwdLocked()) {
10617                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10618                } else {
10619                    resourcePath = packagePath;
10620                }
10621            } else {
10622                packagePath = mountFile.getAbsolutePath();
10623                resourcePath = packagePath;
10624            }
10625        }
10626
10627        int doPostInstall(int status, int uid) {
10628            if (status != PackageManager.INSTALL_SUCCEEDED) {
10629                cleanUp();
10630            } else {
10631                final int groupOwner;
10632                final String protectedFile;
10633                if (isFwdLocked()) {
10634                    groupOwner = UserHandle.getSharedAppGid(uid);
10635                    protectedFile = RES_FILE_NAME;
10636                } else {
10637                    groupOwner = -1;
10638                    protectedFile = null;
10639                }
10640
10641                if (uid < Process.FIRST_APPLICATION_UID
10642                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10643                    Slog.e(TAG, "Failed to finalize " + cid);
10644                    PackageHelper.destroySdDir(cid);
10645                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10646                }
10647
10648                boolean mounted = PackageHelper.isContainerMounted(cid);
10649                if (!mounted) {
10650                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10651                }
10652            }
10653            return status;
10654        }
10655
10656        private void cleanUp() {
10657            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10658
10659            // Destroy secure container
10660            PackageHelper.destroySdDir(cid);
10661        }
10662
10663        private List<String> getAllCodePaths() {
10664            final File codeFile = new File(getCodePath());
10665            if (codeFile != null && codeFile.exists()) {
10666                try {
10667                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10668                    return pkg.getAllCodePaths();
10669                } catch (PackageParserException e) {
10670                    // Ignored; we tried our best
10671                }
10672            }
10673            return Collections.EMPTY_LIST;
10674        }
10675
10676        void cleanUpResourcesLI() {
10677            // Enumerate all code paths before deleting
10678            cleanUpResourcesLI(getAllCodePaths());
10679        }
10680
10681        private void cleanUpResourcesLI(List<String> allCodePaths) {
10682            cleanUp();
10683            removeDexFiles(allCodePaths, instructionSets);
10684        }
10685
10686        String getPackageName() {
10687            return getAsecPackageName(cid);
10688        }
10689
10690        boolean doPostDeleteLI(boolean delete) {
10691            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10692            final List<String> allCodePaths = getAllCodePaths();
10693            boolean mounted = PackageHelper.isContainerMounted(cid);
10694            if (mounted) {
10695                // Unmount first
10696                if (PackageHelper.unMountSdDir(cid)) {
10697                    mounted = false;
10698                }
10699            }
10700            if (!mounted && delete) {
10701                cleanUpResourcesLI(allCodePaths);
10702            }
10703            return !mounted;
10704        }
10705
10706        @Override
10707        int doPreCopy() {
10708            if (isFwdLocked()) {
10709                if (!PackageHelper.fixSdPermissions(cid,
10710                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10711                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10712                }
10713            }
10714
10715            return PackageManager.INSTALL_SUCCEEDED;
10716        }
10717
10718        @Override
10719        int doPostCopy(int uid) {
10720            if (isFwdLocked()) {
10721                if (uid < Process.FIRST_APPLICATION_UID
10722                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10723                                RES_FILE_NAME)) {
10724                    Slog.e(TAG, "Failed to finalize " + cid);
10725                    PackageHelper.destroySdDir(cid);
10726                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10727                }
10728            }
10729
10730            return PackageManager.INSTALL_SUCCEEDED;
10731        }
10732    }
10733
10734    /**
10735     * Logic to handle movement of existing installed applications.
10736     */
10737    class MoveInstallArgs extends InstallArgs {
10738        private File codeFile;
10739        private File resourceFile;
10740
10741        /** New install */
10742        MoveInstallArgs(InstallParams params) {
10743            super(params.origin, params.move, params.observer, params.installFlags,
10744                    params.installerPackageName, params.volumeUuid, params.getManifestDigest(),
10745                    params.getUser(), null /* instruction sets */, params.packageAbiOverride);
10746        }
10747
10748        int copyApk(IMediaContainerService imcs, boolean temp) {
10749            Slog.d(TAG, "Moving " + move.packageName + " from " + move.fromUuid + " to "
10750                    + move.toUuid);
10751            synchronized (mInstaller) {
10752                if (mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName,
10753                        move.dataAppName, move.appId, move.seinfo) != 0) {
10754                    return PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
10755                }
10756            }
10757
10758            codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName);
10759            resourceFile = codeFile;
10760            Slog.d(TAG, "codeFile after move is " + codeFile);
10761
10762            return PackageManager.INSTALL_SUCCEEDED;
10763        }
10764
10765        int doPreInstall(int status) {
10766            if (status != PackageManager.INSTALL_SUCCEEDED) {
10767                cleanUp();
10768            }
10769            return status;
10770        }
10771
10772        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10773            if (status != PackageManager.INSTALL_SUCCEEDED) {
10774                cleanUp();
10775                return false;
10776            }
10777
10778            // Reflect the move in app info
10779            pkg.applicationInfo.volumeUuid = pkg.volumeUuid;
10780            pkg.applicationInfo.setCodePath(pkg.codePath);
10781            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10782            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10783            pkg.applicationInfo.setResourcePath(pkg.codePath);
10784            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10785            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10786
10787            return true;
10788        }
10789
10790        int doPostInstall(int status, int uid) {
10791            if (status != PackageManager.INSTALL_SUCCEEDED) {
10792                cleanUp();
10793            }
10794            return status;
10795        }
10796
10797        @Override
10798        String getCodePath() {
10799            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10800        }
10801
10802        @Override
10803        String getResourcePath() {
10804            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10805        }
10806
10807        private boolean cleanUp() {
10808            if (codeFile == null || !codeFile.exists()) {
10809                return false;
10810            }
10811
10812            if (codeFile.isDirectory()) {
10813                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10814            } else {
10815                codeFile.delete();
10816            }
10817
10818            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10819                resourceFile.delete();
10820            }
10821
10822            return true;
10823        }
10824
10825        void cleanUpResourcesLI() {
10826            cleanUp();
10827        }
10828
10829        boolean doPostDeleteLI(boolean delete) {
10830            // XXX err, shouldn't we respect the delete flag?
10831            cleanUpResourcesLI();
10832            return true;
10833        }
10834    }
10835
10836    static String getAsecPackageName(String packageCid) {
10837        int idx = packageCid.lastIndexOf("-");
10838        if (idx == -1) {
10839            return packageCid;
10840        }
10841        return packageCid.substring(0, idx);
10842    }
10843
10844    // Utility method used to create code paths based on package name and available index.
10845    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10846        String idxStr = "";
10847        int idx = 1;
10848        // Fall back to default value of idx=1 if prefix is not
10849        // part of oldCodePath
10850        if (oldCodePath != null) {
10851            String subStr = oldCodePath;
10852            // Drop the suffix right away
10853            if (suffix != null && subStr.endsWith(suffix)) {
10854                subStr = subStr.substring(0, subStr.length() - suffix.length());
10855            }
10856            // If oldCodePath already contains prefix find out the
10857            // ending index to either increment or decrement.
10858            int sidx = subStr.lastIndexOf(prefix);
10859            if (sidx != -1) {
10860                subStr = subStr.substring(sidx + prefix.length());
10861                if (subStr != null) {
10862                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10863                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10864                    }
10865                    try {
10866                        idx = Integer.parseInt(subStr);
10867                        if (idx <= 1) {
10868                            idx++;
10869                        } else {
10870                            idx--;
10871                        }
10872                    } catch(NumberFormatException e) {
10873                    }
10874                }
10875            }
10876        }
10877        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10878        return prefix + idxStr;
10879    }
10880
10881    private File getNextCodePath(File targetDir, String packageName) {
10882        int suffix = 1;
10883        File result;
10884        do {
10885            result = new File(targetDir, packageName + "-" + suffix);
10886            suffix++;
10887        } while (result.exists());
10888        return result;
10889    }
10890
10891    // Utility method that returns the relative package path with respect
10892    // to the installation directory. Like say for /data/data/com.test-1.apk
10893    // string com.test-1 is returned.
10894    static String deriveCodePathName(String codePath) {
10895        if (codePath == null) {
10896            return null;
10897        }
10898        final File codeFile = new File(codePath);
10899        final String name = codeFile.getName();
10900        if (codeFile.isDirectory()) {
10901            return name;
10902        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10903            final int lastDot = name.lastIndexOf('.');
10904            return name.substring(0, lastDot);
10905        } else {
10906            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10907            return null;
10908        }
10909    }
10910
10911    class PackageInstalledInfo {
10912        String name;
10913        int uid;
10914        // The set of users that originally had this package installed.
10915        int[] origUsers;
10916        // The set of users that now have this package installed.
10917        int[] newUsers;
10918        PackageParser.Package pkg;
10919        int returnCode;
10920        String returnMsg;
10921        PackageRemovedInfo removedInfo;
10922
10923        public void setError(int code, String msg) {
10924            returnCode = code;
10925            returnMsg = msg;
10926            Slog.w(TAG, msg);
10927        }
10928
10929        public void setError(String msg, PackageParserException e) {
10930            returnCode = e.error;
10931            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10932            Slog.w(TAG, msg, e);
10933        }
10934
10935        public void setError(String msg, PackageManagerException e) {
10936            returnCode = e.error;
10937            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10938            Slog.w(TAG, msg, e);
10939        }
10940
10941        // In some error cases we want to convey more info back to the observer
10942        String origPackage;
10943        String origPermission;
10944    }
10945
10946    /*
10947     * Install a non-existing package.
10948     */
10949    private void installNewPackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
10950            UserHandle user, String installerPackageName, String volumeUuid,
10951            PackageInstalledInfo res) {
10952        // Remember this for later, in case we need to rollback this install
10953        String pkgName = pkg.packageName;
10954
10955        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10956        final boolean dataDirExists = PackageManager.getDataDirForUser(volumeUuid, pkgName,
10957                UserHandle.USER_OWNER).exists();
10958        synchronized(mPackages) {
10959            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10960                // A package with the same name is already installed, though
10961                // it has been renamed to an older name.  The package we
10962                // are trying to install should be installed as an update to
10963                // the existing one, but that has not been requested, so bail.
10964                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10965                        + " without first uninstalling package running as "
10966                        + mSettings.mRenamedPackages.get(pkgName));
10967                return;
10968            }
10969            if (mPackages.containsKey(pkgName)) {
10970                // Don't allow installation over an existing package with the same name.
10971                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10972                        + " without first uninstalling.");
10973                return;
10974            }
10975        }
10976
10977        try {
10978            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10979                    System.currentTimeMillis(), user);
10980
10981            updateSettingsLI(newPackage, installerPackageName, volumeUuid, null, null, res, user);
10982            // delete the partially installed application. the data directory will have to be
10983            // restored if it was already existing
10984            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10985                // remove package from internal structures.  Note that we want deletePackageX to
10986                // delete the package data and cache directories that it created in
10987                // scanPackageLocked, unless those directories existed before we even tried to
10988                // install.
10989                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10990                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10991                                res.removedInfo, true);
10992            }
10993
10994        } catch (PackageManagerException e) {
10995            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10996        }
10997    }
10998
10999    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
11000        // Upgrade keysets are being used.  Determine if new package has a superset of the
11001        // required keys.
11002        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
11003        KeySetManagerService ksms = mSettings.mKeySetManagerService;
11004        for (int i = 0; i < upgradeKeySets.length; i++) {
11005            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
11006            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
11007                return true;
11008            }
11009        }
11010        return false;
11011    }
11012
11013    private void replacePackageLI(PackageParser.Package pkg, int parseFlags, int scanFlags,
11014            UserHandle user, String installerPackageName, String volumeUuid,
11015            PackageInstalledInfo res) {
11016        final PackageParser.Package oldPackage;
11017        final String pkgName = pkg.packageName;
11018        final int[] allUsers;
11019        final boolean[] perUserInstalled;
11020        final boolean weFroze;
11021
11022        // First find the old package info and check signatures
11023        synchronized(mPackages) {
11024            oldPackage = mPackages.get(pkgName);
11025            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
11026            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11027            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11028                // default to original signature matching
11029                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
11030                    != PackageManager.SIGNATURE_MATCH) {
11031                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11032                            "New package has a different signature: " + pkgName);
11033                    return;
11034                }
11035            } else {
11036                if(!checkUpgradeKeySetLP(ps, pkg)) {
11037                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
11038                            "New package not signed by keys specified by upgrade-keysets: "
11039                            + pkgName);
11040                    return;
11041                }
11042            }
11043
11044            // In case of rollback, remember per-user/profile install state
11045            allUsers = sUserManager.getUserIds();
11046            perUserInstalled = new boolean[allUsers.length];
11047            for (int i = 0; i < allUsers.length; i++) {
11048                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11049            }
11050
11051            // Mark the app as frozen to prevent launching during the upgrade
11052            // process, and then kill all running instances
11053            if (!ps.frozen) {
11054                ps.frozen = true;
11055                weFroze = true;
11056            } else {
11057                weFroze = false;
11058            }
11059        }
11060
11061        // Now that we're guarded by frozen state, kill app during upgrade
11062        killApplication(pkgName, oldPackage.applicationInfo.uid, "replace pkg");
11063
11064        try {
11065            boolean sysPkg = (isSystemApp(oldPackage));
11066            if (sysPkg) {
11067                replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11068                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11069            } else {
11070                replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
11071                        user, allUsers, perUserInstalled, installerPackageName, volumeUuid, res);
11072            }
11073        } finally {
11074            // Regardless of success or failure of upgrade steps above, always
11075            // unfreeze the package if we froze it
11076            if (weFroze) {
11077                unfreezePackage(pkgName);
11078            }
11079        }
11080    }
11081
11082    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
11083            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11084            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11085            String volumeUuid, PackageInstalledInfo res) {
11086        String pkgName = deletedPackage.packageName;
11087        boolean deletedPkg = true;
11088        boolean updatedSettings = false;
11089
11090        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
11091                + deletedPackage);
11092        long origUpdateTime;
11093        if (pkg.mExtras != null) {
11094            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
11095        } else {
11096            origUpdateTime = 0;
11097        }
11098
11099        // First delete the existing package while retaining the data directory
11100        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
11101                res.removedInfo, true)) {
11102            // If the existing package wasn't successfully deleted
11103            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
11104            deletedPkg = false;
11105        } else {
11106            // Successfully deleted the old package; proceed with replace.
11107
11108            // If deleted package lived in a container, give users a chance to
11109            // relinquish resources before killing.
11110            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
11111                if (DEBUG_INSTALL) {
11112                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
11113                }
11114                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
11115                final ArrayList<String> pkgList = new ArrayList<String>(1);
11116                pkgList.add(deletedPackage.applicationInfo.packageName);
11117                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
11118            }
11119
11120            deleteCodeCacheDirsLI(pkg.volumeUuid, pkgName);
11121            try {
11122                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
11123                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
11124                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11125                        perUserInstalled, res, user);
11126                updatedSettings = true;
11127            } catch (PackageManagerException e) {
11128                res.setError("Package couldn't be installed in " + pkg.codePath, e);
11129            }
11130        }
11131
11132        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11133            // remove package from internal structures.  Note that we want deletePackageX to
11134            // delete the package data and cache directories that it created in
11135            // scanPackageLocked, unless those directories existed before we even tried to
11136            // install.
11137            if(updatedSettings) {
11138                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
11139                deletePackageLI(
11140                        pkgName, null, true, allUsers, perUserInstalled,
11141                        PackageManager.DELETE_KEEP_DATA,
11142                                res.removedInfo, true);
11143            }
11144            // Since we failed to install the new package we need to restore the old
11145            // package that we deleted.
11146            if (deletedPkg) {
11147                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
11148                File restoreFile = new File(deletedPackage.codePath);
11149                // Parse old package
11150                boolean oldExternal = isExternal(deletedPackage);
11151                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
11152                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
11153                        (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11154                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
11155                try {
11156                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
11157                } catch (PackageManagerException e) {
11158                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
11159                            + e.getMessage());
11160                    return;
11161                }
11162                // Restore of old package succeeded. Update permissions.
11163                // writer
11164                synchronized (mPackages) {
11165                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
11166                            UPDATE_PERMISSIONS_ALL);
11167                    // can downgrade to reader
11168                    mSettings.writeLPr();
11169                }
11170                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
11171            }
11172        }
11173    }
11174
11175    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
11176            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
11177            int[] allUsers, boolean[] perUserInstalled, String installerPackageName,
11178            String volumeUuid, PackageInstalledInfo res) {
11179        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
11180                + ", old=" + deletedPackage);
11181        boolean disabledSystem = false;
11182        boolean updatedSettings = false;
11183        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
11184        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
11185                != 0) {
11186            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11187        }
11188        String packageName = deletedPackage.packageName;
11189        if (packageName == null) {
11190            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11191                    "Attempt to delete null packageName.");
11192            return;
11193        }
11194        PackageParser.Package oldPkg;
11195        PackageSetting oldPkgSetting;
11196        // reader
11197        synchronized (mPackages) {
11198            oldPkg = mPackages.get(packageName);
11199            oldPkgSetting = mSettings.mPackages.get(packageName);
11200            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
11201                    (oldPkgSetting == null)) {
11202                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
11203                        "Couldn't find package:" + packageName + " information");
11204                return;
11205            }
11206        }
11207
11208        res.removedInfo.uid = oldPkg.applicationInfo.uid;
11209        res.removedInfo.removedPackage = packageName;
11210        // Remove existing system package
11211        removePackageLI(oldPkgSetting, true);
11212        // writer
11213        synchronized (mPackages) {
11214            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
11215            if (!disabledSystem && deletedPackage != null) {
11216                // We didn't need to disable the .apk as a current system package,
11217                // which means we are replacing another update that is already
11218                // installed.  We need to make sure to delete the older one's .apk.
11219                res.removedInfo.args = createInstallArgsForExisting(0,
11220                        deletedPackage.applicationInfo.getCodePath(),
11221                        deletedPackage.applicationInfo.getResourcePath(),
11222                        getAppDexInstructionSets(deletedPackage.applicationInfo));
11223            } else {
11224                res.removedInfo.args = null;
11225            }
11226        }
11227
11228        // Successfully disabled the old package. Now proceed with re-installation
11229        deleteCodeCacheDirsLI(pkg.volumeUuid, packageName);
11230
11231        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11232        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
11233
11234        PackageParser.Package newPackage = null;
11235        try {
11236            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
11237            if (newPackage.mExtras != null) {
11238                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
11239                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
11240                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
11241
11242                // is the update attempting to change shared user? that isn't going to work...
11243                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
11244                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
11245                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
11246                            + " to " + newPkgSetting.sharedUser);
11247                    updatedSettings = true;
11248                }
11249            }
11250
11251            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
11252                updateSettingsLI(newPackage, installerPackageName, volumeUuid, allUsers,
11253                        perUserInstalled, res, user);
11254                updatedSettings = true;
11255            }
11256
11257        } catch (PackageManagerException e) {
11258            res.setError("Package couldn't be installed in " + pkg.codePath, e);
11259        }
11260
11261        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
11262            // Re installation failed. Restore old information
11263            // Remove new pkg information
11264            if (newPackage != null) {
11265                removeInstalledPackageLI(newPackage, true);
11266            }
11267            // Add back the old system package
11268            try {
11269                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
11270            } catch (PackageManagerException e) {
11271                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
11272            }
11273            // Restore the old system information in Settings
11274            synchronized (mPackages) {
11275                if (disabledSystem) {
11276                    mSettings.enableSystemPackageLPw(packageName);
11277                }
11278                if (updatedSettings) {
11279                    mSettings.setInstallerPackageName(packageName,
11280                            oldPkgSetting.installerPackageName);
11281                }
11282                mSettings.writeLPr();
11283            }
11284        }
11285    }
11286
11287    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
11288            String volumeUuid, int[] allUsers, boolean[] perUserInstalled, PackageInstalledInfo res,
11289            UserHandle user) {
11290        String pkgName = newPackage.packageName;
11291        synchronized (mPackages) {
11292            //write settings. the installStatus will be incomplete at this stage.
11293            //note that the new package setting would have already been
11294            //added to mPackages. It hasn't been persisted yet.
11295            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
11296            mSettings.writeLPr();
11297        }
11298
11299        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
11300
11301        synchronized (mPackages) {
11302            updatePermissionsLPw(newPackage.packageName, newPackage,
11303                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
11304                            ? UPDATE_PERMISSIONS_ALL : 0));
11305            // For system-bundled packages, we assume that installing an upgraded version
11306            // of the package implies that the user actually wants to run that new code,
11307            // so we enable the package.
11308            PackageSetting ps = mSettings.mPackages.get(pkgName);
11309            if (ps != null) {
11310                if (isSystemApp(newPackage)) {
11311                    // NB: implicit assumption that system package upgrades apply to all users
11312                    if (DEBUG_INSTALL) {
11313                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
11314                    }
11315                    if (res.origUsers != null) {
11316                        for (int userHandle : res.origUsers) {
11317                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
11318                                    userHandle, installerPackageName);
11319                        }
11320                    }
11321                    // Also convey the prior install/uninstall state
11322                    if (allUsers != null && perUserInstalled != null) {
11323                        for (int i = 0; i < allUsers.length; i++) {
11324                            if (DEBUG_INSTALL) {
11325                                Slog.d(TAG, "    user " + allUsers[i]
11326                                        + " => " + perUserInstalled[i]);
11327                            }
11328                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
11329                        }
11330                        // these install state changes will be persisted in the
11331                        // upcoming call to mSettings.writeLPr().
11332                    }
11333                }
11334                // It's implied that when a user requests installation, they want the app to be
11335                // installed and enabled.
11336                int userId = user.getIdentifier();
11337                if (userId != UserHandle.USER_ALL) {
11338                    ps.setInstalled(true, userId);
11339                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
11340                }
11341            }
11342            res.name = pkgName;
11343            res.uid = newPackage.applicationInfo.uid;
11344            res.pkg = newPackage;
11345            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
11346            mSettings.setInstallerPackageName(pkgName, installerPackageName);
11347            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11348            //to update install status
11349            mSettings.writeLPr();
11350        }
11351    }
11352
11353    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
11354        final int installFlags = args.installFlags;
11355        final String installerPackageName = args.installerPackageName;
11356        final String volumeUuid = args.volumeUuid;
11357        final File tmpPackageFile = new File(args.getCodePath());
11358        final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
11359        final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0)
11360                || (args.volumeUuid != null));
11361        boolean replace = false;
11362        int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
11363        // Result object to be returned
11364        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
11365
11366        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
11367        // Retrieve PackageSettings and parse package
11368        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
11369                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
11370                | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0);
11371        PackageParser pp = new PackageParser();
11372        pp.setSeparateProcesses(mSeparateProcesses);
11373        pp.setDisplayMetrics(mMetrics);
11374
11375        final PackageParser.Package pkg;
11376        try {
11377            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
11378        } catch (PackageParserException e) {
11379            res.setError("Failed parse during installPackageLI", e);
11380            return;
11381        }
11382
11383        // Mark that we have an install time CPU ABI override.
11384        pkg.cpuAbiOverride = args.abiOverride;
11385
11386        String pkgName = res.name = pkg.packageName;
11387        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
11388            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
11389                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
11390                return;
11391            }
11392        }
11393
11394        try {
11395            pp.collectCertificates(pkg, parseFlags);
11396            pp.collectManifestDigest(pkg);
11397        } catch (PackageParserException e) {
11398            res.setError("Failed collect during installPackageLI", e);
11399            return;
11400        }
11401
11402        /* If the installer passed in a manifest digest, compare it now. */
11403        if (args.manifestDigest != null) {
11404            if (DEBUG_INSTALL) {
11405                final String parsedManifest = pkg.manifestDigest == null ? "null"
11406                        : pkg.manifestDigest.toString();
11407                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
11408                        + parsedManifest);
11409            }
11410
11411            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
11412                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
11413                return;
11414            }
11415        } else if (DEBUG_INSTALL) {
11416            final String parsedManifest = pkg.manifestDigest == null
11417                    ? "null" : pkg.manifestDigest.toString();
11418            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
11419        }
11420
11421        // Get rid of all references to package scan path via parser.
11422        pp = null;
11423        String oldCodePath = null;
11424        boolean systemApp = false;
11425        synchronized (mPackages) {
11426            // Check if installing already existing package
11427            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11428                String oldName = mSettings.mRenamedPackages.get(pkgName);
11429                if (pkg.mOriginalPackages != null
11430                        && pkg.mOriginalPackages.contains(oldName)
11431                        && mPackages.containsKey(oldName)) {
11432                    // This package is derived from an original package,
11433                    // and this device has been updating from that original
11434                    // name.  We must continue using the original name, so
11435                    // rename the new package here.
11436                    pkg.setPackageName(oldName);
11437                    pkgName = pkg.packageName;
11438                    replace = true;
11439                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11440                            + oldName + " pkgName=" + pkgName);
11441                } else if (mPackages.containsKey(pkgName)) {
11442                    // This package, under its official name, already exists
11443                    // on the device; we should replace it.
11444                    replace = true;
11445                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11446                }
11447            }
11448
11449            PackageSetting ps = mSettings.mPackages.get(pkgName);
11450            if (ps != null) {
11451                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11452
11453                // Quick sanity check that we're signed correctly if updating;
11454                // we'll check this again later when scanning, but we want to
11455                // bail early here before tripping over redefined permissions.
11456                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11457                    try {
11458                        verifySignaturesLP(ps, pkg);
11459                    } catch (PackageManagerException e) {
11460                        res.setError(e.error, e.getMessage());
11461                        return;
11462                    }
11463                } else {
11464                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11465                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11466                                + pkg.packageName + " upgrade keys do not match the "
11467                                + "previously installed version");
11468                        return;
11469                    }
11470                }
11471
11472                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11473                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11474                    systemApp = (ps.pkg.applicationInfo.flags &
11475                            ApplicationInfo.FLAG_SYSTEM) != 0;
11476                }
11477                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11478            }
11479
11480            // Check whether the newly-scanned package wants to define an already-defined perm
11481            int N = pkg.permissions.size();
11482            for (int i = N-1; i >= 0; i--) {
11483                PackageParser.Permission perm = pkg.permissions.get(i);
11484                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11485                if (bp != null) {
11486                    // If the defining package is signed with our cert, it's okay.  This
11487                    // also includes the "updating the same package" case, of course.
11488                    // "updating same package" could also involve key-rotation.
11489                    final boolean sigsOk;
11490                    if (!bp.sourcePackage.equals(pkg.packageName)
11491                            || !(bp.packageSetting instanceof PackageSetting)
11492                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11493                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11494                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11495                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11496                    } else {
11497                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11498                    }
11499                    if (!sigsOk) {
11500                        // If the owning package is the system itself, we log but allow
11501                        // install to proceed; we fail the install on all other permission
11502                        // redefinitions.
11503                        if (!bp.sourcePackage.equals("android")) {
11504                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11505                                    + pkg.packageName + " attempting to redeclare permission "
11506                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11507                            res.origPermission = perm.info.name;
11508                            res.origPackage = bp.sourcePackage;
11509                            return;
11510                        } else {
11511                            Slog.w(TAG, "Package " + pkg.packageName
11512                                    + " attempting to redeclare system permission "
11513                                    + perm.info.name + "; ignoring new declaration");
11514                            pkg.permissions.remove(i);
11515                        }
11516                    }
11517                }
11518            }
11519
11520        }
11521
11522        if (systemApp && onExternal) {
11523            // Disable updates to system apps on sdcard
11524            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11525                    "Cannot install updates to system apps on sdcard");
11526            return;
11527        }
11528
11529        if (args.move != null) {
11530            // We did an in-place move, so dex is ready to roll
11531            scanFlags |= SCAN_NO_DEX;
11532        } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) {
11533            // Enable SCAN_NO_DEX flag to skip dexopt at a later stage
11534            scanFlags |= SCAN_NO_DEX;
11535            // Run dexopt before old package gets removed, to minimize time when app is unavailable
11536            int result = mPackageDexOptimizer
11537                    .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11538                            false /* defer */, false /* inclDependencies */);
11539            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11540                res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11541                return;
11542            }
11543        }
11544
11545        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11546            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11547            return;
11548        }
11549
11550        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11551
11552        if (replace) {
11553            replacePackageLI(pkg, parseFlags, scanFlags, args.user,
11554                    installerPackageName, volumeUuid, res);
11555        } else {
11556            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11557                    args.user, installerPackageName, volumeUuid, res);
11558        }
11559        synchronized (mPackages) {
11560            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11561            if (ps != null) {
11562                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11563            }
11564        }
11565    }
11566
11567    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11568        if (mIntentFilterVerifierComponent == null) {
11569            Slog.d(TAG, "No IntentFilter verification will not be done as "
11570                    + "there is no IntentFilterVerifier available!");
11571            return;
11572        }
11573
11574        final int verifierUid = getPackageUid(
11575                mIntentFilterVerifierComponent.getPackageName(),
11576                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11577
11578        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11579        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11580        msg.obj = pkg;
11581        msg.arg1 = userId;
11582        msg.arg2 = verifierUid;
11583
11584        mHandler.sendMessage(msg);
11585    }
11586
11587    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11588            PackageParser.Package pkg) {
11589        int size = pkg.activities.size();
11590        if (size == 0) {
11591            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11592            return;
11593        }
11594
11595        final boolean hasDomainURLs = hasDomainURLs(pkg);
11596        if (!hasDomainURLs) {
11597            Slog.d(TAG, "No domain URLs, so no need to verify any IntentFilter!");
11598            return;
11599        }
11600
11601        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11602                + " Activities needs verification ...");
11603
11604        final int verificationId = mIntentFilterVerificationToken++;
11605        int count = 0;
11606        final String packageName = pkg.packageName;
11607        ArrayList<String> allHosts = new ArrayList<>();
11608
11609        synchronized (mPackages) {
11610            for (PackageParser.Activity a : pkg.activities) {
11611                for (ActivityIntentInfo filter : a.intents) {
11612                    boolean needsFilterVerification = filter.needsVerification();
11613                    if (needsFilterVerification && needsNetworkVerificationLPr(filter)) {
11614                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11615                        mIntentFilterVerifier.addOneIntentFilterVerification(
11616                                verifierUid, userId, verificationId, filter, packageName);
11617                        count++;
11618                    } else if (!needsFilterVerification) {
11619                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11620                        if (hasValidDomains(filter)) {
11621                            ArrayList<String> hosts = filter.getHostsList();
11622                            if (hosts.size() > 0) {
11623                                allHosts.addAll(hosts);
11624                            } else {
11625                                if (allHosts.isEmpty()) {
11626                                    allHosts.add("*");
11627                                }
11628                            }
11629                        }
11630                    } else {
11631                        Slog.d(TAG, "Verification already done for IntentFilter:"
11632                                + filter.toString());
11633                    }
11634                }
11635            }
11636        }
11637
11638        if (count > 0) {
11639            mIntentFilterVerifier.startVerifications(userId);
11640            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11641                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11642        } else {
11643            Slog.d(TAG, "No need to start any IntentFilter verification!");
11644            if (allHosts.size() > 0 && mSettings.createIntentFilterVerificationIfNeededLPw(
11645                    packageName, allHosts) != null) {
11646                scheduleWriteSettingsLocked();
11647            }
11648        }
11649    }
11650
11651    private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) {
11652        final ComponentName cn  = filter.activity.getComponentName();
11653        final String packageName = cn.getPackageName();
11654
11655        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11656                packageName);
11657        if (ivi == null) {
11658            return true;
11659        }
11660        int status = ivi.getStatus();
11661        switch (status) {
11662            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11663            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11664                return true;
11665
11666            default:
11667                // Nothing to do
11668                return false;
11669        }
11670    }
11671
11672    private static boolean isMultiArch(PackageSetting ps) {
11673        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11674    }
11675
11676    private static boolean isMultiArch(ApplicationInfo info) {
11677        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11678    }
11679
11680    private static boolean isExternal(PackageParser.Package pkg) {
11681        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11682    }
11683
11684    private static boolean isExternal(PackageSetting ps) {
11685        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11686    }
11687
11688    private static boolean isExternal(ApplicationInfo info) {
11689        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11690    }
11691
11692    private static boolean isSystemApp(PackageParser.Package pkg) {
11693        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11694    }
11695
11696    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11697        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11698    }
11699
11700    private static boolean hasDomainURLs(PackageParser.Package pkg) {
11701        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0;
11702    }
11703
11704    private static boolean isSystemApp(PackageSetting ps) {
11705        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11706    }
11707
11708    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11709        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11710    }
11711
11712    private int packageFlagsToInstallFlags(PackageSetting ps) {
11713        int installFlags = 0;
11714        if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) {
11715            // This existing package was an external ASEC install when we have
11716            // the external flag without a UUID
11717            installFlags |= PackageManager.INSTALL_EXTERNAL;
11718        }
11719        if (ps.isForwardLocked()) {
11720            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11721        }
11722        return installFlags;
11723    }
11724
11725    private void deleteTempPackageFiles() {
11726        final FilenameFilter filter = new FilenameFilter() {
11727            public boolean accept(File dir, String name) {
11728                return name.startsWith("vmdl") && name.endsWith(".tmp");
11729            }
11730        };
11731        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11732            file.delete();
11733        }
11734    }
11735
11736    @Override
11737    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11738            int flags) {
11739        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11740                flags);
11741    }
11742
11743    @Override
11744    public void deletePackage(final String packageName,
11745            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11746        mContext.enforceCallingOrSelfPermission(
11747                android.Manifest.permission.DELETE_PACKAGES, null);
11748        final int uid = Binder.getCallingUid();
11749        if (UserHandle.getUserId(uid) != userId) {
11750            mContext.enforceCallingPermission(
11751                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11752                    "deletePackage for user " + userId);
11753        }
11754        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11755            try {
11756                observer.onPackageDeleted(packageName,
11757                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11758            } catch (RemoteException re) {
11759            }
11760            return;
11761        }
11762
11763        boolean uninstallBlocked = false;
11764        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11765            int[] users = sUserManager.getUserIds();
11766            for (int i = 0; i < users.length; ++i) {
11767                if (getBlockUninstallForUser(packageName, users[i])) {
11768                    uninstallBlocked = true;
11769                    break;
11770                }
11771            }
11772        } else {
11773            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11774        }
11775        if (uninstallBlocked) {
11776            try {
11777                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11778                        null);
11779            } catch (RemoteException re) {
11780            }
11781            return;
11782        }
11783
11784        if (DEBUG_REMOVE) {
11785            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11786        }
11787        // Queue up an async operation since the package deletion may take a little while.
11788        mHandler.post(new Runnable() {
11789            public void run() {
11790                mHandler.removeCallbacks(this);
11791                final int returnCode = deletePackageX(packageName, userId, flags);
11792                if (observer != null) {
11793                    try {
11794                        observer.onPackageDeleted(packageName, returnCode, null);
11795                    } catch (RemoteException e) {
11796                        Log.i(TAG, "Observer no longer exists.");
11797                    } //end catch
11798                } //end if
11799            } //end run
11800        });
11801    }
11802
11803    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11804        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11805                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11806        try {
11807            if (dpm != null) {
11808                if (dpm.isDeviceOwner(packageName)) {
11809                    return true;
11810                }
11811                int[] users;
11812                if (userId == UserHandle.USER_ALL) {
11813                    users = sUserManager.getUserIds();
11814                } else {
11815                    users = new int[]{userId};
11816                }
11817                for (int i = 0; i < users.length; ++i) {
11818                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11819                        return true;
11820                    }
11821                }
11822            }
11823        } catch (RemoteException e) {
11824        }
11825        return false;
11826    }
11827
11828    /**
11829     *  This method is an internal method that could be get invoked either
11830     *  to delete an installed package or to clean up a failed installation.
11831     *  After deleting an installed package, a broadcast is sent to notify any
11832     *  listeners that the package has been installed. For cleaning up a failed
11833     *  installation, the broadcast is not necessary since the package's
11834     *  installation wouldn't have sent the initial broadcast either
11835     *  The key steps in deleting a package are
11836     *  deleting the package information in internal structures like mPackages,
11837     *  deleting the packages base directories through installd
11838     *  updating mSettings to reflect current status
11839     *  persisting settings for later use
11840     *  sending a broadcast if necessary
11841     */
11842    private int deletePackageX(String packageName, int userId, int flags) {
11843        final PackageRemovedInfo info = new PackageRemovedInfo();
11844        final boolean res;
11845
11846        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11847                ? UserHandle.ALL : new UserHandle(userId);
11848
11849        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11850            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11851            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11852        }
11853
11854        boolean removedForAllUsers = false;
11855        boolean systemUpdate = false;
11856
11857        // for the uninstall-updates case and restricted profiles, remember the per-
11858        // userhandle installed state
11859        int[] allUsers;
11860        boolean[] perUserInstalled;
11861        synchronized (mPackages) {
11862            PackageSetting ps = mSettings.mPackages.get(packageName);
11863            allUsers = sUserManager.getUserIds();
11864            perUserInstalled = new boolean[allUsers.length];
11865            for (int i = 0; i < allUsers.length; i++) {
11866                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11867            }
11868        }
11869
11870        synchronized (mInstallLock) {
11871            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11872            res = deletePackageLI(packageName, removeForUser,
11873                    true, allUsers, perUserInstalled,
11874                    flags | REMOVE_CHATTY, info, true);
11875            systemUpdate = info.isRemovedPackageSystemUpdate;
11876            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11877                removedForAllUsers = true;
11878            }
11879            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11880                    + " removedForAllUsers=" + removedForAllUsers);
11881        }
11882
11883        if (res) {
11884            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11885
11886            // If the removed package was a system update, the old system package
11887            // was re-enabled; we need to broadcast this information
11888            if (systemUpdate) {
11889                Bundle extras = new Bundle(1);
11890                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11891                        ? info.removedAppId : info.uid);
11892                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11893
11894                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11895                        extras, null, null, null);
11896                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11897                        extras, null, null, null);
11898                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11899                        null, packageName, null, null);
11900            }
11901        }
11902        // Force a gc here.
11903        Runtime.getRuntime().gc();
11904        // Delete the resources here after sending the broadcast to let
11905        // other processes clean up before deleting resources.
11906        if (info.args != null) {
11907            synchronized (mInstallLock) {
11908                info.args.doPostDeleteLI(true);
11909            }
11910        }
11911
11912        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11913    }
11914
11915    class PackageRemovedInfo {
11916        String removedPackage;
11917        int uid = -1;
11918        int removedAppId = -1;
11919        int[] removedUsers = null;
11920        boolean isRemovedPackageSystemUpdate = false;
11921        // Clean up resources deleted packages.
11922        InstallArgs args = null;
11923
11924        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11925            Bundle extras = new Bundle(1);
11926            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11927            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11928            if (replacing) {
11929                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11930            }
11931            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11932            if (removedPackage != null) {
11933                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11934                        extras, null, null, removedUsers);
11935                if (fullRemove && !replacing) {
11936                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11937                            extras, null, null, removedUsers);
11938                }
11939            }
11940            if (removedAppId >= 0) {
11941                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11942                        removedUsers);
11943            }
11944        }
11945    }
11946
11947    /*
11948     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11949     * flag is not set, the data directory is removed as well.
11950     * make sure this flag is set for partially installed apps. If not its meaningless to
11951     * delete a partially installed application.
11952     */
11953    private void removePackageDataLI(PackageSetting ps,
11954            int[] allUserHandles, boolean[] perUserInstalled,
11955            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11956        String packageName = ps.name;
11957        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11958        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11959        // Retrieve object to delete permissions for shared user later on
11960        final PackageSetting deletedPs;
11961        // reader
11962        synchronized (mPackages) {
11963            deletedPs = mSettings.mPackages.get(packageName);
11964            if (outInfo != null) {
11965                outInfo.removedPackage = packageName;
11966                outInfo.removedUsers = deletedPs != null
11967                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11968                        : null;
11969            }
11970        }
11971        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11972            removeDataDirsLI(ps.volumeUuid, packageName);
11973            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11974        }
11975        // writer
11976        synchronized (mPackages) {
11977            if (deletedPs != null) {
11978                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11979                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11980                    clearDefaultBrowserIfNeeded(packageName);
11981                    if (outInfo != null) {
11982                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11983                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11984                    }
11985                    updatePermissionsLPw(deletedPs.name, null, 0);
11986                    if (deletedPs.sharedUser != null) {
11987                        // Remove permissions associated with package. Since runtime
11988                        // permissions are per user we have to kill the removed package
11989                        // or packages running under the shared user of the removed
11990                        // package if revoking the permissions requested only by the removed
11991                        // package is successful and this causes a change in gids.
11992                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11993                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11994                                    userId);
11995                            if (userIdToKill == UserHandle.USER_ALL
11996                                    || userIdToKill >= UserHandle.USER_OWNER) {
11997                                // If gids changed for this user, kill all affected packages.
11998                                mHandler.post(new Runnable() {
11999                                    @Override
12000                                    public void run() {
12001                                        // This has to happen with no lock held.
12002                                        killSettingPackagesForUser(deletedPs, userIdToKill,
12003                                                KILL_APP_REASON_GIDS_CHANGED);
12004                                    }
12005                                });
12006                            break;
12007                            }
12008                        }
12009                    }
12010                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
12011                }
12012                // make sure to preserve per-user disabled state if this removal was just
12013                // a downgrade of a system app to the factory package
12014                if (allUserHandles != null && perUserInstalled != null) {
12015                    if (DEBUG_REMOVE) {
12016                        Slog.d(TAG, "Propagating install state across downgrade");
12017                    }
12018                    for (int i = 0; i < allUserHandles.length; i++) {
12019                        if (DEBUG_REMOVE) {
12020                            Slog.d(TAG, "    user " + allUserHandles[i]
12021                                    + " => " + perUserInstalled[i]);
12022                        }
12023                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12024                    }
12025                }
12026            }
12027            // can downgrade to reader
12028            if (writeSettings) {
12029                // Save settings now
12030                mSettings.writeLPr();
12031            }
12032        }
12033        if (outInfo != null) {
12034            // A user ID was deleted here. Go through all users and remove it
12035            // from KeyStore.
12036            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
12037        }
12038    }
12039
12040    static boolean locationIsPrivileged(File path) {
12041        try {
12042            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
12043                    .getCanonicalPath();
12044            return path.getCanonicalPath().startsWith(privilegedAppDir);
12045        } catch (IOException e) {
12046            Slog.e(TAG, "Unable to access code path " + path);
12047        }
12048        return false;
12049    }
12050
12051    /*
12052     * Tries to delete system package.
12053     */
12054    private boolean deleteSystemPackageLI(PackageSetting newPs,
12055            int[] allUserHandles, boolean[] perUserInstalled,
12056            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
12057        final boolean applyUserRestrictions
12058                = (allUserHandles != null) && (perUserInstalled != null);
12059        PackageSetting disabledPs = null;
12060        // Confirm if the system package has been updated
12061        // An updated system app can be deleted. This will also have to restore
12062        // the system pkg from system partition
12063        // reader
12064        synchronized (mPackages) {
12065            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
12066        }
12067        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
12068                + " disabledPs=" + disabledPs);
12069        if (disabledPs == null) {
12070            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
12071            return false;
12072        } else if (DEBUG_REMOVE) {
12073            Slog.d(TAG, "Deleting system pkg from data partition");
12074        }
12075        if (DEBUG_REMOVE) {
12076            if (applyUserRestrictions) {
12077                Slog.d(TAG, "Remembering install states:");
12078                for (int i = 0; i < allUserHandles.length; i++) {
12079                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
12080                }
12081            }
12082        }
12083        // Delete the updated package
12084        outInfo.isRemovedPackageSystemUpdate = true;
12085        if (disabledPs.versionCode < newPs.versionCode) {
12086            // Delete data for downgrades
12087            flags &= ~PackageManager.DELETE_KEEP_DATA;
12088        } else {
12089            // Preserve data by setting flag
12090            flags |= PackageManager.DELETE_KEEP_DATA;
12091        }
12092        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
12093                allUserHandles, perUserInstalled, outInfo, writeSettings);
12094        if (!ret) {
12095            return false;
12096        }
12097        // writer
12098        synchronized (mPackages) {
12099            // Reinstate the old system package
12100            mSettings.enableSystemPackageLPw(newPs.name);
12101            // Remove any native libraries from the upgraded package.
12102            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
12103        }
12104        // Install the system package
12105        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
12106        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
12107        if (locationIsPrivileged(disabledPs.codePath)) {
12108            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
12109        }
12110
12111        final PackageParser.Package newPkg;
12112        try {
12113            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
12114        } catch (PackageManagerException e) {
12115            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
12116            return false;
12117        }
12118
12119        // writer
12120        synchronized (mPackages) {
12121            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
12122            updatePermissionsLPw(newPkg.packageName, newPkg,
12123                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
12124            if (applyUserRestrictions) {
12125                if (DEBUG_REMOVE) {
12126                    Slog.d(TAG, "Propagating install state across reinstall");
12127                }
12128                for (int i = 0; i < allUserHandles.length; i++) {
12129                    if (DEBUG_REMOVE) {
12130                        Slog.d(TAG, "    user " + allUserHandles[i]
12131                                + " => " + perUserInstalled[i]);
12132                    }
12133                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
12134                }
12135                // Regardless of writeSettings we need to ensure that this restriction
12136                // state propagation is persisted
12137                mSettings.writeAllUsersPackageRestrictionsLPr();
12138            }
12139            // can downgrade to reader here
12140            if (writeSettings) {
12141                mSettings.writeLPr();
12142            }
12143        }
12144        return true;
12145    }
12146
12147    private boolean deleteInstalledPackageLI(PackageSetting ps,
12148            boolean deleteCodeAndResources, int flags,
12149            int[] allUserHandles, boolean[] perUserInstalled,
12150            PackageRemovedInfo outInfo, boolean writeSettings) {
12151        if (outInfo != null) {
12152            outInfo.uid = ps.appId;
12153        }
12154
12155        // Delete package data from internal structures and also remove data if flag is set
12156        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
12157
12158        // Delete application code and resources
12159        if (deleteCodeAndResources && (outInfo != null)) {
12160            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
12161                    ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps));
12162            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
12163        }
12164        return true;
12165    }
12166
12167    @Override
12168    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
12169            int userId) {
12170        mContext.enforceCallingOrSelfPermission(
12171                android.Manifest.permission.DELETE_PACKAGES, null);
12172        synchronized (mPackages) {
12173            PackageSetting ps = mSettings.mPackages.get(packageName);
12174            if (ps == null) {
12175                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
12176                return false;
12177            }
12178            if (!ps.getInstalled(userId)) {
12179                // Can't block uninstall for an app that is not installed or enabled.
12180                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
12181                return false;
12182            }
12183            ps.setBlockUninstall(blockUninstall, userId);
12184            mSettings.writePackageRestrictionsLPr(userId);
12185        }
12186        return true;
12187    }
12188
12189    @Override
12190    public boolean getBlockUninstallForUser(String packageName, int userId) {
12191        synchronized (mPackages) {
12192            PackageSetting ps = mSettings.mPackages.get(packageName);
12193            if (ps == null) {
12194                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
12195                return false;
12196            }
12197            return ps.getBlockUninstall(userId);
12198        }
12199    }
12200
12201    /*
12202     * This method handles package deletion in general
12203     */
12204    private boolean deletePackageLI(String packageName, UserHandle user,
12205            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
12206            int flags, PackageRemovedInfo outInfo,
12207            boolean writeSettings) {
12208        if (packageName == null) {
12209            Slog.w(TAG, "Attempt to delete null packageName.");
12210            return false;
12211        }
12212        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
12213        PackageSetting ps;
12214        boolean dataOnly = false;
12215        int removeUser = -1;
12216        int appId = -1;
12217        synchronized (mPackages) {
12218            ps = mSettings.mPackages.get(packageName);
12219            if (ps == null) {
12220                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12221                return false;
12222            }
12223            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
12224                    && user.getIdentifier() != UserHandle.USER_ALL) {
12225                // The caller is asking that the package only be deleted for a single
12226                // user.  To do this, we just mark its uninstalled state and delete
12227                // its data.  If this is a system app, we only allow this to happen if
12228                // they have set the special DELETE_SYSTEM_APP which requests different
12229                // semantics than normal for uninstalling system apps.
12230                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
12231                ps.setUserState(user.getIdentifier(),
12232                        COMPONENT_ENABLED_STATE_DEFAULT,
12233                        false, //installed
12234                        true,  //stopped
12235                        true,  //notLaunched
12236                        false, //hidden
12237                        null, null, null,
12238                        false, // blockUninstall
12239                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
12240                if (!isSystemApp(ps)) {
12241                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
12242                        // Other user still have this package installed, so all
12243                        // we need to do is clear this user's data and save that
12244                        // it is uninstalled.
12245                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
12246                        removeUser = user.getIdentifier();
12247                        appId = ps.appId;
12248                        scheduleWritePackageRestrictionsLocked(removeUser);
12249                    } else {
12250                        // We need to set it back to 'installed' so the uninstall
12251                        // broadcasts will be sent correctly.
12252                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
12253                        ps.setInstalled(true, user.getIdentifier());
12254                    }
12255                } else {
12256                    // This is a system app, so we assume that the
12257                    // other users still have this package installed, so all
12258                    // we need to do is clear this user's data and save that
12259                    // it is uninstalled.
12260                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
12261                    removeUser = user.getIdentifier();
12262                    appId = ps.appId;
12263                    scheduleWritePackageRestrictionsLocked(removeUser);
12264                }
12265            }
12266        }
12267
12268        if (removeUser >= 0) {
12269            // From above, we determined that we are deleting this only
12270            // for a single user.  Continue the work here.
12271            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
12272            if (outInfo != null) {
12273                outInfo.removedPackage = packageName;
12274                outInfo.removedAppId = appId;
12275                outInfo.removedUsers = new int[] {removeUser};
12276            }
12277            mInstaller.clearUserData(ps.volumeUuid, packageName, removeUser);
12278            removeKeystoreDataIfNeeded(removeUser, appId);
12279            schedulePackageCleaning(packageName, removeUser, false);
12280            synchronized (mPackages) {
12281                if (clearPackagePreferredActivitiesLPw(packageName, removeUser)) {
12282                    scheduleWritePackageRestrictionsLocked(removeUser);
12283                }
12284            }
12285            return true;
12286        }
12287
12288        if (dataOnly) {
12289            // Delete application data first
12290            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
12291            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
12292            return true;
12293        }
12294
12295        boolean ret = false;
12296        if (isSystemApp(ps)) {
12297            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
12298            // When an updated system application is deleted we delete the existing resources as well and
12299            // fall back to existing code in system partition
12300            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
12301                    flags, outInfo, writeSettings);
12302        } else {
12303            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
12304            // Kill application pre-emptively especially for apps on sd.
12305            killApplication(packageName, ps.appId, "uninstall pkg");
12306            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
12307                    allUserHandles, perUserInstalled,
12308                    outInfo, writeSettings);
12309        }
12310
12311        return ret;
12312    }
12313
12314    private final class ClearStorageConnection implements ServiceConnection {
12315        IMediaContainerService mContainerService;
12316
12317        @Override
12318        public void onServiceConnected(ComponentName name, IBinder service) {
12319            synchronized (this) {
12320                mContainerService = IMediaContainerService.Stub.asInterface(service);
12321                notifyAll();
12322            }
12323        }
12324
12325        @Override
12326        public void onServiceDisconnected(ComponentName name) {
12327        }
12328    }
12329
12330    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
12331        final boolean mounted;
12332        if (Environment.isExternalStorageEmulated()) {
12333            mounted = true;
12334        } else {
12335            final String status = Environment.getExternalStorageState();
12336
12337            mounted = status.equals(Environment.MEDIA_MOUNTED)
12338                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
12339        }
12340
12341        if (!mounted) {
12342            return;
12343        }
12344
12345        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
12346        int[] users;
12347        if (userId == UserHandle.USER_ALL) {
12348            users = sUserManager.getUserIds();
12349        } else {
12350            users = new int[] { userId };
12351        }
12352        final ClearStorageConnection conn = new ClearStorageConnection();
12353        if (mContext.bindServiceAsUser(
12354                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
12355            try {
12356                for (int curUser : users) {
12357                    long timeout = SystemClock.uptimeMillis() + 5000;
12358                    synchronized (conn) {
12359                        long now = SystemClock.uptimeMillis();
12360                        while (conn.mContainerService == null && now < timeout) {
12361                            try {
12362                                conn.wait(timeout - now);
12363                            } catch (InterruptedException e) {
12364                            }
12365                        }
12366                    }
12367                    if (conn.mContainerService == null) {
12368                        return;
12369                    }
12370
12371                    final UserEnvironment userEnv = new UserEnvironment(curUser);
12372                    clearDirectory(conn.mContainerService,
12373                            userEnv.buildExternalStorageAppCacheDirs(packageName));
12374                    if (allData) {
12375                        clearDirectory(conn.mContainerService,
12376                                userEnv.buildExternalStorageAppDataDirs(packageName));
12377                        clearDirectory(conn.mContainerService,
12378                                userEnv.buildExternalStorageAppMediaDirs(packageName));
12379                    }
12380                }
12381            } finally {
12382                mContext.unbindService(conn);
12383            }
12384        }
12385    }
12386
12387    @Override
12388    public void clearApplicationUserData(final String packageName,
12389            final IPackageDataObserver observer, final int userId) {
12390        mContext.enforceCallingOrSelfPermission(
12391                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
12392        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
12393        // Queue up an async operation since the package deletion may take a little while.
12394        mHandler.post(new Runnable() {
12395            public void run() {
12396                mHandler.removeCallbacks(this);
12397                final boolean succeeded;
12398                synchronized (mInstallLock) {
12399                    succeeded = clearApplicationUserDataLI(packageName, userId);
12400                }
12401                clearExternalStorageDataSync(packageName, userId, true);
12402                if (succeeded) {
12403                    // invoke DeviceStorageMonitor's update method to clear any notifications
12404                    DeviceStorageMonitorInternal
12405                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12406                    if (dsm != null) {
12407                        dsm.checkMemory();
12408                    }
12409                }
12410                if(observer != null) {
12411                    try {
12412                        observer.onRemoveCompleted(packageName, succeeded);
12413                    } catch (RemoteException e) {
12414                        Log.i(TAG, "Observer no longer exists.");
12415                    }
12416                } //end if observer
12417            } //end run
12418        });
12419    }
12420
12421    private boolean clearApplicationUserDataLI(String packageName, int userId) {
12422        if (packageName == null) {
12423            Slog.w(TAG, "Attempt to delete null packageName.");
12424            return false;
12425        }
12426
12427        // Try finding details about the requested package
12428        PackageParser.Package pkg;
12429        synchronized (mPackages) {
12430            pkg = mPackages.get(packageName);
12431            if (pkg == null) {
12432                final PackageSetting ps = mSettings.mPackages.get(packageName);
12433                if (ps != null) {
12434                    pkg = ps.pkg;
12435                }
12436            }
12437        }
12438
12439        if (pkg == null) {
12440            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
12441        }
12442
12443        // Always delete data directories for package, even if we found no other
12444        // record of app. This helps users recover from UID mismatches without
12445        // resorting to a full data wipe.
12446        int retCode = mInstaller.clearUserData(pkg.volumeUuid, packageName, userId);
12447        if (retCode < 0) {
12448            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
12449            return false;
12450        }
12451
12452        if (pkg == null) {
12453            return false;
12454        }
12455
12456        if (pkg != null && pkg.applicationInfo != null) {
12457            final int appId = pkg.applicationInfo.uid;
12458            removeKeystoreDataIfNeeded(userId, appId);
12459        }
12460
12461        // Create a native library symlink only if we have native libraries
12462        // and if the native libraries are 32 bit libraries. We do not provide
12463        // this symlink for 64 bit libraries.
12464        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12465                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12466            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12467            if (mInstaller.linkNativeLibraryDirectory(pkg.volumeUuid, pkg.packageName,
12468                    nativeLibPath, userId) < 0) {
12469                Slog.w(TAG, "Failed linking native library dir");
12470                return false;
12471            }
12472        }
12473
12474        return true;
12475    }
12476
12477    /**
12478     * Remove entries from the keystore daemon. Will only remove it if the
12479     * {@code appId} is valid.
12480     */
12481    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12482        if (appId < 0) {
12483            return;
12484        }
12485
12486        final KeyStore keyStore = KeyStore.getInstance();
12487        if (keyStore != null) {
12488            if (userId == UserHandle.USER_ALL) {
12489                for (final int individual : sUserManager.getUserIds()) {
12490                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12491                }
12492            } else {
12493                keyStore.clearUid(UserHandle.getUid(userId, appId));
12494            }
12495        } else {
12496            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12497        }
12498    }
12499
12500    @Override
12501    public void deleteApplicationCacheFiles(final String packageName,
12502            final IPackageDataObserver observer) {
12503        mContext.enforceCallingOrSelfPermission(
12504                android.Manifest.permission.DELETE_CACHE_FILES, null);
12505        // Queue up an async operation since the package deletion may take a little while.
12506        final int userId = UserHandle.getCallingUserId();
12507        mHandler.post(new Runnable() {
12508            public void run() {
12509                mHandler.removeCallbacks(this);
12510                final boolean succeded;
12511                synchronized (mInstallLock) {
12512                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12513                }
12514                clearExternalStorageDataSync(packageName, userId, false);
12515                if (observer != null) {
12516                    try {
12517                        observer.onRemoveCompleted(packageName, succeded);
12518                    } catch (RemoteException e) {
12519                        Log.i(TAG, "Observer no longer exists.");
12520                    }
12521                } //end if observer
12522            } //end run
12523        });
12524    }
12525
12526    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12527        if (packageName == null) {
12528            Slog.w(TAG, "Attempt to delete null packageName.");
12529            return false;
12530        }
12531        PackageParser.Package p;
12532        synchronized (mPackages) {
12533            p = mPackages.get(packageName);
12534        }
12535        if (p == null) {
12536            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12537            return false;
12538        }
12539        final ApplicationInfo applicationInfo = p.applicationInfo;
12540        if (applicationInfo == null) {
12541            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12542            return false;
12543        }
12544        int retCode = mInstaller.deleteCacheFiles(p.volumeUuid, packageName, userId);
12545        if (retCode < 0) {
12546            Slog.w(TAG, "Couldn't remove cache files for package: "
12547                       + packageName + " u" + userId);
12548            return false;
12549        }
12550        return true;
12551    }
12552
12553    @Override
12554    public void getPackageSizeInfo(final String packageName, int userHandle,
12555            final IPackageStatsObserver observer) {
12556        mContext.enforceCallingOrSelfPermission(
12557                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12558        if (packageName == null) {
12559            throw new IllegalArgumentException("Attempt to get size of null packageName");
12560        }
12561
12562        PackageStats stats = new PackageStats(packageName, userHandle);
12563
12564        /*
12565         * Queue up an async operation since the package measurement may take a
12566         * little while.
12567         */
12568        Message msg = mHandler.obtainMessage(INIT_COPY);
12569        msg.obj = new MeasureParams(stats, observer);
12570        mHandler.sendMessage(msg);
12571    }
12572
12573    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12574            PackageStats pStats) {
12575        if (packageName == null) {
12576            Slog.w(TAG, "Attempt to get size of null packageName.");
12577            return false;
12578        }
12579        PackageParser.Package p;
12580        boolean dataOnly = false;
12581        String libDirRoot = null;
12582        String asecPath = null;
12583        PackageSetting ps = null;
12584        synchronized (mPackages) {
12585            p = mPackages.get(packageName);
12586            ps = mSettings.mPackages.get(packageName);
12587            if(p == null) {
12588                dataOnly = true;
12589                if((ps == null) || (ps.pkg == null)) {
12590                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12591                    return false;
12592                }
12593                p = ps.pkg;
12594            }
12595            if (ps != null) {
12596                libDirRoot = ps.legacyNativeLibraryPathString;
12597            }
12598            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12599                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12600                if (secureContainerId != null) {
12601                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12602                }
12603            }
12604        }
12605        String publicSrcDir = null;
12606        if(!dataOnly) {
12607            final ApplicationInfo applicationInfo = p.applicationInfo;
12608            if (applicationInfo == null) {
12609                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12610                return false;
12611            }
12612            if (p.isForwardLocked()) {
12613                publicSrcDir = applicationInfo.getBaseResourcePath();
12614            }
12615        }
12616        // TODO: extend to measure size of split APKs
12617        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12618        // not just the first level.
12619        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12620        // just the primary.
12621        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12622        int res = mInstaller.getSizeInfo(p.volumeUuid, packageName, userHandle, p.baseCodePath,
12623                libDirRoot, publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12624        if (res < 0) {
12625            return false;
12626        }
12627
12628        // Fix-up for forward-locked applications in ASEC containers.
12629        if (!isExternal(p)) {
12630            pStats.codeSize += pStats.externalCodeSize;
12631            pStats.externalCodeSize = 0L;
12632        }
12633
12634        return true;
12635    }
12636
12637
12638    @Override
12639    public void addPackageToPreferred(String packageName) {
12640        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12641    }
12642
12643    @Override
12644    public void removePackageFromPreferred(String packageName) {
12645        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12646    }
12647
12648    @Override
12649    public List<PackageInfo> getPreferredPackages(int flags) {
12650        return new ArrayList<PackageInfo>();
12651    }
12652
12653    private int getUidTargetSdkVersionLockedLPr(int uid) {
12654        Object obj = mSettings.getUserIdLPr(uid);
12655        if (obj instanceof SharedUserSetting) {
12656            final SharedUserSetting sus = (SharedUserSetting) obj;
12657            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12658            final Iterator<PackageSetting> it = sus.packages.iterator();
12659            while (it.hasNext()) {
12660                final PackageSetting ps = it.next();
12661                if (ps.pkg != null) {
12662                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12663                    if (v < vers) vers = v;
12664                }
12665            }
12666            return vers;
12667        } else if (obj instanceof PackageSetting) {
12668            final PackageSetting ps = (PackageSetting) obj;
12669            if (ps.pkg != null) {
12670                return ps.pkg.applicationInfo.targetSdkVersion;
12671            }
12672        }
12673        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12674    }
12675
12676    @Override
12677    public void addPreferredActivity(IntentFilter filter, int match,
12678            ComponentName[] set, ComponentName activity, int userId) {
12679        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12680                "Adding preferred");
12681    }
12682
12683    private void addPreferredActivityInternal(IntentFilter filter, int match,
12684            ComponentName[] set, ComponentName activity, boolean always, int userId,
12685            String opname) {
12686        // writer
12687        int callingUid = Binder.getCallingUid();
12688        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12689        if (filter.countActions() == 0) {
12690            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12691            return;
12692        }
12693        synchronized (mPackages) {
12694            if (mContext.checkCallingOrSelfPermission(
12695                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12696                    != PackageManager.PERMISSION_GRANTED) {
12697                if (getUidTargetSdkVersionLockedLPr(callingUid)
12698                        < Build.VERSION_CODES.FROYO) {
12699                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12700                            + callingUid);
12701                    return;
12702                }
12703                mContext.enforceCallingOrSelfPermission(
12704                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12705            }
12706
12707            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12708            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12709                    + userId + ":");
12710            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12711            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12712            scheduleWritePackageRestrictionsLocked(userId);
12713        }
12714    }
12715
12716    @Override
12717    public void replacePreferredActivity(IntentFilter filter, int match,
12718            ComponentName[] set, ComponentName activity, int userId) {
12719        if (filter.countActions() != 1) {
12720            throw new IllegalArgumentException(
12721                    "replacePreferredActivity expects filter to have only 1 action.");
12722        }
12723        if (filter.countDataAuthorities() != 0
12724                || filter.countDataPaths() != 0
12725                || filter.countDataSchemes() > 1
12726                || filter.countDataTypes() != 0) {
12727            throw new IllegalArgumentException(
12728                    "replacePreferredActivity expects filter to have no data authorities, " +
12729                    "paths, or types; and at most one scheme.");
12730        }
12731
12732        final int callingUid = Binder.getCallingUid();
12733        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12734        synchronized (mPackages) {
12735            if (mContext.checkCallingOrSelfPermission(
12736                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12737                    != PackageManager.PERMISSION_GRANTED) {
12738                if (getUidTargetSdkVersionLockedLPr(callingUid)
12739                        < Build.VERSION_CODES.FROYO) {
12740                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12741                            + Binder.getCallingUid());
12742                    return;
12743                }
12744                mContext.enforceCallingOrSelfPermission(
12745                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12746            }
12747
12748            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12749            if (pir != null) {
12750                // Get all of the existing entries that exactly match this filter.
12751                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12752                if (existing != null && existing.size() == 1) {
12753                    PreferredActivity cur = existing.get(0);
12754                    if (DEBUG_PREFERRED) {
12755                        Slog.i(TAG, "Checking replace of preferred:");
12756                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12757                        if (!cur.mPref.mAlways) {
12758                            Slog.i(TAG, "  -- CUR; not mAlways!");
12759                        } else {
12760                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12761                            Slog.i(TAG, "  -- CUR: mSet="
12762                                    + Arrays.toString(cur.mPref.mSetComponents));
12763                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12764                            Slog.i(TAG, "  -- NEW: mMatch="
12765                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12766                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12767                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12768                        }
12769                    }
12770                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12771                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12772                            && cur.mPref.sameSet(set)) {
12773                        // Setting the preferred activity to what it happens to be already
12774                        if (DEBUG_PREFERRED) {
12775                            Slog.i(TAG, "Replacing with same preferred activity "
12776                                    + cur.mPref.mShortComponent + " for user "
12777                                    + userId + ":");
12778                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12779                        }
12780                        return;
12781                    }
12782                }
12783
12784                if (existing != null) {
12785                    if (DEBUG_PREFERRED) {
12786                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12787                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12788                    }
12789                    for (int i = 0; i < existing.size(); i++) {
12790                        PreferredActivity pa = existing.get(i);
12791                        if (DEBUG_PREFERRED) {
12792                            Slog.i(TAG, "Removing existing preferred activity "
12793                                    + pa.mPref.mComponent + ":");
12794                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12795                        }
12796                        pir.removeFilter(pa);
12797                    }
12798                }
12799            }
12800            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12801                    "Replacing preferred");
12802        }
12803    }
12804
12805    @Override
12806    public void clearPackagePreferredActivities(String packageName) {
12807        final int uid = Binder.getCallingUid();
12808        // writer
12809        synchronized (mPackages) {
12810            PackageParser.Package pkg = mPackages.get(packageName);
12811            if (pkg == null || pkg.applicationInfo.uid != uid) {
12812                if (mContext.checkCallingOrSelfPermission(
12813                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12814                        != PackageManager.PERMISSION_GRANTED) {
12815                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12816                            < Build.VERSION_CODES.FROYO) {
12817                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12818                                + Binder.getCallingUid());
12819                        return;
12820                    }
12821                    mContext.enforceCallingOrSelfPermission(
12822                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12823                }
12824            }
12825
12826            int user = UserHandle.getCallingUserId();
12827            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12828                scheduleWritePackageRestrictionsLocked(user);
12829            }
12830        }
12831    }
12832
12833    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12834    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12835        ArrayList<PreferredActivity> removed = null;
12836        boolean changed = false;
12837        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12838            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12839            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12840            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12841                continue;
12842            }
12843            Iterator<PreferredActivity> it = pir.filterIterator();
12844            while (it.hasNext()) {
12845                PreferredActivity pa = it.next();
12846                // Mark entry for removal only if it matches the package name
12847                // and the entry is of type "always".
12848                if (packageName == null ||
12849                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12850                                && pa.mPref.mAlways)) {
12851                    if (removed == null) {
12852                        removed = new ArrayList<PreferredActivity>();
12853                    }
12854                    removed.add(pa);
12855                }
12856            }
12857            if (removed != null) {
12858                for (int j=0; j<removed.size(); j++) {
12859                    PreferredActivity pa = removed.get(j);
12860                    pir.removeFilter(pa);
12861                }
12862                changed = true;
12863            }
12864        }
12865        return changed;
12866    }
12867
12868    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12869    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12870        if (userId == UserHandle.USER_ALL) {
12871            if (mSettings.removeIntentFilterVerificationLPw(packageName,
12872                    sUserManager.getUserIds())) {
12873                for (int oneUserId : sUserManager.getUserIds()) {
12874                    scheduleWritePackageRestrictionsLocked(oneUserId);
12875                }
12876            }
12877        } else {
12878            if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) {
12879                scheduleWritePackageRestrictionsLocked(userId);
12880            }
12881        }
12882    }
12883
12884
12885    void clearDefaultBrowserIfNeeded(String packageName) {
12886        for (int oneUserId : sUserManager.getUserIds()) {
12887            String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId);
12888            if (TextUtils.isEmpty(defaultBrowserPackageName)) continue;
12889            if (packageName.equals(defaultBrowserPackageName)) {
12890                setDefaultBrowserPackageName(null, oneUserId);
12891            }
12892        }
12893    }
12894
12895    @Override
12896    public void resetPreferredActivities(int userId) {
12897        /* TODO: Actually use userId. Why is it being passed in? */
12898        mContext.enforceCallingOrSelfPermission(
12899                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12900        // writer
12901        synchronized (mPackages) {
12902            int user = UserHandle.getCallingUserId();
12903            clearPackagePreferredActivitiesLPw(null, user);
12904            mSettings.readDefaultPreferredAppsLPw(this, user);
12905            scheduleWritePackageRestrictionsLocked(user);
12906        }
12907    }
12908
12909    @Override
12910    public int getPreferredActivities(List<IntentFilter> outFilters,
12911            List<ComponentName> outActivities, String packageName) {
12912
12913        int num = 0;
12914        final int userId = UserHandle.getCallingUserId();
12915        // reader
12916        synchronized (mPackages) {
12917            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12918            if (pir != null) {
12919                final Iterator<PreferredActivity> it = pir.filterIterator();
12920                while (it.hasNext()) {
12921                    final PreferredActivity pa = it.next();
12922                    if (packageName == null
12923                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12924                                    && pa.mPref.mAlways)) {
12925                        if (outFilters != null) {
12926                            outFilters.add(new IntentFilter(pa));
12927                        }
12928                        if (outActivities != null) {
12929                            outActivities.add(pa.mPref.mComponent);
12930                        }
12931                    }
12932                }
12933            }
12934        }
12935
12936        return num;
12937    }
12938
12939    @Override
12940    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12941            int userId) {
12942        int callingUid = Binder.getCallingUid();
12943        if (callingUid != Process.SYSTEM_UID) {
12944            throw new SecurityException(
12945                    "addPersistentPreferredActivity can only be run by the system");
12946        }
12947        if (filter.countActions() == 0) {
12948            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12949            return;
12950        }
12951        synchronized (mPackages) {
12952            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12953                    " :");
12954            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12955            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12956                    new PersistentPreferredActivity(filter, activity));
12957            scheduleWritePackageRestrictionsLocked(userId);
12958        }
12959    }
12960
12961    @Override
12962    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12963        int callingUid = Binder.getCallingUid();
12964        if (callingUid != Process.SYSTEM_UID) {
12965            throw new SecurityException(
12966                    "clearPackagePersistentPreferredActivities can only be run by the system");
12967        }
12968        ArrayList<PersistentPreferredActivity> removed = null;
12969        boolean changed = false;
12970        synchronized (mPackages) {
12971            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12972                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12973                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12974                        .valueAt(i);
12975                if (userId != thisUserId) {
12976                    continue;
12977                }
12978                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12979                while (it.hasNext()) {
12980                    PersistentPreferredActivity ppa = it.next();
12981                    // Mark entry for removal only if it matches the package name.
12982                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12983                        if (removed == null) {
12984                            removed = new ArrayList<PersistentPreferredActivity>();
12985                        }
12986                        removed.add(ppa);
12987                    }
12988                }
12989                if (removed != null) {
12990                    for (int j=0; j<removed.size(); j++) {
12991                        PersistentPreferredActivity ppa = removed.get(j);
12992                        ppir.removeFilter(ppa);
12993                    }
12994                    changed = true;
12995                }
12996            }
12997
12998            if (changed) {
12999                scheduleWritePackageRestrictionsLocked(userId);
13000            }
13001        }
13002    }
13003
13004    /**
13005     * Non-Binder method, support for the backup/restore mechanism: write the
13006     * full set of preferred activities in its canonical XML format.  Returns true
13007     * on success; false otherwise.
13008     */
13009    @Override
13010    public byte[] getPreferredActivityBackup(int userId) {
13011        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13012            throw new SecurityException("Only the system may call getPreferredActivityBackup()");
13013        }
13014
13015        ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
13016        try {
13017            final XmlSerializer serializer = new FastXmlSerializer();
13018            serializer.setOutput(dataStream, "utf-8");
13019            serializer.startDocument(null, true);
13020            serializer.startTag(null, TAG_PREFERRED_BACKUP);
13021
13022            synchronized (mPackages) {
13023                mSettings.writePreferredActivitiesLPr(serializer, userId, true);
13024            }
13025
13026            serializer.endTag(null, TAG_PREFERRED_BACKUP);
13027            serializer.endDocument();
13028            serializer.flush();
13029        } catch (Exception e) {
13030            if (DEBUG_BACKUP) {
13031                Slog.e(TAG, "Unable to write preferred activities for backup", e);
13032            }
13033            return null;
13034        }
13035
13036        return dataStream.toByteArray();
13037    }
13038
13039    @Override
13040    public void restorePreferredActivities(byte[] backup, int userId) {
13041        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
13042            throw new SecurityException("Only the system may call restorePreferredActivities()");
13043        }
13044
13045        try {
13046            final XmlPullParser parser = Xml.newPullParser();
13047            parser.setInput(new ByteArrayInputStream(backup), null);
13048
13049            int type;
13050            while ((type = parser.next()) != XmlPullParser.START_TAG
13051                    && type != XmlPullParser.END_DOCUMENT) {
13052            }
13053            if (type != XmlPullParser.START_TAG) {
13054                // oops didn't find a start tag?!
13055                if (DEBUG_BACKUP) {
13056                    Slog.e(TAG, "Didn't find start tag during restore");
13057                }
13058                return;
13059            }
13060
13061            // this is supposed to be TAG_PREFERRED_BACKUP
13062            if (!TAG_PREFERRED_BACKUP.equals(parser.getName())) {
13063                if (DEBUG_BACKUP) {
13064                    Slog.e(TAG, "Found unexpected tag " + parser.getName());
13065                }
13066                return;
13067            }
13068
13069            // skip interfering stuff, then we're aligned with the backing implementation
13070            while ((type = parser.next()) == XmlPullParser.TEXT) { }
13071            synchronized (mPackages) {
13072                mSettings.readPreferredActivitiesLPw(parser, userId);
13073            }
13074        } catch (Exception e) {
13075            if (DEBUG_BACKUP) {
13076                Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage());
13077            }
13078        }
13079    }
13080
13081    @Override
13082    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
13083            int sourceUserId, int targetUserId, int flags) {
13084        mContext.enforceCallingOrSelfPermission(
13085                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13086        int callingUid = Binder.getCallingUid();
13087        enforceOwnerRights(ownerPackage, callingUid);
13088        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13089        if (intentFilter.countActions() == 0) {
13090            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
13091            return;
13092        }
13093        synchronized (mPackages) {
13094            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
13095                    ownerPackage, targetUserId, flags);
13096            CrossProfileIntentResolver resolver =
13097                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13098            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
13099            // We have all those whose filter is equal. Now checking if the rest is equal as well.
13100            if (existing != null) {
13101                int size = existing.size();
13102                for (int i = 0; i < size; i++) {
13103                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
13104                        return;
13105                    }
13106                }
13107            }
13108            resolver.addFilter(newFilter);
13109            scheduleWritePackageRestrictionsLocked(sourceUserId);
13110        }
13111    }
13112
13113    @Override
13114    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
13115        mContext.enforceCallingOrSelfPermission(
13116                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
13117        int callingUid = Binder.getCallingUid();
13118        enforceOwnerRights(ownerPackage, callingUid);
13119        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
13120        synchronized (mPackages) {
13121            CrossProfileIntentResolver resolver =
13122                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
13123            ArraySet<CrossProfileIntentFilter> set =
13124                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
13125            for (CrossProfileIntentFilter filter : set) {
13126                if (filter.getOwnerPackage().equals(ownerPackage)) {
13127                    resolver.removeFilter(filter);
13128                }
13129            }
13130            scheduleWritePackageRestrictionsLocked(sourceUserId);
13131        }
13132    }
13133
13134    // Enforcing that callingUid is owning pkg on userId
13135    private void enforceOwnerRights(String pkg, int callingUid) {
13136        // The system owns everything.
13137        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
13138            return;
13139        }
13140        int callingUserId = UserHandle.getUserId(callingUid);
13141        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
13142        if (pi == null) {
13143            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
13144                    + callingUserId);
13145        }
13146        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
13147            throw new SecurityException("Calling uid " + callingUid
13148                    + " does not own package " + pkg);
13149        }
13150    }
13151
13152    @Override
13153    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
13154        Intent intent = new Intent(Intent.ACTION_MAIN);
13155        intent.addCategory(Intent.CATEGORY_HOME);
13156
13157        final int callingUserId = UserHandle.getCallingUserId();
13158        List<ResolveInfo> list = queryIntentActivities(intent, null,
13159                PackageManager.GET_META_DATA, callingUserId);
13160        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
13161                true, false, false, callingUserId);
13162
13163        allHomeCandidates.clear();
13164        if (list != null) {
13165            for (ResolveInfo ri : list) {
13166                allHomeCandidates.add(ri);
13167            }
13168        }
13169        return (preferred == null || preferred.activityInfo == null)
13170                ? null
13171                : new ComponentName(preferred.activityInfo.packageName,
13172                        preferred.activityInfo.name);
13173    }
13174
13175    @Override
13176    public void setApplicationEnabledSetting(String appPackageName,
13177            int newState, int flags, int userId, String callingPackage) {
13178        if (!sUserManager.exists(userId)) return;
13179        if (callingPackage == null) {
13180            callingPackage = Integer.toString(Binder.getCallingUid());
13181        }
13182        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
13183    }
13184
13185    @Override
13186    public void setComponentEnabledSetting(ComponentName componentName,
13187            int newState, int flags, int userId) {
13188        if (!sUserManager.exists(userId)) return;
13189        setEnabledSetting(componentName.getPackageName(),
13190                componentName.getClassName(), newState, flags, userId, null);
13191    }
13192
13193    private void setEnabledSetting(final String packageName, String className, int newState,
13194            final int flags, int userId, String callingPackage) {
13195        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
13196              || newState == COMPONENT_ENABLED_STATE_ENABLED
13197              || newState == COMPONENT_ENABLED_STATE_DISABLED
13198              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
13199              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
13200            throw new IllegalArgumentException("Invalid new component state: "
13201                    + newState);
13202        }
13203        PackageSetting pkgSetting;
13204        final int uid = Binder.getCallingUid();
13205        final int permission = mContext.checkCallingOrSelfPermission(
13206                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13207        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
13208        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13209        boolean sendNow = false;
13210        boolean isApp = (className == null);
13211        String componentName = isApp ? packageName : className;
13212        int packageUid = -1;
13213        ArrayList<String> components;
13214
13215        // writer
13216        synchronized (mPackages) {
13217            pkgSetting = mSettings.mPackages.get(packageName);
13218            if (pkgSetting == null) {
13219                if (className == null) {
13220                    throw new IllegalArgumentException(
13221                            "Unknown package: " + packageName);
13222                }
13223                throw new IllegalArgumentException(
13224                        "Unknown component: " + packageName
13225                        + "/" + className);
13226            }
13227            // Allow root and verify that userId is not being specified by a different user
13228            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
13229                throw new SecurityException(
13230                        "Permission Denial: attempt to change component state from pid="
13231                        + Binder.getCallingPid()
13232                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
13233            }
13234            if (className == null) {
13235                // We're dealing with an application/package level state change
13236                if (pkgSetting.getEnabled(userId) == newState) {
13237                    // Nothing to do
13238                    return;
13239                }
13240                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
13241                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
13242                    // Don't care about who enables an app.
13243                    callingPackage = null;
13244                }
13245                pkgSetting.setEnabled(newState, userId, callingPackage);
13246                // pkgSetting.pkg.mSetEnabled = newState;
13247            } else {
13248                // We're dealing with a component level state change
13249                // First, verify that this is a valid class name.
13250                PackageParser.Package pkg = pkgSetting.pkg;
13251                if (pkg == null || !pkg.hasComponentClassName(className)) {
13252                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
13253                        throw new IllegalArgumentException("Component class " + className
13254                                + " does not exist in " + packageName);
13255                    } else {
13256                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
13257                                + className + " does not exist in " + packageName);
13258                    }
13259                }
13260                switch (newState) {
13261                case COMPONENT_ENABLED_STATE_ENABLED:
13262                    if (!pkgSetting.enableComponentLPw(className, userId)) {
13263                        return;
13264                    }
13265                    break;
13266                case COMPONENT_ENABLED_STATE_DISABLED:
13267                    if (!pkgSetting.disableComponentLPw(className, userId)) {
13268                        return;
13269                    }
13270                    break;
13271                case COMPONENT_ENABLED_STATE_DEFAULT:
13272                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
13273                        return;
13274                    }
13275                    break;
13276                default:
13277                    Slog.e(TAG, "Invalid new component state: " + newState);
13278                    return;
13279                }
13280            }
13281            scheduleWritePackageRestrictionsLocked(userId);
13282            components = mPendingBroadcasts.get(userId, packageName);
13283            final boolean newPackage = components == null;
13284            if (newPackage) {
13285                components = new ArrayList<String>();
13286            }
13287            if (!components.contains(componentName)) {
13288                components.add(componentName);
13289            }
13290            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
13291                sendNow = true;
13292                // Purge entry from pending broadcast list if another one exists already
13293                // since we are sending one right away.
13294                mPendingBroadcasts.remove(userId, packageName);
13295            } else {
13296                if (newPackage) {
13297                    mPendingBroadcasts.put(userId, packageName, components);
13298                }
13299                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
13300                    // Schedule a message
13301                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
13302                }
13303            }
13304        }
13305
13306        long callingId = Binder.clearCallingIdentity();
13307        try {
13308            if (sendNow) {
13309                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
13310                sendPackageChangedBroadcast(packageName,
13311                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
13312            }
13313        } finally {
13314            Binder.restoreCallingIdentity(callingId);
13315        }
13316    }
13317
13318    private void sendPackageChangedBroadcast(String packageName,
13319            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
13320        if (DEBUG_INSTALL)
13321            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
13322                    + componentNames);
13323        Bundle extras = new Bundle(4);
13324        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
13325        String nameList[] = new String[componentNames.size()];
13326        componentNames.toArray(nameList);
13327        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
13328        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
13329        extras.putInt(Intent.EXTRA_UID, packageUid);
13330        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
13331                new int[] {UserHandle.getUserId(packageUid)});
13332    }
13333
13334    @Override
13335    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
13336        if (!sUserManager.exists(userId)) return;
13337        final int uid = Binder.getCallingUid();
13338        final int permission = mContext.checkCallingOrSelfPermission(
13339                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
13340        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
13341        enforceCrossUserPermission(uid, userId, true, true, "stop package");
13342        // writer
13343        synchronized (mPackages) {
13344            if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped,
13345                    allowedByPermission, uid, userId)) {
13346                scheduleWritePackageRestrictionsLocked(userId);
13347            }
13348        }
13349    }
13350
13351    @Override
13352    public String getInstallerPackageName(String packageName) {
13353        // reader
13354        synchronized (mPackages) {
13355            return mSettings.getInstallerPackageNameLPr(packageName);
13356        }
13357    }
13358
13359    @Override
13360    public int getApplicationEnabledSetting(String packageName, int userId) {
13361        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13362        int uid = Binder.getCallingUid();
13363        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
13364        // reader
13365        synchronized (mPackages) {
13366            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
13367        }
13368    }
13369
13370    @Override
13371    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
13372        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
13373        int uid = Binder.getCallingUid();
13374        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
13375        // reader
13376        synchronized (mPackages) {
13377            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
13378        }
13379    }
13380
13381    @Override
13382    public void enterSafeMode() {
13383        enforceSystemOrRoot("Only the system can request entering safe mode");
13384
13385        if (!mSystemReady) {
13386            mSafeMode = true;
13387        }
13388    }
13389
13390    @Override
13391    public void systemReady() {
13392        mSystemReady = true;
13393
13394        // Read the compatibilty setting when the system is ready.
13395        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
13396                mContext.getContentResolver(),
13397                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
13398        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
13399        if (DEBUG_SETTINGS) {
13400            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
13401        }
13402
13403        synchronized (mPackages) {
13404            // Verify that all of the preferred activity components actually
13405            // exist.  It is possible for applications to be updated and at
13406            // that point remove a previously declared activity component that
13407            // had been set as a preferred activity.  We try to clean this up
13408            // the next time we encounter that preferred activity, but it is
13409            // possible for the user flow to never be able to return to that
13410            // situation so here we do a sanity check to make sure we haven't
13411            // left any junk around.
13412            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
13413            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13414                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13415                removed.clear();
13416                for (PreferredActivity pa : pir.filterSet()) {
13417                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
13418                        removed.add(pa);
13419                    }
13420                }
13421                if (removed.size() > 0) {
13422                    for (int r=0; r<removed.size(); r++) {
13423                        PreferredActivity pa = removed.get(r);
13424                        Slog.w(TAG, "Removing dangling preferred activity: "
13425                                + pa.mPref.mComponent);
13426                        pir.removeFilter(pa);
13427                    }
13428                    mSettings.writePackageRestrictionsLPr(
13429                            mSettings.mPreferredActivities.keyAt(i));
13430                }
13431            }
13432        }
13433        sUserManager.systemReady();
13434
13435        // Kick off any messages waiting for system ready
13436        if (mPostSystemReadyMessages != null) {
13437            for (Message msg : mPostSystemReadyMessages) {
13438                msg.sendToTarget();
13439            }
13440            mPostSystemReadyMessages = null;
13441        }
13442
13443        // Watch for external volumes that come and go over time
13444        final StorageManager storage = mContext.getSystemService(StorageManager.class);
13445        storage.registerListener(mStorageListener);
13446
13447        mInstallerService.systemReady();
13448    }
13449
13450    @Override
13451    public boolean isSafeMode() {
13452        return mSafeMode;
13453    }
13454
13455    @Override
13456    public boolean hasSystemUidErrors() {
13457        return mHasSystemUidErrors;
13458    }
13459
13460    static String arrayToString(int[] array) {
13461        StringBuffer buf = new StringBuffer(128);
13462        buf.append('[');
13463        if (array != null) {
13464            for (int i=0; i<array.length; i++) {
13465                if (i > 0) buf.append(", ");
13466                buf.append(array[i]);
13467            }
13468        }
13469        buf.append(']');
13470        return buf.toString();
13471    }
13472
13473    static class DumpState {
13474        public static final int DUMP_LIBS = 1 << 0;
13475        public static final int DUMP_FEATURES = 1 << 1;
13476        public static final int DUMP_RESOLVERS = 1 << 2;
13477        public static final int DUMP_PERMISSIONS = 1 << 3;
13478        public static final int DUMP_PACKAGES = 1 << 4;
13479        public static final int DUMP_SHARED_USERS = 1 << 5;
13480        public static final int DUMP_MESSAGES = 1 << 6;
13481        public static final int DUMP_PROVIDERS = 1 << 7;
13482        public static final int DUMP_VERIFIERS = 1 << 8;
13483        public static final int DUMP_PREFERRED = 1 << 9;
13484        public static final int DUMP_PREFERRED_XML = 1 << 10;
13485        public static final int DUMP_KEYSETS = 1 << 11;
13486        public static final int DUMP_VERSION = 1 << 12;
13487        public static final int DUMP_INSTALLS = 1 << 13;
13488        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
13489        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
13490
13491        public static final int OPTION_SHOW_FILTERS = 1 << 0;
13492
13493        private int mTypes;
13494
13495        private int mOptions;
13496
13497        private boolean mTitlePrinted;
13498
13499        private SharedUserSetting mSharedUser;
13500
13501        public boolean isDumping(int type) {
13502            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
13503                return true;
13504            }
13505
13506            return (mTypes & type) != 0;
13507        }
13508
13509        public void setDump(int type) {
13510            mTypes |= type;
13511        }
13512
13513        public boolean isOptionEnabled(int option) {
13514            return (mOptions & option) != 0;
13515        }
13516
13517        public void setOptionEnabled(int option) {
13518            mOptions |= option;
13519        }
13520
13521        public boolean onTitlePrinted() {
13522            final boolean printed = mTitlePrinted;
13523            mTitlePrinted = true;
13524            return printed;
13525        }
13526
13527        public boolean getTitlePrinted() {
13528            return mTitlePrinted;
13529        }
13530
13531        public void setTitlePrinted(boolean enabled) {
13532            mTitlePrinted = enabled;
13533        }
13534
13535        public SharedUserSetting getSharedUser() {
13536            return mSharedUser;
13537        }
13538
13539        public void setSharedUser(SharedUserSetting user) {
13540            mSharedUser = user;
13541        }
13542    }
13543
13544    @Override
13545    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
13546        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
13547                != PackageManager.PERMISSION_GRANTED) {
13548            pw.println("Permission Denial: can't dump ActivityManager from from pid="
13549                    + Binder.getCallingPid()
13550                    + ", uid=" + Binder.getCallingUid()
13551                    + " without permission "
13552                    + android.Manifest.permission.DUMP);
13553            return;
13554        }
13555
13556        DumpState dumpState = new DumpState();
13557        boolean fullPreferred = false;
13558        boolean checkin = false;
13559
13560        String packageName = null;
13561
13562        int opti = 0;
13563        while (opti < args.length) {
13564            String opt = args[opti];
13565            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13566                break;
13567            }
13568            opti++;
13569
13570            if ("-a".equals(opt)) {
13571                // Right now we only know how to print all.
13572            } else if ("-h".equals(opt)) {
13573                pw.println("Package manager dump options:");
13574                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13575                pw.println("    --checkin: dump for a checkin");
13576                pw.println("    -f: print details of intent filters");
13577                pw.println("    -h: print this help");
13578                pw.println("  cmd may be one of:");
13579                pw.println("    l[ibraries]: list known shared libraries");
13580                pw.println("    f[ibraries]: list device features");
13581                pw.println("    k[eysets]: print known keysets");
13582                pw.println("    r[esolvers]: dump intent resolvers");
13583                pw.println("    perm[issions]: dump permissions");
13584                pw.println("    pref[erred]: print preferred package settings");
13585                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13586                pw.println("    prov[iders]: dump content providers");
13587                pw.println("    p[ackages]: dump installed packages");
13588                pw.println("    s[hared-users]: dump shared user IDs");
13589                pw.println("    m[essages]: print collected runtime messages");
13590                pw.println("    v[erifiers]: print package verifier info");
13591                pw.println("    version: print database version info");
13592                pw.println("    write: write current settings now");
13593                pw.println("    <package.name>: info about given package");
13594                pw.println("    installs: details about install sessions");
13595                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13596                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13597                return;
13598            } else if ("--checkin".equals(opt)) {
13599                checkin = true;
13600            } else if ("-f".equals(opt)) {
13601                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13602            } else {
13603                pw.println("Unknown argument: " + opt + "; use -h for help");
13604            }
13605        }
13606
13607        // Is the caller requesting to dump a particular piece of data?
13608        if (opti < args.length) {
13609            String cmd = args[opti];
13610            opti++;
13611            // Is this a package name?
13612            if ("android".equals(cmd) || cmd.contains(".")) {
13613                packageName = cmd;
13614                // When dumping a single package, we always dump all of its
13615                // filter information since the amount of data will be reasonable.
13616                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13617            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13618                dumpState.setDump(DumpState.DUMP_LIBS);
13619            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13620                dumpState.setDump(DumpState.DUMP_FEATURES);
13621            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13622                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13623            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13624                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13625            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13626                dumpState.setDump(DumpState.DUMP_PREFERRED);
13627            } else if ("preferred-xml".equals(cmd)) {
13628                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13629                if (opti < args.length && "--full".equals(args[opti])) {
13630                    fullPreferred = true;
13631                    opti++;
13632                }
13633            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13634                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13635            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13636                dumpState.setDump(DumpState.DUMP_PACKAGES);
13637            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13638                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13639            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13640                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13641            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13642                dumpState.setDump(DumpState.DUMP_MESSAGES);
13643            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13644                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13645            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13646                    || "intent-filter-verifiers".equals(cmd)) {
13647                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13648            } else if ("version".equals(cmd)) {
13649                dumpState.setDump(DumpState.DUMP_VERSION);
13650            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13651                dumpState.setDump(DumpState.DUMP_KEYSETS);
13652            } else if ("installs".equals(cmd)) {
13653                dumpState.setDump(DumpState.DUMP_INSTALLS);
13654            } else if ("write".equals(cmd)) {
13655                synchronized (mPackages) {
13656                    mSettings.writeLPr();
13657                    pw.println("Settings written.");
13658                    return;
13659                }
13660            }
13661        }
13662
13663        if (checkin) {
13664            pw.println("vers,1");
13665        }
13666
13667        // reader
13668        synchronized (mPackages) {
13669            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13670                if (!checkin) {
13671                    if (dumpState.onTitlePrinted())
13672                        pw.println();
13673                    pw.println("Database versions:");
13674                    pw.print("  SDK Version:");
13675                    pw.print(" internal=");
13676                    pw.print(mSettings.mInternalSdkPlatform);
13677                    pw.print(" external=");
13678                    pw.println(mSettings.mExternalSdkPlatform);
13679                    pw.print("  DB Version:");
13680                    pw.print(" internal=");
13681                    pw.print(mSettings.mInternalDatabaseVersion);
13682                    pw.print(" external=");
13683                    pw.println(mSettings.mExternalDatabaseVersion);
13684                }
13685            }
13686
13687            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13688                if (!checkin) {
13689                    if (dumpState.onTitlePrinted())
13690                        pw.println();
13691                    pw.println("Verifiers:");
13692                    pw.print("  Required: ");
13693                    pw.print(mRequiredVerifierPackage);
13694                    pw.print(" (uid=");
13695                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13696                    pw.println(")");
13697                } else if (mRequiredVerifierPackage != null) {
13698                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13699                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13700                }
13701            }
13702
13703            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13704                    packageName == null) {
13705                if (mIntentFilterVerifierComponent != null) {
13706                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13707                    if (!checkin) {
13708                        if (dumpState.onTitlePrinted())
13709                            pw.println();
13710                        pw.println("Intent Filter Verifier:");
13711                        pw.print("  Using: ");
13712                        pw.print(verifierPackageName);
13713                        pw.print(" (uid=");
13714                        pw.print(getPackageUid(verifierPackageName, 0));
13715                        pw.println(")");
13716                    } else if (verifierPackageName != null) {
13717                        pw.print("ifv,"); pw.print(verifierPackageName);
13718                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13719                    }
13720                } else {
13721                    pw.println();
13722                    pw.println("No Intent Filter Verifier available!");
13723                }
13724            }
13725
13726            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13727                boolean printedHeader = false;
13728                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13729                while (it.hasNext()) {
13730                    String name = it.next();
13731                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13732                    if (!checkin) {
13733                        if (!printedHeader) {
13734                            if (dumpState.onTitlePrinted())
13735                                pw.println();
13736                            pw.println("Libraries:");
13737                            printedHeader = true;
13738                        }
13739                        pw.print("  ");
13740                    } else {
13741                        pw.print("lib,");
13742                    }
13743                    pw.print(name);
13744                    if (!checkin) {
13745                        pw.print(" -> ");
13746                    }
13747                    if (ent.path != null) {
13748                        if (!checkin) {
13749                            pw.print("(jar) ");
13750                            pw.print(ent.path);
13751                        } else {
13752                            pw.print(",jar,");
13753                            pw.print(ent.path);
13754                        }
13755                    } else {
13756                        if (!checkin) {
13757                            pw.print("(apk) ");
13758                            pw.print(ent.apk);
13759                        } else {
13760                            pw.print(",apk,");
13761                            pw.print(ent.apk);
13762                        }
13763                    }
13764                    pw.println();
13765                }
13766            }
13767
13768            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13769                if (dumpState.onTitlePrinted())
13770                    pw.println();
13771                if (!checkin) {
13772                    pw.println("Features:");
13773                }
13774                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13775                while (it.hasNext()) {
13776                    String name = it.next();
13777                    if (!checkin) {
13778                        pw.print("  ");
13779                    } else {
13780                        pw.print("feat,");
13781                    }
13782                    pw.println(name);
13783                }
13784            }
13785
13786            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13787                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13788                        : "Activity Resolver Table:", "  ", packageName,
13789                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13790                    dumpState.setTitlePrinted(true);
13791                }
13792                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13793                        : "Receiver Resolver Table:", "  ", packageName,
13794                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13795                    dumpState.setTitlePrinted(true);
13796                }
13797                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13798                        : "Service Resolver Table:", "  ", packageName,
13799                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13800                    dumpState.setTitlePrinted(true);
13801                }
13802                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13803                        : "Provider Resolver Table:", "  ", packageName,
13804                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13805                    dumpState.setTitlePrinted(true);
13806                }
13807            }
13808
13809            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13810                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13811                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13812                    int user = mSettings.mPreferredActivities.keyAt(i);
13813                    if (pir.dump(pw,
13814                            dumpState.getTitlePrinted()
13815                                ? "\nPreferred Activities User " + user + ":"
13816                                : "Preferred Activities User " + user + ":", "  ",
13817                            packageName, true, false)) {
13818                        dumpState.setTitlePrinted(true);
13819                    }
13820                }
13821            }
13822
13823            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13824                pw.flush();
13825                FileOutputStream fout = new FileOutputStream(fd);
13826                BufferedOutputStream str = new BufferedOutputStream(fout);
13827                XmlSerializer serializer = new FastXmlSerializer();
13828                try {
13829                    serializer.setOutput(str, "utf-8");
13830                    serializer.startDocument(null, true);
13831                    serializer.setFeature(
13832                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13833                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13834                    serializer.endDocument();
13835                    serializer.flush();
13836                } catch (IllegalArgumentException e) {
13837                    pw.println("Failed writing: " + e);
13838                } catch (IllegalStateException e) {
13839                    pw.println("Failed writing: " + e);
13840                } catch (IOException e) {
13841                    pw.println("Failed writing: " + e);
13842                }
13843            }
13844
13845            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13846                pw.println();
13847                int count = mSettings.mPackages.size();
13848                if (count == 0) {
13849                    pw.println("No domain preferred apps!");
13850                    pw.println();
13851                } else {
13852                    final String prefix = "  ";
13853                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13854                    if (allPackageSettings.size() == 0) {
13855                        pw.println("No domain preferred apps!");
13856                        pw.println();
13857                    } else {
13858                        pw.println("Domain preferred apps status:");
13859                        pw.println();
13860                        count = 0;
13861                        for (PackageSetting ps : allPackageSettings) {
13862                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13863                            if (ivi == null || ivi.getPackageName() == null) continue;
13864                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13865                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13866                            pw.println(prefix + "Status: " + ivi.getStatusString());
13867                            pw.println();
13868                            count++;
13869                        }
13870                        if (count == 0) {
13871                            pw.println(prefix + "No domain preferred app status!");
13872                            pw.println();
13873                        }
13874                        for (int userId : sUserManager.getUserIds()) {
13875                            pw.println("Domain preferred apps for User " + userId + ":");
13876                            pw.println();
13877                            count = 0;
13878                            for (PackageSetting ps : allPackageSettings) {
13879                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13880                                if (ivi == null || ivi.getPackageName() == null) {
13881                                    continue;
13882                                }
13883                                final int status = ps.getDomainVerificationStatusForUser(userId);
13884                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13885                                    continue;
13886                                }
13887                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13888                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13889                                String statusStr = IntentFilterVerificationInfo.
13890                                        getStatusStringFromValue(status);
13891                                pw.println(prefix + "Status: " + statusStr);
13892                                pw.println();
13893                                count++;
13894                            }
13895                            if (count == 0) {
13896                                pw.println(prefix + "No domain preferred apps!");
13897                                pw.println();
13898                            }
13899                        }
13900                    }
13901                }
13902            }
13903
13904            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13905                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13906                if (packageName == null) {
13907                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13908                        if (iperm == 0) {
13909                            if (dumpState.onTitlePrinted())
13910                                pw.println();
13911                            pw.println("AppOp Permissions:");
13912                        }
13913                        pw.print("  AppOp Permission ");
13914                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13915                        pw.println(":");
13916                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13917                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13918                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13919                        }
13920                    }
13921                }
13922            }
13923
13924            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13925                boolean printedSomething = false;
13926                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13927                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13928                        continue;
13929                    }
13930                    if (!printedSomething) {
13931                        if (dumpState.onTitlePrinted())
13932                            pw.println();
13933                        pw.println("Registered ContentProviders:");
13934                        printedSomething = true;
13935                    }
13936                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13937                    pw.print("    "); pw.println(p.toString());
13938                }
13939                printedSomething = false;
13940                for (Map.Entry<String, PackageParser.Provider> entry :
13941                        mProvidersByAuthority.entrySet()) {
13942                    PackageParser.Provider p = entry.getValue();
13943                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13944                        continue;
13945                    }
13946                    if (!printedSomething) {
13947                        if (dumpState.onTitlePrinted())
13948                            pw.println();
13949                        pw.println("ContentProvider Authorities:");
13950                        printedSomething = true;
13951                    }
13952                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13953                    pw.print("    "); pw.println(p.toString());
13954                    if (p.info != null && p.info.applicationInfo != null) {
13955                        final String appInfo = p.info.applicationInfo.toString();
13956                        pw.print("      applicationInfo="); pw.println(appInfo);
13957                    }
13958                }
13959            }
13960
13961            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13962                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13963            }
13964
13965            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13966                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13967            }
13968
13969            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13970                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13971            }
13972
13973            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13974                // XXX should handle packageName != null by dumping only install data that
13975                // the given package is involved with.
13976                if (dumpState.onTitlePrinted()) pw.println();
13977                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13978            }
13979
13980            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13981                if (dumpState.onTitlePrinted()) pw.println();
13982                mSettings.dumpReadMessagesLPr(pw, dumpState);
13983
13984                pw.println();
13985                pw.println("Package warning messages:");
13986                BufferedReader in = null;
13987                String line = null;
13988                try {
13989                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13990                    while ((line = in.readLine()) != null) {
13991                        if (line.contains("ignored: updated version")) continue;
13992                        pw.println(line);
13993                    }
13994                } catch (IOException ignored) {
13995                } finally {
13996                    IoUtils.closeQuietly(in);
13997                }
13998            }
13999
14000            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
14001                BufferedReader in = null;
14002                String line = null;
14003                try {
14004                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
14005                    while ((line = in.readLine()) != null) {
14006                        if (line.contains("ignored: updated version")) continue;
14007                        pw.print("msg,");
14008                        pw.println(line);
14009                    }
14010                } catch (IOException ignored) {
14011                } finally {
14012                    IoUtils.closeQuietly(in);
14013                }
14014            }
14015        }
14016    }
14017
14018    // ------- apps on sdcard specific code -------
14019    static final boolean DEBUG_SD_INSTALL = false;
14020
14021    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
14022
14023    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
14024
14025    private boolean mMediaMounted = false;
14026
14027    static String getEncryptKey() {
14028        try {
14029            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
14030                    SD_ENCRYPTION_KEYSTORE_NAME);
14031            if (sdEncKey == null) {
14032                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
14033                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
14034                if (sdEncKey == null) {
14035                    Slog.e(TAG, "Failed to create encryption keys");
14036                    return null;
14037                }
14038            }
14039            return sdEncKey;
14040        } catch (NoSuchAlgorithmException nsae) {
14041            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
14042            return null;
14043        } catch (IOException ioe) {
14044            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
14045            return null;
14046        }
14047    }
14048
14049    /*
14050     * Update media status on PackageManager.
14051     */
14052    @Override
14053    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
14054        int callingUid = Binder.getCallingUid();
14055        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
14056            throw new SecurityException("Media status can only be updated by the system");
14057        }
14058        // reader; this apparently protects mMediaMounted, but should probably
14059        // be a different lock in that case.
14060        synchronized (mPackages) {
14061            Log.i(TAG, "Updating external media status from "
14062                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
14063                    + (mediaStatus ? "mounted" : "unmounted"));
14064            if (DEBUG_SD_INSTALL)
14065                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
14066                        + ", mMediaMounted=" + mMediaMounted);
14067            if (mediaStatus == mMediaMounted) {
14068                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
14069                        : 0, -1);
14070                mHandler.sendMessage(msg);
14071                return;
14072            }
14073            mMediaMounted = mediaStatus;
14074        }
14075        // Queue up an async operation since the package installation may take a
14076        // little while.
14077        mHandler.post(new Runnable() {
14078            public void run() {
14079                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
14080            }
14081        });
14082    }
14083
14084    /**
14085     * Called by MountService when the initial ASECs to scan are available.
14086     * Should block until all the ASEC containers are finished being scanned.
14087     */
14088    public void scanAvailableAsecs() {
14089        updateExternalMediaStatusInner(true, false, false);
14090        if (mShouldRestoreconData) {
14091            SELinuxMMAC.setRestoreconDone();
14092            mShouldRestoreconData = false;
14093        }
14094    }
14095
14096    /*
14097     * Collect information of applications on external media, map them against
14098     * existing containers and update information based on current mount status.
14099     * Please note that we always have to report status if reportStatus has been
14100     * set to true especially when unloading packages.
14101     */
14102    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
14103            boolean externalStorage) {
14104        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
14105        int[] uidArr = EmptyArray.INT;
14106
14107        final String[] list = PackageHelper.getSecureContainerList();
14108        if (ArrayUtils.isEmpty(list)) {
14109            Log.i(TAG, "No secure containers found");
14110        } else {
14111            // Process list of secure containers and categorize them
14112            // as active or stale based on their package internal state.
14113
14114            // reader
14115            synchronized (mPackages) {
14116                for (String cid : list) {
14117                    // Leave stages untouched for now; installer service owns them
14118                    if (PackageInstallerService.isStageName(cid)) continue;
14119
14120                    if (DEBUG_SD_INSTALL)
14121                        Log.i(TAG, "Processing container " + cid);
14122                    String pkgName = getAsecPackageName(cid);
14123                    if (pkgName == null) {
14124                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
14125                        continue;
14126                    }
14127                    if (DEBUG_SD_INSTALL)
14128                        Log.i(TAG, "Looking for pkg : " + pkgName);
14129
14130                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
14131                    if (ps == null) {
14132                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
14133                        continue;
14134                    }
14135
14136                    /*
14137                     * Skip packages that are not external if we're unmounting
14138                     * external storage.
14139                     */
14140                    if (externalStorage && !isMounted && !isExternal(ps)) {
14141                        continue;
14142                    }
14143
14144                    final AsecInstallArgs args = new AsecInstallArgs(cid,
14145                            getAppDexInstructionSets(ps), ps.isForwardLocked());
14146                    // The package status is changed only if the code path
14147                    // matches between settings and the container id.
14148                    if (ps.codePathString != null
14149                            && ps.codePathString.startsWith(args.getCodePath())) {
14150                        if (DEBUG_SD_INSTALL) {
14151                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
14152                                    + " at code path: " + ps.codePathString);
14153                        }
14154
14155                        // We do have a valid package installed on sdcard
14156                        processCids.put(args, ps.codePathString);
14157                        final int uid = ps.appId;
14158                        if (uid != -1) {
14159                            uidArr = ArrayUtils.appendInt(uidArr, uid);
14160                        }
14161                    } else {
14162                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
14163                                + ps.codePathString);
14164                    }
14165                }
14166            }
14167
14168            Arrays.sort(uidArr);
14169        }
14170
14171        // Process packages with valid entries.
14172        if (isMounted) {
14173            if (DEBUG_SD_INSTALL)
14174                Log.i(TAG, "Loading packages");
14175            loadMediaPackages(processCids, uidArr);
14176            startCleaningPackages();
14177            mInstallerService.onSecureContainersAvailable();
14178        } else {
14179            if (DEBUG_SD_INSTALL)
14180                Log.i(TAG, "Unloading packages");
14181            unloadMediaPackages(processCids, uidArr, reportStatus);
14182        }
14183    }
14184
14185    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14186            ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) {
14187        final int size = infos.size();
14188        final String[] packageNames = new String[size];
14189        final int[] packageUids = new int[size];
14190        for (int i = 0; i < size; i++) {
14191            final ApplicationInfo info = infos.get(i);
14192            packageNames[i] = info.packageName;
14193            packageUids[i] = info.uid;
14194        }
14195        sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids,
14196                finishedReceiver);
14197    }
14198
14199    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14200            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14201        sendResourcesChangedBroadcast(mediaStatus, replacing,
14202                pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver);
14203    }
14204
14205    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
14206            String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
14207        int size = pkgList.length;
14208        if (size > 0) {
14209            // Send broadcasts here
14210            Bundle extras = new Bundle();
14211            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList);
14212            if (uidArr != null) {
14213                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
14214            }
14215            if (replacing) {
14216                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
14217            }
14218            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
14219                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
14220            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
14221        }
14222    }
14223
14224   /*
14225     * Look at potentially valid container ids from processCids If package
14226     * information doesn't match the one on record or package scanning fails,
14227     * the cid is added to list of removeCids. We currently don't delete stale
14228     * containers.
14229     */
14230    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
14231        ArrayList<String> pkgList = new ArrayList<String>();
14232        Set<AsecInstallArgs> keys = processCids.keySet();
14233
14234        for (AsecInstallArgs args : keys) {
14235            String codePath = processCids.get(args);
14236            if (DEBUG_SD_INSTALL)
14237                Log.i(TAG, "Loading container : " + args.cid);
14238            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
14239            try {
14240                // Make sure there are no container errors first.
14241                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
14242                    Slog.e(TAG, "Failed to mount cid : " + args.cid
14243                            + " when installing from sdcard");
14244                    continue;
14245                }
14246                // Check code path here.
14247                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
14248                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
14249                            + " does not match one in settings " + codePath);
14250                    continue;
14251                }
14252                // Parse package
14253                int parseFlags = mDefParseFlags;
14254                if (args.isExternalAsec()) {
14255                    parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE;
14256                }
14257                if (args.isFwdLocked()) {
14258                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
14259                }
14260
14261                synchronized (mInstallLock) {
14262                    PackageParser.Package pkg = null;
14263                    try {
14264                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
14265                    } catch (PackageManagerException e) {
14266                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
14267                    }
14268                    // Scan the package
14269                    if (pkg != null) {
14270                        /*
14271                         * TODO why is the lock being held? doPostInstall is
14272                         * called in other places without the lock. This needs
14273                         * to be straightened out.
14274                         */
14275                        // writer
14276                        synchronized (mPackages) {
14277                            retCode = PackageManager.INSTALL_SUCCEEDED;
14278                            pkgList.add(pkg.packageName);
14279                            // Post process args
14280                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
14281                                    pkg.applicationInfo.uid);
14282                        }
14283                    } else {
14284                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
14285                    }
14286                }
14287
14288            } finally {
14289                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
14290                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
14291                }
14292            }
14293        }
14294        // writer
14295        synchronized (mPackages) {
14296            // If the platform SDK has changed since the last time we booted,
14297            // we need to re-grant app permission to catch any new ones that
14298            // appear. This is really a hack, and means that apps can in some
14299            // cases get permissions that the user didn't initially explicitly
14300            // allow... it would be nice to have some better way to handle
14301            // this situation.
14302            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
14303            if (regrantPermissions)
14304                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
14305                        + mSdkVersion + "; regranting permissions for external storage");
14306            mSettings.mExternalSdkPlatform = mSdkVersion;
14307
14308            // Make sure group IDs have been assigned, and any permission
14309            // changes in other apps are accounted for
14310            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
14311                    | (regrantPermissions
14312                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
14313                            : 0));
14314
14315            mSettings.updateExternalDatabaseVersion();
14316
14317            // can downgrade to reader
14318            // Persist settings
14319            mSettings.writeLPr();
14320        }
14321        // Send a broadcast to let everyone know we are done processing
14322        if (pkgList.size() > 0) {
14323            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
14324        }
14325    }
14326
14327   /*
14328     * Utility method to unload a list of specified containers
14329     */
14330    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
14331        // Just unmount all valid containers.
14332        for (AsecInstallArgs arg : cidArgs) {
14333            synchronized (mInstallLock) {
14334                arg.doPostDeleteLI(false);
14335           }
14336       }
14337   }
14338
14339    /*
14340     * Unload packages mounted on external media. This involves deleting package
14341     * data from internal structures, sending broadcasts about diabled packages,
14342     * gc'ing to free up references, unmounting all secure containers
14343     * corresponding to packages on external media, and posting a
14344     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
14345     * that we always have to post this message if status has been requested no
14346     * matter what.
14347     */
14348    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
14349            final boolean reportStatus) {
14350        if (DEBUG_SD_INSTALL)
14351            Log.i(TAG, "unloading media packages");
14352        ArrayList<String> pkgList = new ArrayList<String>();
14353        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
14354        final Set<AsecInstallArgs> keys = processCids.keySet();
14355        for (AsecInstallArgs args : keys) {
14356            String pkgName = args.getPackageName();
14357            if (DEBUG_SD_INSTALL)
14358                Log.i(TAG, "Trying to unload pkg : " + pkgName);
14359            // Delete package internally
14360            PackageRemovedInfo outInfo = new PackageRemovedInfo();
14361            synchronized (mInstallLock) {
14362                boolean res = deletePackageLI(pkgName, null, false, null, null,
14363                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
14364                if (res) {
14365                    pkgList.add(pkgName);
14366                } else {
14367                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
14368                    failedList.add(args);
14369                }
14370            }
14371        }
14372
14373        // reader
14374        synchronized (mPackages) {
14375            // We didn't update the settings after removing each package;
14376            // write them now for all packages.
14377            mSettings.writeLPr();
14378        }
14379
14380        // We have to absolutely send UPDATED_MEDIA_STATUS only
14381        // after confirming that all the receivers processed the ordered
14382        // broadcast when packages get disabled, force a gc to clean things up.
14383        // and unload all the containers.
14384        if (pkgList.size() > 0) {
14385            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
14386                    new IIntentReceiver.Stub() {
14387                public void performReceive(Intent intent, int resultCode, String data,
14388                        Bundle extras, boolean ordered, boolean sticky,
14389                        int sendingUser) throws RemoteException {
14390                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
14391                            reportStatus ? 1 : 0, 1, keys);
14392                    mHandler.sendMessage(msg);
14393                }
14394            });
14395        } else {
14396            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
14397                    keys);
14398            mHandler.sendMessage(msg);
14399        }
14400    }
14401
14402    private void loadPrivatePackages(VolumeInfo vol) {
14403        final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
14404        final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
14405        synchronized (mInstallLock) {
14406        synchronized (mPackages) {
14407            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14408            for (PackageSetting ps : packages) {
14409                final PackageParser.Package pkg;
14410                try {
14411                    pkg = scanPackageLI(ps.codePath, parseFlags, 0, 0, null);
14412                    loaded.add(pkg.applicationInfo);
14413                } catch (PackageManagerException e) {
14414                    Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
14415                }
14416            }
14417
14418            // TODO: regrant any permissions that changed based since original install
14419
14420            mSettings.writeLPr();
14421        }
14422        }
14423
14424        Slog.d(TAG, "Loaded packages " + loaded);
14425        sendResourcesChangedBroadcast(true, false, loaded, null);
14426    }
14427
14428    private void unloadPrivatePackages(VolumeInfo vol) {
14429        final ArrayList<ApplicationInfo> unloaded = new ArrayList<>();
14430        synchronized (mInstallLock) {
14431        synchronized (mPackages) {
14432            final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(vol.fsUuid);
14433            for (PackageSetting ps : packages) {
14434                if (ps.pkg == null) continue;
14435
14436                final ApplicationInfo info = ps.pkg.applicationInfo;
14437                final PackageRemovedInfo outInfo = new PackageRemovedInfo();
14438                if (deletePackageLI(ps.name, null, false, null, null,
14439                        PackageManager.DELETE_KEEP_DATA, outInfo, false)) {
14440                    unloaded.add(info);
14441                } else {
14442                    Slog.w(TAG, "Failed to unload " + ps.codePath);
14443                }
14444            }
14445
14446            mSettings.writeLPr();
14447        }
14448        }
14449
14450        Slog.d(TAG, "Unloaded packages " + unloaded);
14451        sendResourcesChangedBroadcast(false, false, unloaded, null);
14452    }
14453
14454    private void unfreezePackage(String packageName) {
14455        synchronized (mPackages) {
14456            final PackageSetting ps = mSettings.mPackages.get(packageName);
14457            if (ps != null) {
14458                ps.frozen = false;
14459            }
14460        }
14461    }
14462
14463    @Override
14464    public int movePackage(final String packageName, final String volumeUuid) {
14465        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14466
14467        final int moveId = mNextMoveId.getAndIncrement();
14468        try {
14469            movePackageInternal(packageName, volumeUuid, moveId);
14470        } catch (PackageManagerException e) {
14471            Slog.d(TAG, "Failed to move " + packageName, e);
14472            mMoveCallbacks.notifyStatusChanged(moveId,
14473                    PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14474        }
14475        return moveId;
14476    }
14477
14478    private void movePackageInternal(final String packageName, final String volumeUuid,
14479            final int moveId) throws PackageManagerException {
14480        final UserHandle user = new UserHandle(UserHandle.getCallingUserId());
14481        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14482        final PackageManager pm = mContext.getPackageManager();
14483
14484        final boolean currentAsec;
14485        final String currentVolumeUuid;
14486        final File codeFile;
14487        final String installerPackageName;
14488        final String packageAbiOverride;
14489        final int appId;
14490        final String seinfo;
14491        final String label;
14492
14493        // reader
14494        synchronized (mPackages) {
14495            final PackageParser.Package pkg = mPackages.get(packageName);
14496            final PackageSetting ps = mSettings.mPackages.get(packageName);
14497            if (pkg == null || ps == null) {
14498                throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
14499            }
14500
14501            if (pkg.applicationInfo.isSystemApp()) {
14502                throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE,
14503                        "Cannot move system application");
14504            }
14505
14506            if (Objects.equals(ps.volumeUuid, volumeUuid)) {
14507                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14508                        "Package already moved to " + volumeUuid);
14509            }
14510
14511            final File probe = new File(pkg.codePath);
14512            final File probeOat = new File(probe, "oat");
14513            if (!probe.isDirectory() || !probeOat.isDirectory()) {
14514                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14515                        "Move only supported for modern cluster style installs");
14516            }
14517
14518            if (ps.frozen) {
14519                throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING,
14520                        "Failed to move already frozen package");
14521            }
14522            ps.frozen = true;
14523
14524            currentAsec = pkg.applicationInfo.isForwardLocked()
14525                    || pkg.applicationInfo.isExternalAsec();
14526            currentVolumeUuid = ps.volumeUuid;
14527            codeFile = new File(pkg.codePath);
14528            installerPackageName = ps.installerPackageName;
14529            packageAbiOverride = ps.cpuAbiOverrideString;
14530            appId = UserHandle.getAppId(pkg.applicationInfo.uid);
14531            seinfo = pkg.applicationInfo.seinfo;
14532            label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
14533        }
14534
14535        // Now that we're guarded by frozen state, kill app during move
14536        killApplication(packageName, appId, "move pkg");
14537
14538        final Bundle extras = new Bundle();
14539        extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
14540        extras.putString(Intent.EXTRA_TITLE, label);
14541        mMoveCallbacks.notifyCreated(moveId, extras);
14542
14543        int installFlags;
14544        final boolean moveCompleteApp;
14545        final File measurePath;
14546
14547        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
14548            installFlags = INSTALL_INTERNAL;
14549            moveCompleteApp = !currentAsec;
14550            measurePath = Environment.getDataAppDirectory(volumeUuid);
14551        } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
14552            installFlags = INSTALL_EXTERNAL;
14553            moveCompleteApp = false;
14554            measurePath = storage.getPrimaryPhysicalVolume().getPath();
14555        } else {
14556            final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
14557            if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE
14558                    || !volume.isMountedWritable()) {
14559                unfreezePackage(packageName);
14560                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14561                        "Move location not mounted private volume");
14562            }
14563
14564            Preconditions.checkState(!currentAsec);
14565
14566            installFlags = INSTALL_INTERNAL;
14567            moveCompleteApp = true;
14568            measurePath = Environment.getDataAppDirectory(volumeUuid);
14569        }
14570
14571        final PackageStats stats = new PackageStats(null, -1);
14572        synchronized (mInstaller) {
14573            if (!getPackageSizeInfoLI(packageName, -1, stats)) {
14574                unfreezePackage(packageName);
14575                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14576                        "Failed to measure package size");
14577            }
14578        }
14579
14580        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
14581
14582        final long startFreeBytes = measurePath.getFreeSpace();
14583        final long sizeBytes;
14584        if (moveCompleteApp) {
14585            sizeBytes = stats.codeSize + stats.dataSize;
14586        } else {
14587            sizeBytes = stats.codeSize;
14588        }
14589
14590        if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
14591            unfreezePackage(packageName);
14592            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR,
14593                    "Not enough free space to move");
14594        }
14595
14596        mMoveCallbacks.notifyStatusChanged(moveId, 10);
14597
14598        final CountDownLatch installedLatch = new CountDownLatch(1);
14599        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
14600            @Override
14601            public void onUserActionRequired(Intent intent) throws RemoteException {
14602                throw new IllegalStateException();
14603            }
14604
14605            @Override
14606            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
14607                    Bundle extras) throws RemoteException {
14608                Slog.d(TAG, "Install result for move: "
14609                        + PackageManager.installStatusToString(returnCode, msg));
14610
14611                installedLatch.countDown();
14612
14613                // Regardless of success or failure of the move operation,
14614                // always unfreeze the package
14615                unfreezePackage(packageName);
14616
14617                final int status = PackageManager.installStatusToPublicStatus(returnCode);
14618                switch (status) {
14619                    case PackageInstaller.STATUS_SUCCESS:
14620                        mMoveCallbacks.notifyStatusChanged(moveId,
14621                                PackageManager.MOVE_SUCCEEDED);
14622                        break;
14623                    case PackageInstaller.STATUS_FAILURE_STORAGE:
14624                        mMoveCallbacks.notifyStatusChanged(moveId,
14625                                PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
14626                        break;
14627                    default:
14628                        mMoveCallbacks.notifyStatusChanged(moveId,
14629                                PackageManager.MOVE_FAILED_INTERNAL_ERROR);
14630                        break;
14631                }
14632            }
14633        };
14634
14635        final MoveInfo move;
14636        if (moveCompleteApp) {
14637            // Kick off a thread to report progress estimates
14638            new Thread() {
14639                @Override
14640                public void run() {
14641                    while (true) {
14642                        try {
14643                            if (installedLatch.await(1, TimeUnit.SECONDS)) {
14644                                break;
14645                            }
14646                        } catch (InterruptedException ignored) {
14647                        }
14648
14649                        final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
14650                        final int progress = 10 + (int) MathUtils.constrain(
14651                                ((deltaFreeBytes * 80) / sizeBytes), 0, 80);
14652                        mMoveCallbacks.notifyStatusChanged(moveId, progress);
14653                    }
14654                }
14655            }.start();
14656
14657            final String dataAppName = codeFile.getName();
14658            move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName,
14659                    dataAppName, appId, seinfo);
14660        } else {
14661            move = null;
14662        }
14663
14664        installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
14665
14666        final Message msg = mHandler.obtainMessage(INIT_COPY);
14667        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
14668        msg.obj = new InstallParams(origin, move, installObserver, installFlags,
14669                installerPackageName, volumeUuid, null, user, packageAbiOverride);
14670        mHandler.sendMessage(msg);
14671    }
14672
14673    @Override
14674    public int movePrimaryStorage(String volumeUuid) throws RemoteException {
14675        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
14676
14677        final int realMoveId = mNextMoveId.getAndIncrement();
14678        final Bundle extras = new Bundle();
14679        extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid);
14680        mMoveCallbacks.notifyCreated(realMoveId, extras);
14681
14682        final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() {
14683            @Override
14684            public void onCreated(int moveId, Bundle extras) {
14685                // Ignored
14686            }
14687
14688            @Override
14689            public void onStatusChanged(int moveId, int status, long estMillis) {
14690                mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis);
14691            }
14692        };
14693
14694        final StorageManager storage = mContext.getSystemService(StorageManager.class);
14695        storage.setPrimaryStorageUuid(volumeUuid, callback);
14696        return realMoveId;
14697    }
14698
14699    @Override
14700    public int getMoveStatus(int moveId) {
14701        mContext.enforceCallingOrSelfPermission(
14702                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14703        return mMoveCallbacks.mLastStatus.get(moveId);
14704    }
14705
14706    @Override
14707    public void registerMoveCallback(IPackageMoveObserver callback) {
14708        mContext.enforceCallingOrSelfPermission(
14709                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14710        mMoveCallbacks.register(callback);
14711    }
14712
14713    @Override
14714    public void unregisterMoveCallback(IPackageMoveObserver callback) {
14715        mContext.enforceCallingOrSelfPermission(
14716                android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null);
14717        mMoveCallbacks.unregister(callback);
14718    }
14719
14720    @Override
14721    public boolean setInstallLocation(int loc) {
14722        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
14723                null);
14724        if (getInstallLocation() == loc) {
14725            return true;
14726        }
14727        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
14728                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
14729            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
14730                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
14731            return true;
14732        }
14733        return false;
14734   }
14735
14736    @Override
14737    public int getInstallLocation() {
14738        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
14739                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
14740                PackageHelper.APP_INSTALL_AUTO);
14741    }
14742
14743    /** Called by UserManagerService */
14744    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
14745        mDirtyUsers.remove(userHandle);
14746        mSettings.removeUserLPw(userHandle);
14747        mPendingBroadcasts.remove(userHandle);
14748        if (mInstaller != null) {
14749            // Technically, we shouldn't be doing this with the package lock
14750            // held.  However, this is very rare, and there is already so much
14751            // other disk I/O going on, that we'll let it slide for now.
14752            final StorageManager storage = StorageManager.from(mContext);
14753            final List<VolumeInfo> vols = storage.getVolumes();
14754            for (VolumeInfo vol : vols) {
14755                if (vol.getType() == VolumeInfo.TYPE_PRIVATE && vol.isMountedWritable()) {
14756                    final String volumeUuid = vol.getFsUuid();
14757                    Slog.d(TAG, "Removing user data on volume " + volumeUuid);
14758                    mInstaller.removeUserDataDirs(volumeUuid, userHandle);
14759                }
14760            }
14761        }
14762        mUserNeedsBadging.delete(userHandle);
14763        removeUnusedPackagesLILPw(userManager, userHandle);
14764    }
14765
14766    /**
14767     * We're removing userHandle and would like to remove any downloaded packages
14768     * that are no longer in use by any other user.
14769     * @param userHandle the user being removed
14770     */
14771    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
14772        final boolean DEBUG_CLEAN_APKS = false;
14773        int [] users = userManager.getUserIdsLPr();
14774        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
14775        while (psit.hasNext()) {
14776            PackageSetting ps = psit.next();
14777            if (ps.pkg == null) {
14778                continue;
14779            }
14780            final String packageName = ps.pkg.packageName;
14781            // Skip over if system app
14782            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
14783                continue;
14784            }
14785            if (DEBUG_CLEAN_APKS) {
14786                Slog.i(TAG, "Checking package " + packageName);
14787            }
14788            boolean keep = false;
14789            for (int i = 0; i < users.length; i++) {
14790                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14791                    keep = true;
14792                    if (DEBUG_CLEAN_APKS) {
14793                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14794                                + users[i]);
14795                    }
14796                    break;
14797                }
14798            }
14799            if (!keep) {
14800                if (DEBUG_CLEAN_APKS) {
14801                    Slog.i(TAG, "  Removing package " + packageName);
14802                }
14803                mHandler.post(new Runnable() {
14804                    public void run() {
14805                        deletePackageX(packageName, userHandle, 0);
14806                    } //end run
14807                });
14808            }
14809        }
14810    }
14811
14812    /** Called by UserManagerService */
14813    void createNewUserLILPw(int userHandle, File path) {
14814        if (mInstaller != null) {
14815            mInstaller.createUserConfig(userHandle);
14816            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14817        }
14818    }
14819
14820    void newUserCreatedLILPw(int userHandle) {
14821        // Adding a user requires updating runtime permissions for system apps.
14822        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14823    }
14824
14825    @Override
14826    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14827        mContext.enforceCallingOrSelfPermission(
14828                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14829                "Only package verification agents can read the verifier device identity");
14830
14831        synchronized (mPackages) {
14832            return mSettings.getVerifierDeviceIdentityLPw();
14833        }
14834    }
14835
14836    @Override
14837    public void setPermissionEnforced(String permission, boolean enforced) {
14838        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14839        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14840            synchronized (mPackages) {
14841                if (mSettings.mReadExternalStorageEnforced == null
14842                        || mSettings.mReadExternalStorageEnforced != enforced) {
14843                    mSettings.mReadExternalStorageEnforced = enforced;
14844                    mSettings.writeLPr();
14845                }
14846            }
14847            // kill any non-foreground processes so we restart them and
14848            // grant/revoke the GID.
14849            final IActivityManager am = ActivityManagerNative.getDefault();
14850            if (am != null) {
14851                final long token = Binder.clearCallingIdentity();
14852                try {
14853                    am.killProcessesBelowForeground("setPermissionEnforcement");
14854                } catch (RemoteException e) {
14855                } finally {
14856                    Binder.restoreCallingIdentity(token);
14857                }
14858            }
14859        } else {
14860            throw new IllegalArgumentException("No selective enforcement for " + permission);
14861        }
14862    }
14863
14864    @Override
14865    @Deprecated
14866    public boolean isPermissionEnforced(String permission) {
14867        return true;
14868    }
14869
14870    @Override
14871    public boolean isStorageLow() {
14872        final long token = Binder.clearCallingIdentity();
14873        try {
14874            final DeviceStorageMonitorInternal
14875                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14876            if (dsm != null) {
14877                return dsm.isMemoryLow();
14878            } else {
14879                return false;
14880            }
14881        } finally {
14882            Binder.restoreCallingIdentity(token);
14883        }
14884    }
14885
14886    @Override
14887    public IPackageInstaller getPackageInstaller() {
14888        return mInstallerService;
14889    }
14890
14891    private boolean userNeedsBadging(int userId) {
14892        int index = mUserNeedsBadging.indexOfKey(userId);
14893        if (index < 0) {
14894            final UserInfo userInfo;
14895            final long token = Binder.clearCallingIdentity();
14896            try {
14897                userInfo = sUserManager.getUserInfo(userId);
14898            } finally {
14899                Binder.restoreCallingIdentity(token);
14900            }
14901            final boolean b;
14902            if (userInfo != null && userInfo.isManagedProfile()) {
14903                b = true;
14904            } else {
14905                b = false;
14906            }
14907            mUserNeedsBadging.put(userId, b);
14908            return b;
14909        }
14910        return mUserNeedsBadging.valueAt(index);
14911    }
14912
14913    @Override
14914    public KeySet getKeySetByAlias(String packageName, String alias) {
14915        if (packageName == null || alias == null) {
14916            return null;
14917        }
14918        synchronized(mPackages) {
14919            final PackageParser.Package pkg = mPackages.get(packageName);
14920            if (pkg == null) {
14921                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14922                throw new IllegalArgumentException("Unknown package: " + packageName);
14923            }
14924            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14925            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14926        }
14927    }
14928
14929    @Override
14930    public KeySet getSigningKeySet(String packageName) {
14931        if (packageName == null) {
14932            return null;
14933        }
14934        synchronized(mPackages) {
14935            final PackageParser.Package pkg = mPackages.get(packageName);
14936            if (pkg == null) {
14937                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14938                throw new IllegalArgumentException("Unknown package: " + packageName);
14939            }
14940            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14941                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14942                throw new SecurityException("May not access signing KeySet of other apps.");
14943            }
14944            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14945            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14946        }
14947    }
14948
14949    @Override
14950    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14951        if (packageName == null || ks == null) {
14952            return false;
14953        }
14954        synchronized(mPackages) {
14955            final PackageParser.Package pkg = mPackages.get(packageName);
14956            if (pkg == null) {
14957                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14958                throw new IllegalArgumentException("Unknown package: " + packageName);
14959            }
14960            IBinder ksh = ks.getToken();
14961            if (ksh instanceof KeySetHandle) {
14962                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14963                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14964            }
14965            return false;
14966        }
14967    }
14968
14969    @Override
14970    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14971        if (packageName == null || ks == null) {
14972            return false;
14973        }
14974        synchronized(mPackages) {
14975            final PackageParser.Package pkg = mPackages.get(packageName);
14976            if (pkg == null) {
14977                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14978                throw new IllegalArgumentException("Unknown package: " + packageName);
14979            }
14980            IBinder ksh = ks.getToken();
14981            if (ksh instanceof KeySetHandle) {
14982                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14983                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14984            }
14985            return false;
14986        }
14987    }
14988
14989    public void getUsageStatsIfNoPackageUsageInfo() {
14990        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14991            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14992            if (usm == null) {
14993                throw new IllegalStateException("UsageStatsManager must be initialized");
14994            }
14995            long now = System.currentTimeMillis();
14996            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14997            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14998                String packageName = entry.getKey();
14999                PackageParser.Package pkg = mPackages.get(packageName);
15000                if (pkg == null) {
15001                    continue;
15002                }
15003                UsageStats usage = entry.getValue();
15004                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
15005                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
15006            }
15007        }
15008    }
15009
15010    /**
15011     * Check and throw if the given before/after packages would be considered a
15012     * downgrade.
15013     */
15014    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
15015            throws PackageManagerException {
15016        if (after.versionCode < before.mVersionCode) {
15017            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15018                    "Update version code " + after.versionCode + " is older than current "
15019                    + before.mVersionCode);
15020        } else if (after.versionCode == before.mVersionCode) {
15021            if (after.baseRevisionCode < before.baseRevisionCode) {
15022                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15023                        "Update base revision code " + after.baseRevisionCode
15024                        + " is older than current " + before.baseRevisionCode);
15025            }
15026
15027            if (!ArrayUtils.isEmpty(after.splitNames)) {
15028                for (int i = 0; i < after.splitNames.length; i++) {
15029                    final String splitName = after.splitNames[i];
15030                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
15031                    if (j != -1) {
15032                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
15033                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
15034                                    "Update split " + splitName + " revision code "
15035                                    + after.splitRevisionCodes[i] + " is older than current "
15036                                    + before.splitRevisionCodes[j]);
15037                        }
15038                    }
15039                }
15040            }
15041        }
15042    }
15043
15044    private static class MoveCallbacks extends Handler {
15045        private static final int MSG_CREATED = 1;
15046        private static final int MSG_STATUS_CHANGED = 2;
15047
15048        private final RemoteCallbackList<IPackageMoveObserver>
15049                mCallbacks = new RemoteCallbackList<>();
15050
15051        private final SparseIntArray mLastStatus = new SparseIntArray();
15052
15053        public MoveCallbacks(Looper looper) {
15054            super(looper);
15055        }
15056
15057        public void register(IPackageMoveObserver callback) {
15058            mCallbacks.register(callback);
15059        }
15060
15061        public void unregister(IPackageMoveObserver callback) {
15062            mCallbacks.unregister(callback);
15063        }
15064
15065        @Override
15066        public void handleMessage(Message msg) {
15067            final SomeArgs args = (SomeArgs) msg.obj;
15068            final int n = mCallbacks.beginBroadcast();
15069            for (int i = 0; i < n; i++) {
15070                final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i);
15071                try {
15072                    invokeCallback(callback, msg.what, args);
15073                } catch (RemoteException ignored) {
15074                }
15075            }
15076            mCallbacks.finishBroadcast();
15077            args.recycle();
15078        }
15079
15080        private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args)
15081                throws RemoteException {
15082            switch (what) {
15083                case MSG_CREATED: {
15084                    callback.onCreated(args.argi1, (Bundle) args.arg2);
15085                    break;
15086                }
15087                case MSG_STATUS_CHANGED: {
15088                    callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
15089                    break;
15090                }
15091            }
15092        }
15093
15094        private void notifyCreated(int moveId, Bundle extras) {
15095            Slog.v(TAG, "Move " + moveId + " created " + extras.toString());
15096
15097            final SomeArgs args = SomeArgs.obtain();
15098            args.argi1 = moveId;
15099            args.arg2 = extras;
15100            obtainMessage(MSG_CREATED, args).sendToTarget();
15101        }
15102
15103        private void notifyStatusChanged(int moveId, int status) {
15104            notifyStatusChanged(moveId, status, -1);
15105        }
15106
15107        private void notifyStatusChanged(int moveId, int status, long estMillis) {
15108            Slog.v(TAG, "Move " + moveId + " status " + status);
15109
15110            final SomeArgs args = SomeArgs.obtain();
15111            args.argi1 = moveId;
15112            args.argi2 = status;
15113            args.arg3 = estMillis;
15114            obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
15115
15116            synchronized (mLastStatus) {
15117                mLastStatus.put(moveId, status);
15118            }
15119        }
15120    }
15121}
15122