PackageManagerService.java revision 429270c3ed1da02914efb476be977dc3829d4c30
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_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
47import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER;
48import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
49import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
50import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
51import static android.content.pm.PackageParser.isApkFile;
52import static android.os.Process.PACKAGE_INFO_GID;
53import static android.os.Process.SYSTEM_UID;
54import static android.system.OsConstants.O_CREAT;
55import static android.system.OsConstants.O_RDWR;
56import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
57import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
58import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
59import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
60import static com.android.internal.util.ArrayUtils.appendInt;
61import static com.android.server.pm.InstructionSets.getAppDexInstructionSets;
62import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet;
63import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets;
64import static com.android.server.pm.InstructionSets.getPreferredInstructionSet;
65import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet;
66
67import android.Manifest;
68import android.content.pm.IntentFilterVerificationInfo;
69import android.util.ArrayMap;
70
71import com.android.internal.R;
72import com.android.internal.app.IMediaContainerService;
73import com.android.internal.app.ResolverActivity;
74import com.android.internal.content.NativeLibraryHelper;
75import com.android.internal.content.PackageHelper;
76import com.android.internal.os.IParcelFileDescriptorFactory;
77import com.android.internal.util.ArrayUtils;
78import com.android.internal.util.FastPrintWriter;
79import com.android.internal.util.FastXmlSerializer;
80import com.android.internal.util.IndentingPrintWriter;
81import com.android.server.EventLogTags;
82import com.android.server.IntentResolver;
83import com.android.server.LocalServices;
84import com.android.server.ServiceThread;
85import com.android.server.SystemConfig;
86import com.android.server.Watchdog;
87import com.android.server.pm.Settings.DatabaseVersion;
88import com.android.server.storage.DeviceStorageMonitorInternal;
89
90import org.xmlpull.v1.XmlSerializer;
91
92import android.app.ActivityManager;
93import android.app.ActivityManagerNative;
94import android.app.AppGlobals;
95import android.app.IActivityManager;
96import android.app.admin.IDevicePolicyManager;
97import android.app.backup.IBackupManager;
98import android.app.usage.UsageStats;
99import android.app.usage.UsageStatsManager;
100import android.content.BroadcastReceiver;
101import android.content.ComponentName;
102import android.content.Context;
103import android.content.IIntentReceiver;
104import android.content.Intent;
105import android.content.IntentFilter;
106import android.content.IntentSender;
107import android.content.IntentSender.SendIntentException;
108import android.content.ServiceConnection;
109import android.content.pm.ActivityInfo;
110import android.content.pm.ApplicationInfo;
111import android.content.pm.FeatureInfo;
112import android.content.pm.IPackageDataObserver;
113import android.content.pm.IPackageDeleteObserver;
114import android.content.pm.IPackageDeleteObserver2;
115import android.content.pm.IPackageInstallObserver2;
116import android.content.pm.IPackageInstaller;
117import android.content.pm.IPackageManager;
118import android.content.pm.IPackageMoveObserver;
119import android.content.pm.IPackageStatsObserver;
120import android.content.pm.InstrumentationInfo;
121import android.content.pm.KeySet;
122import android.content.pm.ManifestDigest;
123import android.content.pm.PackageCleanItem;
124import android.content.pm.PackageInfo;
125import android.content.pm.PackageInfoLite;
126import android.content.pm.PackageInstaller;
127import android.content.pm.PackageManager;
128import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
129import android.content.pm.PackageParser.ActivityIntentInfo;
130import android.content.pm.PackageParser.PackageLite;
131import android.content.pm.PackageParser.PackageParserException;
132import android.content.pm.PackageParser;
133import android.content.pm.PackageStats;
134import android.content.pm.PackageUserState;
135import android.content.pm.ParceledListSlice;
136import android.content.pm.PermissionGroupInfo;
137import android.content.pm.PermissionInfo;
138import android.content.pm.ProviderInfo;
139import android.content.pm.ResolveInfo;
140import android.content.pm.ServiceInfo;
141import android.content.pm.Signature;
142import android.content.pm.UserInfo;
143import android.content.pm.VerificationParams;
144import android.content.pm.VerifierDeviceIdentity;
145import android.content.pm.VerifierInfo;
146import android.content.res.Resources;
147import android.hardware.display.DisplayManager;
148import android.net.Uri;
149import android.os.Binder;
150import android.os.Build;
151import android.os.Bundle;
152import android.os.Environment;
153import android.os.Environment.UserEnvironment;
154import android.os.storage.IMountService;
155import android.os.storage.StorageEventListener;
156import android.os.storage.StorageManager;
157import android.os.storage.VolumeInfo;
158import android.os.Debug;
159import android.os.FileUtils;
160import android.os.Handler;
161import android.os.IBinder;
162import android.os.Looper;
163import android.os.Message;
164import android.os.Parcel;
165import android.os.ParcelFileDescriptor;
166import android.os.Process;
167import android.os.RemoteException;
168import android.os.SELinux;
169import android.os.ServiceManager;
170import android.os.SystemClock;
171import android.os.SystemProperties;
172import android.os.UserHandle;
173import android.os.UserManager;
174import android.security.KeyStore;
175import android.security.SystemKeyStore;
176import android.system.ErrnoException;
177import android.system.Os;
178import android.system.StructStat;
179import android.text.TextUtils;
180import android.text.format.DateUtils;
181import android.util.ArraySet;
182import android.util.AtomicFile;
183import android.util.DisplayMetrics;
184import android.util.EventLog;
185import android.util.ExceptionUtils;
186import android.util.Log;
187import android.util.LogPrinter;
188import android.util.PrintStreamPrinter;
189import android.util.Slog;
190import android.util.SparseArray;
191import android.util.SparseBooleanArray;
192import android.view.Display;
193
194import java.io.BufferedInputStream;
195import java.io.BufferedOutputStream;
196import java.io.BufferedReader;
197import java.io.File;
198import java.io.FileDescriptor;
199import java.io.FileNotFoundException;
200import java.io.FileOutputStream;
201import java.io.FileReader;
202import java.io.FilenameFilter;
203import java.io.IOException;
204import java.io.InputStream;
205import java.io.PrintWriter;
206import java.nio.charset.StandardCharsets;
207import java.security.NoSuchAlgorithmException;
208import java.security.PublicKey;
209import java.security.cert.CertificateEncodingException;
210import java.security.cert.CertificateException;
211import java.text.SimpleDateFormat;
212import java.util.ArrayList;
213import java.util.Arrays;
214import java.util.Collection;
215import java.util.Collections;
216import java.util.Comparator;
217import java.util.Date;
218import java.util.Iterator;
219import java.util.List;
220import java.util.Map;
221import java.util.Objects;
222import java.util.Set;
223import java.util.concurrent.atomic.AtomicBoolean;
224import java.util.concurrent.atomic.AtomicLong;
225
226import dalvik.system.DexFile;
227import dalvik.system.VMRuntime;
228
229import libcore.io.IoUtils;
230import libcore.util.EmptyArray;
231
232/**
233 * Keep track of all those .apks everywhere.
234 *
235 * This is very central to the platform's security; please run the unit
236 * tests whenever making modifications here:
237 *
238mmm frameworks/base/tests/AndroidTests
239adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
240adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
241 *
242 * {@hide}
243 */
244public class PackageManagerService extends IPackageManager.Stub {
245    static final String TAG = "PackageManager";
246    static final boolean DEBUG_SETTINGS = false;
247    static final boolean DEBUG_PREFERRED = false;
248    static final boolean DEBUG_UPGRADE = false;
249    private static final boolean DEBUG_INSTALL = false;
250    private static final boolean DEBUG_REMOVE = false;
251    private static final boolean DEBUG_BROADCASTS = false;
252    private static final boolean DEBUG_SHOW_INFO = false;
253    private static final boolean DEBUG_PACKAGE_INFO = false;
254    private static final boolean DEBUG_INTENT_MATCHING = false;
255    private static final boolean DEBUG_PACKAGE_SCANNING = false;
256    private static final boolean DEBUG_VERIFY = false;
257    private static final boolean DEBUG_DEXOPT = false;
258    private static final boolean DEBUG_ABI_SELECTION = false;
259
260    static final boolean RUNTIME_PERMISSIONS_ENABLED = true;
261
262    private static final int RADIO_UID = Process.PHONE_UID;
263    private static final int LOG_UID = Process.LOG_UID;
264    private static final int NFC_UID = Process.NFC_UID;
265    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
266    private static final int SHELL_UID = Process.SHELL_UID;
267
268    // Cap the size of permission trees that 3rd party apps can define
269    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
270
271    // Suffix used during package installation when copying/moving
272    // package apks to install directory.
273    private static final String INSTALL_PACKAGE_SUFFIX = "-";
274
275    static final int SCAN_NO_DEX = 1<<1;
276    static final int SCAN_FORCE_DEX = 1<<2;
277    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
278    static final int SCAN_NEW_INSTALL = 1<<4;
279    static final int SCAN_NO_PATHS = 1<<5;
280    static final int SCAN_UPDATE_TIME = 1<<6;
281    static final int SCAN_DEFER_DEX = 1<<7;
282    static final int SCAN_BOOTING = 1<<8;
283    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
284    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
285    static final int SCAN_REPLACING = 1<<11;
286    static final int SCAN_REQUIRE_KNOWN = 1<<12;
287
288    static final int REMOVE_CHATTY = 1<<16;
289
290    /**
291     * Timeout (in milliseconds) after which the watchdog should declare that
292     * our handler thread is wedged.  The usual default for such things is one
293     * minute but we sometimes do very lengthy I/O operations on this thread,
294     * such as installing multi-gigabyte applications, so ours needs to be longer.
295     */
296    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
297
298    /**
299     * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim
300     * be run on this device.  We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL
301     * settings entry if available, otherwise we use the hardcoded default.  If it's been
302     * more than this long since the last fstrim, we force one during the boot sequence.
303     *
304     * This backstops other fstrim scheduling:  if the device is alive at midnight+idle,
305     * one gets run at the next available charging+idle time.  This final mandatory
306     * no-fstrim check kicks in only of the other scheduling criteria is never met.
307     */
308    private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS;
309
310    /**
311     * Whether verification is enabled by default.
312     */
313    private static final boolean DEFAULT_VERIFY_ENABLE = true;
314
315    /**
316     * The default maximum time to wait for the verification agent to return in
317     * milliseconds.
318     */
319    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
320
321    /**
322     * The default response for package verification timeout.
323     *
324     * This can be either PackageManager.VERIFICATION_ALLOW or
325     * PackageManager.VERIFICATION_REJECT.
326     */
327    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
328
329    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
330
331    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
332            DEFAULT_CONTAINER_PACKAGE,
333            "com.android.defcontainer.DefaultContainerService");
334
335    private static final String KILL_APP_REASON_GIDS_CHANGED =
336            "permission grant or revoke changed gids";
337
338    private static final String KILL_APP_REASON_PERMISSIONS_REVOKED =
339            "permissions revoked";
340
341    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
342
343    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
344
345    /** Permission grant: not grant the permission. */
346    private static final int GRANT_DENIED = 1;
347
348    /** Permission grant: grant the permission as an install permission. */
349    private static final int GRANT_INSTALL = 2;
350
351    /** Permission grant: grant the permission as a runtime one. */
352    private static final int GRANT_RUNTIME = 3;
353
354    /** Permission grant: grant as runtime a permission that was granted as an install time one. */
355    private static final int GRANT_UPGRADE = 4;
356
357    final ServiceThread mHandlerThread;
358
359    final PackageHandler mHandler;
360
361    /**
362     * Messages for {@link #mHandler} that need to wait for system ready before
363     * being dispatched.
364     */
365    private ArrayList<Message> mPostSystemReadyMessages;
366
367    final int mSdkVersion = Build.VERSION.SDK_INT;
368
369    final Context mContext;
370    final boolean mFactoryTest;
371    final boolean mOnlyCore;
372    final boolean mLazyDexOpt;
373    final long mDexOptLRUThresholdInMills;
374    final DisplayMetrics mMetrics;
375    final int mDefParseFlags;
376    final String[] mSeparateProcesses;
377    final boolean mIsUpgrade;
378
379    // This is where all application persistent data goes.
380    final File mAppDataDir;
381
382    // This is where all application persistent data goes for secondary users.
383    final File mUserAppDataDir;
384
385    /** The location for ASEC container files on internal storage. */
386    final String mAsecInternalPath;
387
388    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
389    // LOCK HELD.  Can be called with mInstallLock held.
390    final Installer mInstaller;
391
392    /** Directory where installed third-party apps stored */
393    final File mAppInstallDir;
394
395    /**
396     * Directory to which applications installed internally have their
397     * 32 bit native libraries copied.
398     */
399    private File mAppLib32InstallDir;
400
401    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
402    // apps.
403    final File mDrmAppPrivateInstallDir;
404
405    // ----------------------------------------------------------------
406
407    // Lock for state used when installing and doing other long running
408    // operations.  Methods that must be called with this lock held have
409    // the suffix "LI".
410    final Object mInstallLock = new Object();
411
412    // ----------------------------------------------------------------
413
414    // Keys are String (package name), values are Package.  This also serves
415    // as the lock for the global state.  Methods that must be called with
416    // this lock held have the prefix "LP".
417    final ArrayMap<String, PackageParser.Package> mPackages =
418            new ArrayMap<String, PackageParser.Package>();
419
420    // Tracks available target package names -> overlay package paths.
421    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
422        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
423
424    final Settings mSettings;
425    boolean mRestoredSettings;
426
427    // System configuration read by SystemConfig.
428    final int[] mGlobalGids;
429    final SparseArray<ArraySet<String>> mSystemPermissions;
430    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
431
432    // If mac_permissions.xml was found for seinfo labeling.
433    boolean mFoundPolicyFile;
434
435    // If a recursive restorecon of /data/data/<pkg> is needed.
436    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
437
438    public static final class SharedLibraryEntry {
439        public final String path;
440        public final String apk;
441
442        SharedLibraryEntry(String _path, String _apk) {
443            path = _path;
444            apk = _apk;
445        }
446    }
447
448    // Currently known shared libraries.
449    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
450            new ArrayMap<String, SharedLibraryEntry>();
451
452    // All available activities, for your resolving pleasure.
453    final ActivityIntentResolver mActivities =
454            new ActivityIntentResolver();
455
456    // All available receivers, for your resolving pleasure.
457    final ActivityIntentResolver mReceivers =
458            new ActivityIntentResolver();
459
460    // All available services, for your resolving pleasure.
461    final ServiceIntentResolver mServices = new ServiceIntentResolver();
462
463    // All available providers, for your resolving pleasure.
464    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
465
466    // Mapping from provider base names (first directory in content URI codePath)
467    // to the provider information.
468    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
469            new ArrayMap<String, PackageParser.Provider>();
470
471    // Mapping from instrumentation class names to info about them.
472    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
473            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
474
475    // Mapping from permission names to info about them.
476    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
477            new ArrayMap<String, PackageParser.PermissionGroup>();
478
479    // Packages whose data we have transfered into another package, thus
480    // should no longer exist.
481    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
482
483    // Broadcast actions that are only available to the system.
484    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
485
486    /** List of packages waiting for verification. */
487    final SparseArray<PackageVerificationState> mPendingVerification
488            = new SparseArray<PackageVerificationState>();
489
490    /** Set of packages associated with each app op permission. */
491    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
492
493    final PackageInstallerService mInstallerService;
494
495    private final PackageDexOptimizer mPackageDexOptimizer;
496    // Cache of users who need badging.
497    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
498
499    /** Token for keys in mPendingVerification. */
500    private int mPendingVerificationToken = 0;
501
502    volatile boolean mSystemReady;
503    volatile boolean mSafeMode;
504    volatile boolean mHasSystemUidErrors;
505
506    ApplicationInfo mAndroidApplication;
507    final ActivityInfo mResolveActivity = new ActivityInfo();
508    final ResolveInfo mResolveInfo = new ResolveInfo();
509    ComponentName mResolveComponentName;
510    PackageParser.Package mPlatformPackage;
511    ComponentName mCustomResolverComponentName;
512
513    boolean mResolverReplaced = false;
514
515    private final ComponentName mIntentFilterVerifierComponent;
516    private int mIntentFilterVerificationToken = 0;
517
518    final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates
519            = new SparseArray<IntentFilterVerificationState>();
520
521    private interface IntentFilterVerifier<T extends IntentFilter> {
522        boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
523                                               T filter, String packageName);
524        void startVerifications(int userId);
525        void receiveVerificationResponse(int verificationId);
526    }
527
528    private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> {
529        private Context mContext;
530        private ComponentName mIntentFilterVerifierComponent;
531        private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>();
532
533        public IntentVerifierProxy(Context context, ComponentName verifierComponent) {
534            mContext = context;
535            mIntentFilterVerifierComponent = verifierComponent;
536        }
537
538        private String getDefaultScheme() {
539            // TODO: replace SCHEME_HTTP with SCHEME_HTTPS
540            return IntentFilter.SCHEME_HTTP;
541        }
542
543        @Override
544        public void startVerifications(int userId) {
545            // Launch verifications requests
546            int count = mCurrentIntentFilterVerifications.size();
547            for (int n=0; n<count; n++) {
548                int verificationId = mCurrentIntentFilterVerifications.get(n);
549                final IntentFilterVerificationState ivs =
550                        mIntentFilterVerificationStates.get(verificationId);
551
552                String packageName = ivs.getPackageName();
553                boolean modified = false;
554
555                ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
556                final int filterCount = filters.size();
557                for (int m=0; m<filterCount; m++) {
558                    PackageParser.ActivityIntentInfo filter = filters.get(m);
559                    synchronized (mPackages) {
560                        modified = mSettings.createIntentFilterVerificationIfNeededLPw(
561                                packageName, filter.getHosts());
562                    }
563                }
564                synchronized (mPackages) {
565                    if (modified) {
566                        scheduleWriteSettingsLocked();
567                    }
568                }
569                sendVerificationRequest(userId, verificationId, ivs);
570            }
571            mCurrentIntentFilterVerifications.clear();
572        }
573
574        private void sendVerificationRequest(int userId, int verificationId,
575                                             IntentFilterVerificationState ivs) {
576
577            Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
578            verificationIntent.putExtra(
579                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID,
580                    verificationId);
581            verificationIntent.putExtra(
582                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME,
583                    getDefaultScheme());
584            verificationIntent.putExtra(
585                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS,
586                    ivs.getHostsString());
587            verificationIntent.putExtra(
588                    PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME,
589                    ivs.getPackageName());
590            verificationIntent.setComponent(mIntentFilterVerifierComponent);
591            verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
592
593            UserHandle user = new UserHandle(userId);
594            mContext.sendBroadcastAsUser(verificationIntent, user);
595            Slog.d(TAG, "Sending IntenFilter verification broadcast");
596        }
597
598        public void receiveVerificationResponse(int verificationId) {
599            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
600
601            final boolean verified = ivs.isVerified();
602
603            ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters();
604            final int count = filters.size();
605            for (int n=0; n<count; n++) {
606                PackageParser.ActivityIntentInfo filter = filters.get(n);
607                filter.setVerified(verified);
608
609                Slog.d(TAG, "IntentFilter " + filter.toString() + " verified with result:"
610                        + verified + " and hosts:" + ivs.getHostsString());
611            }
612
613            mIntentFilterVerificationStates.remove(verificationId);
614
615            final String packageName = ivs.getPackageName();
616            IntentFilterVerificationInfo ivi = null;
617
618            synchronized (mPackages) {
619                ivi = mSettings.getIntentFilterVerificationLPr(packageName);
620            }
621            if (ivi == null) {
622                Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:"
623                        + verificationId + " packageName:" + packageName);
624                return;
625            }
626            Slog.d(TAG, "Updating IntentFilterVerificationInfo for verificationId: "
627                    + verificationId);
628
629            synchronized (mPackages) {
630                if (verified) {
631                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS);
632                } else {
633                    ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK);
634                }
635                scheduleWriteSettingsLocked();
636
637                final int userId = ivs.getUserId();
638                if (userId != UserHandle.USER_ALL) {
639                    final int userStatus =
640                            mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
641
642                    int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED;
643                    boolean needUpdate = false;
644
645                    // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have
646                    // already been set by the User thru the Disambiguation dialog
647                    switch (userStatus) {
648                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
649                            if (verified) {
650                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
651                            } else {
652                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK;
653                            }
654                            needUpdate = true;
655                            break;
656
657                        case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
658                            if (verified) {
659                                updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS;
660                                needUpdate = true;
661                            }
662                            break;
663
664                        default:
665                            // Nothing to do
666                    }
667
668                    if (needUpdate) {
669                        mSettings.updateIntentFilterVerificationStatusLPw(
670                                packageName, updatedStatus, userId);
671                        scheduleWritePackageRestrictionsLocked(userId);
672                    }
673                }
674            }
675        }
676
677        @Override
678        public boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId,
679                    ActivityIntentInfo filter, String packageName) {
680            if (!(filter.hasDataScheme(IntentFilter.SCHEME_HTTP) ||
681                    filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) {
682                Slog.d(TAG, "IntentFilter does not contain HTTP nor HTTPS data scheme");
683                return false;
684            }
685            IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId);
686            if (ivs == null) {
687                ivs = createDomainVerificationState(verifierId, userId, verificationId,
688                        packageName);
689            }
690            ArrayList<String> hosts = filter.getHostsList();
691            if (!hasValidHosts(hosts)) {
692                return false;
693            }
694            ivs.addFilter(filter);
695            return true;
696        }
697
698        private IntentFilterVerificationState createDomainVerificationState(int verifierId,
699                int userId, int verificationId, String packageName) {
700            IntentFilterVerificationState ivs = new IntentFilterVerificationState(
701                    verifierId, userId, packageName);
702            ivs.setPendingState();
703            synchronized (mPackages) {
704                mIntentFilterVerificationStates.append(verificationId, ivs);
705                mCurrentIntentFilterVerifications.add(verificationId);
706            }
707            return ivs;
708        }
709
710        private boolean hasValidHosts(ArrayList<String> hosts) {
711            if (hosts.size() == 0) {
712                Slog.d(TAG, "IntentFilter does not contain any data hosts");
713                return false;
714            }
715            String hostEndBase = null;
716            for (String host : hosts) {
717                String[] hostParts = host.split("\\.");
718                // Should be at minimum a host like "example.com"
719                if (hostParts.length < 2) {
720                    Slog.d(TAG, "IntentFilter does not contain a valid data host name: " + host);
721                    return false;
722                }
723                // Verify that we have the same ending domain
724                int length = hostParts.length;
725                String hostEnd = hostParts[length - 1] + hostParts[length - 2];
726                if (hostEndBase == null) {
727                    hostEndBase = hostEnd;
728                }
729                if (!hostEnd.equalsIgnoreCase(hostEndBase)) {
730                    Slog.d(TAG, "IntentFilter does not contain the same data domains");
731                    return false;
732                }
733            }
734            return true;
735        }
736    }
737
738    private IntentFilterVerifier mIntentFilterVerifier;
739
740    // Set of pending broadcasts for aggregating enable/disable of components.
741    static class PendingPackageBroadcasts {
742        // for each user id, a map of <package name -> components within that package>
743        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
744
745        public PendingPackageBroadcasts() {
746            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
747        }
748
749        public ArrayList<String> get(int userId, String packageName) {
750            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
751            return packages.get(packageName);
752        }
753
754        public void put(int userId, String packageName, ArrayList<String> components) {
755            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
756            packages.put(packageName, components);
757        }
758
759        public void remove(int userId, String packageName) {
760            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
761            if (packages != null) {
762                packages.remove(packageName);
763            }
764        }
765
766        public void remove(int userId) {
767            mUidMap.remove(userId);
768        }
769
770        public int userIdCount() {
771            return mUidMap.size();
772        }
773
774        public int userIdAt(int n) {
775            return mUidMap.keyAt(n);
776        }
777
778        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
779            return mUidMap.get(userId);
780        }
781
782        public int size() {
783            // total number of pending broadcast entries across all userIds
784            int num = 0;
785            for (int i = 0; i< mUidMap.size(); i++) {
786                num += mUidMap.valueAt(i).size();
787            }
788            return num;
789        }
790
791        public void clear() {
792            mUidMap.clear();
793        }
794
795        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
796            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
797            if (map == null) {
798                map = new ArrayMap<String, ArrayList<String>>();
799                mUidMap.put(userId, map);
800            }
801            return map;
802        }
803    }
804    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
805
806    // Service Connection to remote media container service to copy
807    // package uri's from external media onto secure containers
808    // or internal storage.
809    private IMediaContainerService mContainerService = null;
810
811    static final int SEND_PENDING_BROADCAST = 1;
812    static final int MCS_BOUND = 3;
813    static final int END_COPY = 4;
814    static final int INIT_COPY = 5;
815    static final int MCS_UNBIND = 6;
816    static final int START_CLEANING_PACKAGE = 7;
817    static final int FIND_INSTALL_LOC = 8;
818    static final int POST_INSTALL = 9;
819    static final int MCS_RECONNECT = 10;
820    static final int MCS_GIVE_UP = 11;
821    static final int UPDATED_MEDIA_STATUS = 12;
822    static final int WRITE_SETTINGS = 13;
823    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
824    static final int PACKAGE_VERIFIED = 15;
825    static final int CHECK_PENDING_VERIFICATION = 16;
826    static final int START_INTENT_FILTER_VERIFICATIONS = 17;
827    static final int INTENT_FILTER_VERIFIED = 18;
828
829    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
830
831    // Delay time in millisecs
832    static final int BROADCAST_DELAY = 10 * 1000;
833
834    static UserManagerService sUserManager;
835
836    // Stores a list of users whose package restrictions file needs to be updated
837    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
838
839    final private DefaultContainerConnection mDefContainerConn =
840            new DefaultContainerConnection();
841    class DefaultContainerConnection implements ServiceConnection {
842        public void onServiceConnected(ComponentName name, IBinder service) {
843            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
844            IMediaContainerService imcs =
845                IMediaContainerService.Stub.asInterface(service);
846            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
847        }
848
849        public void onServiceDisconnected(ComponentName name) {
850            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
851        }
852    };
853
854    // Recordkeeping of restore-after-install operations that are currently in flight
855    // between the Package Manager and the Backup Manager
856    class PostInstallData {
857        public InstallArgs args;
858        public PackageInstalledInfo res;
859
860        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
861            args = _a;
862            res = _r;
863        }
864    };
865    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
866    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
867
868    private final String mRequiredVerifierPackage;
869
870    private final PackageUsage mPackageUsage = new PackageUsage();
871
872    private class PackageUsage {
873        private static final int WRITE_INTERVAL
874            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
875
876        private final Object mFileLock = new Object();
877        private final AtomicLong mLastWritten = new AtomicLong(0);
878        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
879
880        private boolean mIsHistoricalPackageUsageAvailable = true;
881
882        boolean isHistoricalPackageUsageAvailable() {
883            return mIsHistoricalPackageUsageAvailable;
884        }
885
886        void write(boolean force) {
887            if (force) {
888                writeInternal();
889                return;
890            }
891            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
892                && !DEBUG_DEXOPT) {
893                return;
894            }
895            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
896                new Thread("PackageUsage_DiskWriter") {
897                    @Override
898                    public void run() {
899                        try {
900                            writeInternal();
901                        } finally {
902                            mBackgroundWriteRunning.set(false);
903                        }
904                    }
905                }.start();
906            }
907        }
908
909        private void writeInternal() {
910            synchronized (mPackages) {
911                synchronized (mFileLock) {
912                    AtomicFile file = getFile();
913                    FileOutputStream f = null;
914                    try {
915                        f = file.startWrite();
916                        BufferedOutputStream out = new BufferedOutputStream(f);
917                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID);
918                        StringBuilder sb = new StringBuilder();
919                        for (PackageParser.Package pkg : mPackages.values()) {
920                            if (pkg.mLastPackageUsageTimeInMills == 0) {
921                                continue;
922                            }
923                            sb.setLength(0);
924                            sb.append(pkg.packageName);
925                            sb.append(' ');
926                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
927                            sb.append('\n');
928                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
929                        }
930                        out.flush();
931                        file.finishWrite(f);
932                    } catch (IOException e) {
933                        if (f != null) {
934                            file.failWrite(f);
935                        }
936                        Log.e(TAG, "Failed to write package usage times", e);
937                    }
938                }
939            }
940            mLastWritten.set(SystemClock.elapsedRealtime());
941        }
942
943        void readLP() {
944            synchronized (mFileLock) {
945                AtomicFile file = getFile();
946                BufferedInputStream in = null;
947                try {
948                    in = new BufferedInputStream(file.openRead());
949                    StringBuffer sb = new StringBuffer();
950                    while (true) {
951                        String packageName = readToken(in, sb, ' ');
952                        if (packageName == null) {
953                            break;
954                        }
955                        String timeInMillisString = readToken(in, sb, '\n');
956                        if (timeInMillisString == null) {
957                            throw new IOException("Failed to find last usage time for package "
958                                                  + packageName);
959                        }
960                        PackageParser.Package pkg = mPackages.get(packageName);
961                        if (pkg == null) {
962                            continue;
963                        }
964                        long timeInMillis;
965                        try {
966                            timeInMillis = Long.parseLong(timeInMillisString.toString());
967                        } catch (NumberFormatException e) {
968                            throw new IOException("Failed to parse " + timeInMillisString
969                                                  + " as a long.", e);
970                        }
971                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
972                    }
973                } catch (FileNotFoundException expected) {
974                    mIsHistoricalPackageUsageAvailable = false;
975                } catch (IOException e) {
976                    Log.w(TAG, "Failed to read package usage times", e);
977                } finally {
978                    IoUtils.closeQuietly(in);
979                }
980            }
981            mLastWritten.set(SystemClock.elapsedRealtime());
982        }
983
984        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
985                throws IOException {
986            sb.setLength(0);
987            while (true) {
988                int ch = in.read();
989                if (ch == -1) {
990                    if (sb.length() == 0) {
991                        return null;
992                    }
993                    throw new IOException("Unexpected EOF");
994                }
995                if (ch == endOfToken) {
996                    return sb.toString();
997                }
998                sb.append((char)ch);
999            }
1000        }
1001
1002        private AtomicFile getFile() {
1003            File dataDir = Environment.getDataDirectory();
1004            File systemDir = new File(dataDir, "system");
1005            File fname = new File(systemDir, "package-usage.list");
1006            return new AtomicFile(fname);
1007        }
1008    }
1009
1010    class PackageHandler extends Handler {
1011        private boolean mBound = false;
1012        final ArrayList<HandlerParams> mPendingInstalls =
1013            new ArrayList<HandlerParams>();
1014
1015        private boolean connectToService() {
1016            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
1017                    " DefaultContainerService");
1018            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
1019            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1020            if (mContext.bindServiceAsUser(service, mDefContainerConn,
1021                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
1022                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1023                mBound = true;
1024                return true;
1025            }
1026            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1027            return false;
1028        }
1029
1030        private void disconnectService() {
1031            mContainerService = null;
1032            mBound = false;
1033            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1034            mContext.unbindService(mDefContainerConn);
1035            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1036        }
1037
1038        PackageHandler(Looper looper) {
1039            super(looper);
1040        }
1041
1042        public void handleMessage(Message msg) {
1043            try {
1044                doHandleMessage(msg);
1045            } finally {
1046                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1047            }
1048        }
1049
1050        void doHandleMessage(Message msg) {
1051            switch (msg.what) {
1052                case INIT_COPY: {
1053                    HandlerParams params = (HandlerParams) msg.obj;
1054                    int idx = mPendingInstalls.size();
1055                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
1056                    // If a bind was already initiated we dont really
1057                    // need to do anything. The pending install
1058                    // will be processed later on.
1059                    if (!mBound) {
1060                        // If this is the only one pending we might
1061                        // have to bind to the service again.
1062                        if (!connectToService()) {
1063                            Slog.e(TAG, "Failed to bind to media container service");
1064                            params.serviceError();
1065                            return;
1066                        } else {
1067                            // Once we bind to the service, the first
1068                            // pending request will be processed.
1069                            mPendingInstalls.add(idx, params);
1070                        }
1071                    } else {
1072                        mPendingInstalls.add(idx, params);
1073                        // Already bound to the service. Just make
1074                        // sure we trigger off processing the first request.
1075                        if (idx == 0) {
1076                            mHandler.sendEmptyMessage(MCS_BOUND);
1077                        }
1078                    }
1079                    break;
1080                }
1081                case MCS_BOUND: {
1082                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
1083                    if (msg.obj != null) {
1084                        mContainerService = (IMediaContainerService) msg.obj;
1085                    }
1086                    if (mContainerService == null) {
1087                        // Something seriously wrong. Bail out
1088                        Slog.e(TAG, "Cannot bind to media container service");
1089                        for (HandlerParams params : mPendingInstalls) {
1090                            // Indicate service bind error
1091                            params.serviceError();
1092                        }
1093                        mPendingInstalls.clear();
1094                    } else if (mPendingInstalls.size() > 0) {
1095                        HandlerParams params = mPendingInstalls.get(0);
1096                        if (params != null) {
1097                            if (params.startCopy()) {
1098                                // We are done...  look for more work or to
1099                                // go idle.
1100                                if (DEBUG_SD_INSTALL) Log.i(TAG,
1101                                        "Checking for more work or unbind...");
1102                                // Delete pending install
1103                                if (mPendingInstalls.size() > 0) {
1104                                    mPendingInstalls.remove(0);
1105                                }
1106                                if (mPendingInstalls.size() == 0) {
1107                                    if (mBound) {
1108                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
1109                                                "Posting delayed MCS_UNBIND");
1110                                        removeMessages(MCS_UNBIND);
1111                                        Message ubmsg = obtainMessage(MCS_UNBIND);
1112                                        // Unbind after a little delay, to avoid
1113                                        // continual thrashing.
1114                                        sendMessageDelayed(ubmsg, 10000);
1115                                    }
1116                                } else {
1117                                    // There are more pending requests in queue.
1118                                    // Just post MCS_BOUND message to trigger processing
1119                                    // of next pending install.
1120                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
1121                                            "Posting MCS_BOUND for next work");
1122                                    mHandler.sendEmptyMessage(MCS_BOUND);
1123                                }
1124                            }
1125                        }
1126                    } else {
1127                        // Should never happen ideally.
1128                        Slog.w(TAG, "Empty queue");
1129                    }
1130                    break;
1131                }
1132                case MCS_RECONNECT: {
1133                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
1134                    if (mPendingInstalls.size() > 0) {
1135                        if (mBound) {
1136                            disconnectService();
1137                        }
1138                        if (!connectToService()) {
1139                            Slog.e(TAG, "Failed to bind to media container service");
1140                            for (HandlerParams params : mPendingInstalls) {
1141                                // Indicate service bind error
1142                                params.serviceError();
1143                            }
1144                            mPendingInstalls.clear();
1145                        }
1146                    }
1147                    break;
1148                }
1149                case MCS_UNBIND: {
1150                    // If there is no actual work left, then time to unbind.
1151                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
1152
1153                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
1154                        if (mBound) {
1155                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
1156
1157                            disconnectService();
1158                        }
1159                    } else if (mPendingInstalls.size() > 0) {
1160                        // There are more pending requests in queue.
1161                        // Just post MCS_BOUND message to trigger processing
1162                        // of next pending install.
1163                        mHandler.sendEmptyMessage(MCS_BOUND);
1164                    }
1165
1166                    break;
1167                }
1168                case MCS_GIVE_UP: {
1169                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
1170                    mPendingInstalls.remove(0);
1171                    break;
1172                }
1173                case SEND_PENDING_BROADCAST: {
1174                    String packages[];
1175                    ArrayList<String> components[];
1176                    int size = 0;
1177                    int uids[];
1178                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1179                    synchronized (mPackages) {
1180                        if (mPendingBroadcasts == null) {
1181                            return;
1182                        }
1183                        size = mPendingBroadcasts.size();
1184                        if (size <= 0) {
1185                            // Nothing to be done. Just return
1186                            return;
1187                        }
1188                        packages = new String[size];
1189                        components = new ArrayList[size];
1190                        uids = new int[size];
1191                        int i = 0;  // filling out the above arrays
1192
1193                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
1194                            int packageUserId = mPendingBroadcasts.userIdAt(n);
1195                            Iterator<Map.Entry<String, ArrayList<String>>> it
1196                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
1197                                            .entrySet().iterator();
1198                            while (it.hasNext() && i < size) {
1199                                Map.Entry<String, ArrayList<String>> ent = it.next();
1200                                packages[i] = ent.getKey();
1201                                components[i] = ent.getValue();
1202                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
1203                                uids[i] = (ps != null)
1204                                        ? UserHandle.getUid(packageUserId, ps.appId)
1205                                        : -1;
1206                                i++;
1207                            }
1208                        }
1209                        size = i;
1210                        mPendingBroadcasts.clear();
1211                    }
1212                    // Send broadcasts
1213                    for (int i = 0; i < size; i++) {
1214                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
1215                    }
1216                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1217                    break;
1218                }
1219                case START_CLEANING_PACKAGE: {
1220                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1221                    final String packageName = (String)msg.obj;
1222                    final int userId = msg.arg1;
1223                    final boolean andCode = msg.arg2 != 0;
1224                    synchronized (mPackages) {
1225                        if (userId == UserHandle.USER_ALL) {
1226                            int[] users = sUserManager.getUserIds();
1227                            for (int user : users) {
1228                                mSettings.addPackageToCleanLPw(
1229                                        new PackageCleanItem(user, packageName, andCode));
1230                            }
1231                        } else {
1232                            mSettings.addPackageToCleanLPw(
1233                                    new PackageCleanItem(userId, packageName, andCode));
1234                        }
1235                    }
1236                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1237                    startCleaningPackages();
1238                } break;
1239                case POST_INSTALL: {
1240                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1241                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1242                    mRunningInstalls.delete(msg.arg1);
1243                    boolean deleteOld = false;
1244
1245                    if (data != null) {
1246                        InstallArgs args = data.args;
1247                        PackageInstalledInfo res = data.res;
1248
1249                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1250                            res.removedInfo.sendBroadcast(false, true, false);
1251                            Bundle extras = new Bundle(1);
1252                            extras.putInt(Intent.EXTRA_UID, res.uid);
1253
1254                            // Now that we successfully installed the package, grant runtime
1255                            // permissions if requested before broadcasting the install.
1256                            if ((args.installFlags
1257                                    & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0) {
1258                                grantRequestedRuntimePermissions(res.pkg,
1259                                        args.user.getIdentifier());
1260                            }
1261
1262                            // Determine the set of users who are adding this
1263                            // package for the first time vs. those who are seeing
1264                            // an update.
1265                            int[] firstUsers;
1266                            int[] updateUsers = new int[0];
1267                            if (res.origUsers == null || res.origUsers.length == 0) {
1268                                firstUsers = res.newUsers;
1269                            } else {
1270                                firstUsers = new int[0];
1271                                for (int i=0; i<res.newUsers.length; i++) {
1272                                    int user = res.newUsers[i];
1273                                    boolean isNew = true;
1274                                    for (int j=0; j<res.origUsers.length; j++) {
1275                                        if (res.origUsers[j] == user) {
1276                                            isNew = false;
1277                                            break;
1278                                        }
1279                                    }
1280                                    if (isNew) {
1281                                        int[] newFirst = new int[firstUsers.length+1];
1282                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1283                                                firstUsers.length);
1284                                        newFirst[firstUsers.length] = user;
1285                                        firstUsers = newFirst;
1286                                    } else {
1287                                        int[] newUpdate = new int[updateUsers.length+1];
1288                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1289                                                updateUsers.length);
1290                                        newUpdate[updateUsers.length] = user;
1291                                        updateUsers = newUpdate;
1292                                    }
1293                                }
1294                            }
1295                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1296                                    res.pkg.applicationInfo.packageName,
1297                                    extras, null, null, firstUsers);
1298                            final boolean update = res.removedInfo.removedPackage != null;
1299                            if (update) {
1300                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1301                            }
1302                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1303                                    res.pkg.applicationInfo.packageName,
1304                                    extras, null, null, updateUsers);
1305                            if (update) {
1306                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1307                                        res.pkg.applicationInfo.packageName,
1308                                        extras, null, null, updateUsers);
1309                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1310                                        null, null,
1311                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1312
1313                                // treat asec-hosted packages like removable media on upgrade
1314                                if (res.pkg.isForwardLocked() || isExternal(res.pkg)) {
1315                                    if (DEBUG_INSTALL) {
1316                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1317                                                + " is ASEC-hosted -> AVAILABLE");
1318                                    }
1319                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1320                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1321                                    pkgList.add(res.pkg.applicationInfo.packageName);
1322                                    sendResourcesChangedBroadcast(true, true,
1323                                            pkgList,uidArray, null);
1324                                }
1325                            }
1326                            if (res.removedInfo.args != null) {
1327                                // Remove the replaced package's older resources safely now
1328                                deleteOld = true;
1329                            }
1330
1331                            // Log current value of "unknown sources" setting
1332                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1333                                getUnknownSourcesSettings());
1334                        }
1335                        // Force a gc to clear up things
1336                        Runtime.getRuntime().gc();
1337                        // We delete after a gc for applications  on sdcard.
1338                        if (deleteOld) {
1339                            synchronized (mInstallLock) {
1340                                res.removedInfo.args.doPostDeleteLI(true);
1341                            }
1342                        }
1343                        if (args.observer != null) {
1344                            try {
1345                                Bundle extras = extrasForInstallResult(res);
1346                                args.observer.onPackageInstalled(res.name, res.returnCode,
1347                                        res.returnMsg, extras);
1348                            } catch (RemoteException e) {
1349                                Slog.i(TAG, "Observer no longer exists.");
1350                            }
1351                        }
1352                    } else {
1353                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1354                    }
1355                } break;
1356                case UPDATED_MEDIA_STATUS: {
1357                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1358                    boolean reportStatus = msg.arg1 == 1;
1359                    boolean doGc = msg.arg2 == 1;
1360                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1361                    if (doGc) {
1362                        // Force a gc to clear up stale containers.
1363                        Runtime.getRuntime().gc();
1364                    }
1365                    if (msg.obj != null) {
1366                        @SuppressWarnings("unchecked")
1367                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1368                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1369                        // Unload containers
1370                        unloadAllContainers(args);
1371                    }
1372                    if (reportStatus) {
1373                        try {
1374                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1375                            PackageHelper.getMountService().finishMediaUpdate();
1376                        } catch (RemoteException e) {
1377                            Log.e(TAG, "MountService not running?");
1378                        }
1379                    }
1380                } break;
1381                case WRITE_SETTINGS: {
1382                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1383                    synchronized (mPackages) {
1384                        removeMessages(WRITE_SETTINGS);
1385                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1386                        mSettings.writeLPr();
1387                        mDirtyUsers.clear();
1388                    }
1389                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1390                } break;
1391                case WRITE_PACKAGE_RESTRICTIONS: {
1392                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1393                    synchronized (mPackages) {
1394                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1395                        for (int userId : mDirtyUsers) {
1396                            mSettings.writePackageRestrictionsLPr(userId);
1397                        }
1398                        mDirtyUsers.clear();
1399                    }
1400                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1401                } break;
1402                case CHECK_PENDING_VERIFICATION: {
1403                    final int verificationId = msg.arg1;
1404                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1405
1406                    if ((state != null) && !state.timeoutExtended()) {
1407                        final InstallArgs args = state.getInstallArgs();
1408                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1409
1410                        Slog.i(TAG, "Verification timed out for " + originUri);
1411                        mPendingVerification.remove(verificationId);
1412
1413                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1414
1415                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1416                            Slog.i(TAG, "Continuing with installation of " + originUri);
1417                            state.setVerifierResponse(Binder.getCallingUid(),
1418                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1419                            broadcastPackageVerified(verificationId, originUri,
1420                                    PackageManager.VERIFICATION_ALLOW,
1421                                    state.getInstallArgs().getUser());
1422                            try {
1423                                ret = args.copyApk(mContainerService, true);
1424                            } catch (RemoteException e) {
1425                                Slog.e(TAG, "Could not contact the ContainerService");
1426                            }
1427                        } else {
1428                            broadcastPackageVerified(verificationId, originUri,
1429                                    PackageManager.VERIFICATION_REJECT,
1430                                    state.getInstallArgs().getUser());
1431                        }
1432
1433                        processPendingInstall(args, ret);
1434                        mHandler.sendEmptyMessage(MCS_UNBIND);
1435                    }
1436                    break;
1437                }
1438                case PACKAGE_VERIFIED: {
1439                    final int verificationId = msg.arg1;
1440
1441                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1442                    if (state == null) {
1443                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1444                        break;
1445                    }
1446
1447                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1448
1449                    state.setVerifierResponse(response.callerUid, response.code);
1450
1451                    if (state.isVerificationComplete()) {
1452                        mPendingVerification.remove(verificationId);
1453
1454                        final InstallArgs args = state.getInstallArgs();
1455                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1456
1457                        int ret;
1458                        if (state.isInstallAllowed()) {
1459                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1460                            broadcastPackageVerified(verificationId, originUri,
1461                                    response.code, state.getInstallArgs().getUser());
1462                            try {
1463                                ret = args.copyApk(mContainerService, true);
1464                            } catch (RemoteException e) {
1465                                Slog.e(TAG, "Could not contact the ContainerService");
1466                            }
1467                        } else {
1468                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1469                        }
1470
1471                        processPendingInstall(args, ret);
1472
1473                        mHandler.sendEmptyMessage(MCS_UNBIND);
1474                    }
1475
1476                    break;
1477                }
1478                case START_INTENT_FILTER_VERIFICATIONS: {
1479                    int userId = msg.arg1;
1480                    int verifierUid = msg.arg2;
1481                    PackageParser.Package pkg = (PackageParser.Package)msg.obj;
1482
1483                    verifyIntentFiltersIfNeeded(userId, verifierUid, pkg);
1484                    break;
1485                }
1486                case INTENT_FILTER_VERIFIED: {
1487                    final int verificationId = msg.arg1;
1488
1489                    final IntentFilterVerificationState state = mIntentFilterVerificationStates.get(
1490                            verificationId);
1491                    if (state == null) {
1492                        Slog.w(TAG, "Invalid IntentFilter verification token "
1493                                + verificationId + " received");
1494                        break;
1495                    }
1496
1497                    final int userId = state.getUserId();
1498
1499                    Slog.d(TAG, "Processing IntentFilter verification with token:"
1500                            + verificationId + " and userId:" + userId);
1501
1502                    final IntentFilterVerificationResponse response =
1503                            (IntentFilterVerificationResponse) msg.obj;
1504
1505                    state.setVerifierResponse(response.callerUid, response.code);
1506
1507                    Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1508                            + " and userId:" + userId
1509                            + " is settings verifier response with response code:"
1510                            + response.code);
1511
1512                    if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) {
1513                        Slog.d(TAG, "Domains failing verification: "
1514                                + response.getFailedDomainsString());
1515                    }
1516
1517                    if (state.isVerificationComplete()) {
1518                        mIntentFilterVerifier.receiveVerificationResponse(verificationId);
1519                    } else {
1520                        Slog.d(TAG, "IntentFilter verification with token:" + verificationId
1521                                + " was not said to be complete");
1522                    }
1523
1524                    break;
1525                }
1526            }
1527        }
1528    }
1529
1530    private StorageEventListener mStorageListener = new StorageEventListener() {
1531        @Override
1532        public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
1533            Slog.v(TAG, vol.toString());
1534
1535            // TODO: when private volume shows up, look for packages there too
1536            if (vol.isPrimary() && vol.type == VolumeInfo.TYPE_PUBLIC) {
1537                if (vol.state == VolumeInfo.STATE_MOUNTED) {
1538                    updateExternalMediaStatus(true, false);
1539                } else if (vol.state == VolumeInfo.STATE_UNMOUNTING) {
1540                    updateExternalMediaStatus(false, false);
1541                }
1542            }
1543        }
1544    };
1545
1546    private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int userId) {
1547        if (userId >= UserHandle.USER_OWNER) {
1548            grantRequestedRuntimePermissionsForUser(pkg, userId);
1549        } else if (userId == UserHandle.USER_ALL) {
1550            for (int someUserId : UserManagerService.getInstance().getUserIds()) {
1551                grantRequestedRuntimePermissionsForUser(pkg, someUserId);
1552            }
1553        }
1554    }
1555
1556    private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId) {
1557        SettingBase sb = (SettingBase) pkg.mExtras;
1558        if (sb == null) {
1559            return;
1560        }
1561
1562        PermissionsState permissionsState = sb.getPermissionsState();
1563
1564        for (String permission : pkg.requestedPermissions) {
1565            BasePermission bp = mSettings.mPermissions.get(permission);
1566            if (bp != null && bp.isRuntime()) {
1567                permissionsState.grantRuntimePermission(bp, userId);
1568            }
1569        }
1570    }
1571
1572    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1573        Bundle extras = null;
1574        switch (res.returnCode) {
1575            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1576                extras = new Bundle();
1577                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1578                        res.origPermission);
1579                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1580                        res.origPackage);
1581                break;
1582            }
1583        }
1584        return extras;
1585    }
1586
1587    void scheduleWriteSettingsLocked() {
1588        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1589            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1590        }
1591    }
1592
1593    void scheduleWritePackageRestrictionsLocked(int userId) {
1594        if (!sUserManager.exists(userId)) return;
1595        mDirtyUsers.add(userId);
1596        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1597            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1598        }
1599    }
1600
1601    public static PackageManagerService main(Context context, Installer installer,
1602            boolean factoryTest, boolean onlyCore) {
1603        PackageManagerService m = new PackageManagerService(context, installer,
1604                factoryTest, onlyCore);
1605        ServiceManager.addService("package", m);
1606        return m;
1607    }
1608
1609    static String[] splitString(String str, char sep) {
1610        int count = 1;
1611        int i = 0;
1612        while ((i=str.indexOf(sep, i)) >= 0) {
1613            count++;
1614            i++;
1615        }
1616
1617        String[] res = new String[count];
1618        i=0;
1619        count = 0;
1620        int lastI=0;
1621        while ((i=str.indexOf(sep, i)) >= 0) {
1622            res[count] = str.substring(lastI, i);
1623            count++;
1624            i++;
1625            lastI = i;
1626        }
1627        res[count] = str.substring(lastI, str.length());
1628        return res;
1629    }
1630
1631    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1632        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1633                Context.DISPLAY_SERVICE);
1634        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1635    }
1636
1637    public PackageManagerService(Context context, Installer installer,
1638            boolean factoryTest, boolean onlyCore) {
1639        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1640                SystemClock.uptimeMillis());
1641
1642        if (mSdkVersion <= 0) {
1643            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1644        }
1645
1646        mContext = context;
1647        mFactoryTest = factoryTest;
1648        mOnlyCore = onlyCore;
1649        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1650        mMetrics = new DisplayMetrics();
1651        mSettings = new Settings(mPackages);
1652        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1653                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1654        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1655                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1656        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1657                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1658        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1659                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1660        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1661                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1662        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1663                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1664
1665        // TODO: add a property to control this?
1666        long dexOptLRUThresholdInMinutes;
1667        if (mLazyDexOpt) {
1668            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1669        } else {
1670            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1671        }
1672        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1673
1674        String separateProcesses = SystemProperties.get("debug.separate_processes");
1675        if (separateProcesses != null && separateProcesses.length() > 0) {
1676            if ("*".equals(separateProcesses)) {
1677                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1678                mSeparateProcesses = null;
1679                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1680            } else {
1681                mDefParseFlags = 0;
1682                mSeparateProcesses = separateProcesses.split(",");
1683                Slog.w(TAG, "Running with debug.separate_processes: "
1684                        + separateProcesses);
1685            }
1686        } else {
1687            mDefParseFlags = 0;
1688            mSeparateProcesses = null;
1689        }
1690
1691        mInstaller = installer;
1692        mPackageDexOptimizer = new PackageDexOptimizer(this);
1693
1694        getDefaultDisplayMetrics(context, mMetrics);
1695
1696        SystemConfig systemConfig = SystemConfig.getInstance();
1697        mGlobalGids = systemConfig.getGlobalGids();
1698        mSystemPermissions = systemConfig.getSystemPermissions();
1699        mAvailableFeatures = systemConfig.getAvailableFeatures();
1700
1701        synchronized (mInstallLock) {
1702        // writer
1703        synchronized (mPackages) {
1704            mHandlerThread = new ServiceThread(TAG,
1705                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1706            mHandlerThread.start();
1707            mHandler = new PackageHandler(mHandlerThread.getLooper());
1708            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1709
1710            File dataDir = Environment.getDataDirectory();
1711            mAppDataDir = new File(dataDir, "data");
1712            mAppInstallDir = new File(dataDir, "app");
1713            mAppLib32InstallDir = new File(dataDir, "app-lib");
1714            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1715            mUserAppDataDir = new File(dataDir, "user");
1716            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1717
1718            sUserManager = new UserManagerService(context, this,
1719                    mInstallLock, mPackages);
1720
1721            // Propagate permission configuration in to package manager.
1722            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1723                    = systemConfig.getPermissions();
1724            for (int i=0; i<permConfig.size(); i++) {
1725                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1726                BasePermission bp = mSettings.mPermissions.get(perm.name);
1727                if (bp == null) {
1728                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1729                    mSettings.mPermissions.put(perm.name, bp);
1730                }
1731                if (perm.gids != null) {
1732                    bp.setGids(perm.gids, perm.perUser);
1733                }
1734            }
1735
1736            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1737            for (int i=0; i<libConfig.size(); i++) {
1738                mSharedLibraries.put(libConfig.keyAt(i),
1739                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1740            }
1741
1742            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1743
1744            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1745                    mSdkVersion, mOnlyCore);
1746
1747            String customResolverActivity = Resources.getSystem().getString(
1748                    R.string.config_customResolverActivity);
1749            if (TextUtils.isEmpty(customResolverActivity)) {
1750                customResolverActivity = null;
1751            } else {
1752                mCustomResolverComponentName = ComponentName.unflattenFromString(
1753                        customResolverActivity);
1754            }
1755
1756            long startTime = SystemClock.uptimeMillis();
1757
1758            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1759                    startTime);
1760
1761            // Set flag to monitor and not change apk file paths when
1762            // scanning install directories.
1763            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1764
1765            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1766
1767            /**
1768             * Add everything in the in the boot class path to the
1769             * list of process files because dexopt will have been run
1770             * if necessary during zygote startup.
1771             */
1772            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1773            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1774
1775            if (bootClassPath != null) {
1776                String[] bootClassPathElements = splitString(bootClassPath, ':');
1777                for (String element : bootClassPathElements) {
1778                    alreadyDexOpted.add(element);
1779                }
1780            } else {
1781                Slog.w(TAG, "No BOOTCLASSPATH found!");
1782            }
1783
1784            if (systemServerClassPath != null) {
1785                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1786                for (String element : systemServerClassPathElements) {
1787                    alreadyDexOpted.add(element);
1788                }
1789            } else {
1790                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1791            }
1792
1793            final List<String> allInstructionSets = InstructionSets.getAllInstructionSets();
1794            final String[] dexCodeInstructionSets =
1795                    getDexCodeInstructionSets(
1796                            allInstructionSets.toArray(new String[allInstructionSets.size()]));
1797
1798            /**
1799             * Ensure all external libraries have had dexopt run on them.
1800             */
1801            if (mSharedLibraries.size() > 0) {
1802                // NOTE: For now, we're compiling these system "shared libraries"
1803                // (and framework jars) into all available architectures. It's possible
1804                // to compile them only when we come across an app that uses them (there's
1805                // already logic for that in scanPackageLI) but that adds some complexity.
1806                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1807                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1808                        final String lib = libEntry.path;
1809                        if (lib == null) {
1810                            continue;
1811                        }
1812
1813                        try {
1814                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1815                                                                                 dexCodeInstructionSet,
1816                                                                                 false);
1817                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1818                                alreadyDexOpted.add(lib);
1819
1820                                // The list of "shared libraries" we have at this point is
1821                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1822                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1823                                } else {
1824                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1825                                }
1826                            }
1827                        } catch (FileNotFoundException e) {
1828                            Slog.w(TAG, "Library not found: " + lib);
1829                        } catch (IOException e) {
1830                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1831                                    + e.getMessage());
1832                        }
1833                    }
1834                }
1835            }
1836
1837            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1838
1839            // Gross hack for now: we know this file doesn't contain any
1840            // code, so don't dexopt it to avoid the resulting log spew.
1841            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1842
1843            // Gross hack for now: we know this file is only part of
1844            // the boot class path for art, so don't dexopt it to
1845            // avoid the resulting log spew.
1846            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1847
1848            /**
1849             * And there are a number of commands implemented in Java, which
1850             * we currently need to do the dexopt on so that they can be
1851             * run from a non-root shell.
1852             */
1853            String[] frameworkFiles = frameworkDir.list();
1854            if (frameworkFiles != null) {
1855                // TODO: We could compile these only for the most preferred ABI. We should
1856                // first double check that the dex files for these commands are not referenced
1857                // by other system apps.
1858                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1859                    for (int i=0; i<frameworkFiles.length; i++) {
1860                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1861                        String path = libPath.getPath();
1862                        // Skip the file if we already did it.
1863                        if (alreadyDexOpted.contains(path)) {
1864                            continue;
1865                        }
1866                        // Skip the file if it is not a type we want to dexopt.
1867                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1868                            continue;
1869                        }
1870                        try {
1871                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1872                                                                                 dexCodeInstructionSet,
1873                                                                                 false);
1874                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1875                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1876                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1877                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1878                            }
1879                        } catch (FileNotFoundException e) {
1880                            Slog.w(TAG, "Jar not found: " + path);
1881                        } catch (IOException e) {
1882                            Slog.w(TAG, "Exception reading jar: " + path, e);
1883                        }
1884                    }
1885                }
1886            }
1887
1888            // Collect vendor overlay packages.
1889            // (Do this before scanning any apps.)
1890            // For security and version matching reason, only consider
1891            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1892            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1893            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1894                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1895
1896            // Find base frameworks (resource packages without code).
1897            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1898                    | PackageParser.PARSE_IS_SYSTEM_DIR
1899                    | PackageParser.PARSE_IS_PRIVILEGED,
1900                    scanFlags | SCAN_NO_DEX, 0);
1901
1902            // Collected privileged system packages.
1903            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1904            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1905                    | PackageParser.PARSE_IS_SYSTEM_DIR
1906                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1907
1908            // Collect ordinary system packages.
1909            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1910            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1911                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1912
1913            // Collect all vendor packages.
1914            File vendorAppDir = new File("/vendor/app");
1915            try {
1916                vendorAppDir = vendorAppDir.getCanonicalFile();
1917            } catch (IOException e) {
1918                // failed to look up canonical path, continue with original one
1919            }
1920            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1921                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1922
1923            // Collect all OEM packages.
1924            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1925            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1926                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1927
1928            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1929            mInstaller.moveFiles();
1930
1931            // Prune any system packages that no longer exist.
1932            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1933            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1934            if (!mOnlyCore) {
1935                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1936                while (psit.hasNext()) {
1937                    PackageSetting ps = psit.next();
1938
1939                    /*
1940                     * If this is not a system app, it can't be a
1941                     * disable system app.
1942                     */
1943                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1944                        continue;
1945                    }
1946
1947                    /*
1948                     * If the package is scanned, it's not erased.
1949                     */
1950                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1951                    if (scannedPkg != null) {
1952                        /*
1953                         * If the system app is both scanned and in the
1954                         * disabled packages list, then it must have been
1955                         * added via OTA. Remove it from the currently
1956                         * scanned package so the previously user-installed
1957                         * application can be scanned.
1958                         */
1959                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1960                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1961                                    + ps.name + "; removing system app.  Last known codePath="
1962                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1963                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1964                                    + scannedPkg.mVersionCode);
1965                            removePackageLI(ps, true);
1966                            expectingBetter.put(ps.name, ps.codePath);
1967                        }
1968
1969                        continue;
1970                    }
1971
1972                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1973                        psit.remove();
1974                        logCriticalInfo(Log.WARN, "System package " + ps.name
1975                                + " no longer exists; wiping its data");
1976                        removeDataDirsLI(ps.name);
1977                    } else {
1978                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1979                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1980                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1981                        }
1982                    }
1983                }
1984            }
1985
1986            //look for any incomplete package installations
1987            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1988            //clean up list
1989            for(int i = 0; i < deletePkgsList.size(); i++) {
1990                //clean up here
1991                cleanupInstallFailedPackage(deletePkgsList.get(i));
1992            }
1993            //delete tmp files
1994            deleteTempPackageFiles();
1995
1996            // Remove any shared userIDs that have no associated packages
1997            mSettings.pruneSharedUsersLPw();
1998
1999            if (!mOnlyCore) {
2000                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
2001                        SystemClock.uptimeMillis());
2002                scanDirLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0);
2003
2004                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
2005                        scanFlags | SCAN_REQUIRE_KNOWN, 0);
2006
2007                /**
2008                 * Remove disable package settings for any updated system
2009                 * apps that were removed via an OTA. If they're not a
2010                 * previously-updated app, remove them completely.
2011                 * Otherwise, just revoke their system-level permissions.
2012                 */
2013                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
2014                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
2015                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
2016
2017                    String msg;
2018                    if (deletedPkg == null) {
2019                        msg = "Updated system package " + deletedAppName
2020                                + " no longer exists; wiping its data";
2021                        removeDataDirsLI(deletedAppName);
2022                    } else {
2023                        msg = "Updated system app + " + deletedAppName
2024                                + " no longer present; removing system privileges for "
2025                                + deletedAppName;
2026
2027                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
2028
2029                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
2030                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
2031                    }
2032                    logCriticalInfo(Log.WARN, msg);
2033                }
2034
2035                /**
2036                 * Make sure all system apps that we expected to appear on
2037                 * the userdata partition actually showed up. If they never
2038                 * appeared, crawl back and revive the system version.
2039                 */
2040                for (int i = 0; i < expectingBetter.size(); i++) {
2041                    final String packageName = expectingBetter.keyAt(i);
2042                    if (!mPackages.containsKey(packageName)) {
2043                        final File scanFile = expectingBetter.valueAt(i);
2044
2045                        logCriticalInfo(Log.WARN, "Expected better " + packageName
2046                                + " but never showed up; reverting to system");
2047
2048                        final int reparseFlags;
2049                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
2050                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2051                                    | PackageParser.PARSE_IS_SYSTEM_DIR
2052                                    | PackageParser.PARSE_IS_PRIVILEGED;
2053                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
2054                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2055                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2056                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
2057                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2058                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2059                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
2060                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
2061                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
2062                        } else {
2063                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
2064                            continue;
2065                        }
2066
2067                        mSettings.enableSystemPackageLPw(packageName);
2068
2069                        try {
2070                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
2071                        } catch (PackageManagerException e) {
2072                            Slog.e(TAG, "Failed to parse original system package: "
2073                                    + e.getMessage());
2074                        }
2075                    }
2076                }
2077            }
2078
2079            // Now that we know all of the shared libraries, update all clients to have
2080            // the correct library paths.
2081            updateAllSharedLibrariesLPw();
2082
2083            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
2084                // NOTE: We ignore potential failures here during a system scan (like
2085                // the rest of the commands above) because there's precious little we
2086                // can do about it. A settings error is reported, though.
2087                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
2088                        false /* force dexopt */, false /* defer dexopt */);
2089            }
2090
2091            // Now that we know all the packages we are keeping,
2092            // read and update their last usage times.
2093            mPackageUsage.readLP();
2094
2095            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
2096                    SystemClock.uptimeMillis());
2097            Slog.i(TAG, "Time to scan packages: "
2098                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
2099                    + " seconds");
2100
2101            // If the platform SDK has changed since the last time we booted,
2102            // we need to re-grant app permission to catch any new ones that
2103            // appear.  This is really a hack, and means that apps can in some
2104            // cases get permissions that the user didn't initially explicitly
2105            // allow...  it would be nice to have some better way to handle
2106            // this situation.
2107            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
2108                    != mSdkVersion;
2109            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
2110                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
2111                    + "; regranting permissions for internal storage");
2112            mSettings.mInternalSdkPlatform = mSdkVersion;
2113
2114            // For now runtime permissions are toggled via a system property.
2115            if (!RUNTIME_PERMISSIONS_ENABLED) {
2116                // Remove the runtime permissions state if the feature
2117                // was disabled by flipping the system property.
2118                mSettings.deleteRuntimePermissionsFiles();
2119            }
2120
2121            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
2122                    | (regrantPermissions
2123                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
2124                            : 0));
2125
2126            // If this is the first boot, and it is a normal boot, then
2127            // we need to initialize the default preferred apps.
2128            if (!mRestoredSettings && !onlyCore) {
2129                mSettings.readDefaultPreferredAppsLPw(this, 0);
2130            }
2131
2132            // If this is first boot after an OTA, and a normal boot, then
2133            // we need to clear code cache directories.
2134            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
2135            if (mIsUpgrade && !onlyCore) {
2136                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
2137                for (String pkgName : mSettings.mPackages.keySet()) {
2138                    deleteCodeCacheDirsLI(pkgName);
2139                }
2140                mSettings.mFingerprint = Build.FINGERPRINT;
2141            }
2142
2143            // All the changes are done during package scanning.
2144            mSettings.updateInternalDatabaseVersion();
2145
2146            // can downgrade to reader
2147            mSettings.writeLPr();
2148
2149            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
2150                    SystemClock.uptimeMillis());
2151
2152            mRequiredVerifierPackage = getRequiredVerifierLPr();
2153
2154            mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
2155
2156            mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr();
2157            mIntentFilterVerifier = new IntentVerifierProxy(mContext,
2158                    mIntentFilterVerifierComponent);
2159
2160        } // synchronized (mPackages)
2161        } // synchronized (mInstallLock)
2162
2163        // Now after opening every single application zip, make sure they
2164        // are all flushed.  Not really needed, but keeps things nice and
2165        // tidy.
2166        Runtime.getRuntime().gc();
2167    }
2168
2169    @Override
2170    public boolean isFirstBoot() {
2171        return !mRestoredSettings;
2172    }
2173
2174    @Override
2175    public boolean isOnlyCoreApps() {
2176        return mOnlyCore;
2177    }
2178
2179    @Override
2180    public boolean isUpgrade() {
2181        return mIsUpgrade;
2182    }
2183
2184    private String getRequiredVerifierLPr() {
2185        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
2186        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2187                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
2188
2189        String requiredVerifier = null;
2190
2191        final int N = receivers.size();
2192        for (int i = 0; i < N; i++) {
2193            final ResolveInfo info = receivers.get(i);
2194
2195            if (info.activityInfo == null) {
2196                continue;
2197            }
2198
2199            final String packageName = info.activityInfo.packageName;
2200
2201            if (checkPermission(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
2202                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2203                continue;
2204            }
2205
2206            if (requiredVerifier != null) {
2207                throw new RuntimeException("There can be only one required verifier");
2208            }
2209
2210            requiredVerifier = packageName;
2211        }
2212
2213        return requiredVerifier;
2214    }
2215
2216    private ComponentName getIntentFilterVerifierComponentNameLPr() {
2217        final Intent verification = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION);
2218        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
2219                PackageManager.GET_DISABLED_COMPONENTS, 0 /* userId */);
2220
2221        ComponentName verifierComponentName = null;
2222
2223        int priority = -1000;
2224        final int N = receivers.size();
2225        for (int i = 0; i < N; i++) {
2226            final ResolveInfo info = receivers.get(i);
2227
2228            if (info.activityInfo == null) {
2229                continue;
2230            }
2231
2232            final String packageName = info.activityInfo.packageName;
2233
2234            final PackageSetting ps = mSettings.mPackages.get(packageName);
2235            if (ps == null) {
2236                continue;
2237            }
2238
2239            if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
2240                    packageName, UserHandle.USER_OWNER) != PackageManager.PERMISSION_GRANTED) {
2241                continue;
2242            }
2243
2244            // Select the IntentFilterVerifier with the highest priority
2245            if (priority < info.priority) {
2246                priority = info.priority;
2247                verifierComponentName = new ComponentName(packageName, info.activityInfo.name);
2248                Slog.d(TAG, "Selecting IntentFilterVerifier: " + verifierComponentName +
2249                        " with priority: " + info.priority);
2250            }
2251        }
2252
2253        return verifierComponentName;
2254    }
2255
2256    @Override
2257    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
2258            throws RemoteException {
2259        try {
2260            return super.onTransact(code, data, reply, flags);
2261        } catch (RuntimeException e) {
2262            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
2263                Slog.wtf(TAG, "Package Manager Crash", e);
2264            }
2265            throw e;
2266        }
2267    }
2268
2269    void cleanupInstallFailedPackage(PackageSetting ps) {
2270        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
2271
2272        removeDataDirsLI(ps.name);
2273        if (ps.codePath != null) {
2274            if (ps.codePath.isDirectory()) {
2275                mInstaller.rmPackageDir(ps.codePath.getAbsolutePath());
2276            } else {
2277                ps.codePath.delete();
2278            }
2279        }
2280        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
2281            if (ps.resourcePath.isDirectory()) {
2282                FileUtils.deleteContents(ps.resourcePath);
2283            }
2284            ps.resourcePath.delete();
2285        }
2286        mSettings.removePackageLPw(ps.name);
2287    }
2288
2289    static int[] appendInts(int[] cur, int[] add) {
2290        if (add == null) return cur;
2291        if (cur == null) return add;
2292        final int N = add.length;
2293        for (int i=0; i<N; i++) {
2294            cur = appendInt(cur, add[i]);
2295        }
2296        return cur;
2297    }
2298
2299    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2300        if (!sUserManager.exists(userId)) return null;
2301        final PackageSetting ps = (PackageSetting) p.mExtras;
2302        if (ps == null) {
2303            return null;
2304        }
2305
2306        final PermissionsState permissionsState = ps.getPermissionsState();
2307
2308        final int[] gids = permissionsState.computeGids(userId);
2309        final Set<String> permissions = permissionsState.getPermissions(userId);
2310        final PackageUserState state = ps.readUserState(userId);
2311
2312        return PackageParser.generatePackageInfo(p, gids, flags,
2313                ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId);
2314    }
2315
2316    @Override
2317    public boolean isPackageAvailable(String packageName, int userId) {
2318        if (!sUserManager.exists(userId)) return false;
2319        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
2320        synchronized (mPackages) {
2321            PackageParser.Package p = mPackages.get(packageName);
2322            if (p != null) {
2323                final PackageSetting ps = (PackageSetting) p.mExtras;
2324                if (ps != null) {
2325                    final PackageUserState state = ps.readUserState(userId);
2326                    if (state != null) {
2327                        return PackageParser.isAvailable(state);
2328                    }
2329                }
2330            }
2331        }
2332        return false;
2333    }
2334
2335    @Override
2336    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2337        if (!sUserManager.exists(userId)) return null;
2338        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
2339        // reader
2340        synchronized (mPackages) {
2341            PackageParser.Package p = mPackages.get(packageName);
2342            if (DEBUG_PACKAGE_INFO)
2343                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2344            if (p != null) {
2345                return generatePackageInfo(p, flags, userId);
2346            }
2347            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2348                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2349            }
2350        }
2351        return null;
2352    }
2353
2354    @Override
2355    public String[] currentToCanonicalPackageNames(String[] names) {
2356        String[] out = new String[names.length];
2357        // reader
2358        synchronized (mPackages) {
2359            for (int i=names.length-1; i>=0; i--) {
2360                PackageSetting ps = mSettings.mPackages.get(names[i]);
2361                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2362            }
2363        }
2364        return out;
2365    }
2366
2367    @Override
2368    public String[] canonicalToCurrentPackageNames(String[] names) {
2369        String[] out = new String[names.length];
2370        // reader
2371        synchronized (mPackages) {
2372            for (int i=names.length-1; i>=0; i--) {
2373                String cur = mSettings.mRenamedPackages.get(names[i]);
2374                out[i] = cur != null ? cur : names[i];
2375            }
2376        }
2377        return out;
2378    }
2379
2380    @Override
2381    public int getPackageUid(String packageName, int userId) {
2382        if (!sUserManager.exists(userId)) return -1;
2383        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
2384
2385        // reader
2386        synchronized (mPackages) {
2387            PackageParser.Package p = mPackages.get(packageName);
2388            if(p != null) {
2389                return UserHandle.getUid(userId, p.applicationInfo.uid);
2390            }
2391            PackageSetting ps = mSettings.mPackages.get(packageName);
2392            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2393                return -1;
2394            }
2395            p = ps.pkg;
2396            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2397        }
2398    }
2399
2400    @Override
2401    public int[] getPackageGids(String packageName, int userId) throws RemoteException {
2402        if (!sUserManager.exists(userId)) {
2403            return null;
2404        }
2405
2406        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false,
2407                "getPackageGids");
2408
2409        // reader
2410        synchronized (mPackages) {
2411            PackageParser.Package p = mPackages.get(packageName);
2412            if (DEBUG_PACKAGE_INFO) {
2413                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2414            }
2415            if (p != null) {
2416                PackageSetting ps = (PackageSetting) p.mExtras;
2417                return ps.getPermissionsState().computeGids(userId);
2418            }
2419        }
2420
2421        return null;
2422    }
2423
2424    static PermissionInfo generatePermissionInfo(
2425            BasePermission bp, int flags) {
2426        if (bp.perm != null) {
2427            return PackageParser.generatePermissionInfo(bp.perm, flags);
2428        }
2429        PermissionInfo pi = new PermissionInfo();
2430        pi.name = bp.name;
2431        pi.packageName = bp.sourcePackage;
2432        pi.nonLocalizedLabel = bp.name;
2433        pi.protectionLevel = bp.protectionLevel;
2434        return pi;
2435    }
2436
2437    @Override
2438    public PermissionInfo getPermissionInfo(String name, int flags) {
2439        // reader
2440        synchronized (mPackages) {
2441            final BasePermission p = mSettings.mPermissions.get(name);
2442            if (p != null) {
2443                return generatePermissionInfo(p, flags);
2444            }
2445            return null;
2446        }
2447    }
2448
2449    @Override
2450    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2451        // reader
2452        synchronized (mPackages) {
2453            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2454            for (BasePermission p : mSettings.mPermissions.values()) {
2455                if (group == null) {
2456                    if (p.perm == null || p.perm.info.group == null) {
2457                        out.add(generatePermissionInfo(p, flags));
2458                    }
2459                } else {
2460                    if (p.perm != null && group.equals(p.perm.info.group)) {
2461                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2462                    }
2463                }
2464            }
2465
2466            if (out.size() > 0) {
2467                return out;
2468            }
2469            return mPermissionGroups.containsKey(group) ? out : null;
2470        }
2471    }
2472
2473    @Override
2474    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2475        // reader
2476        synchronized (mPackages) {
2477            return PackageParser.generatePermissionGroupInfo(
2478                    mPermissionGroups.get(name), flags);
2479        }
2480    }
2481
2482    @Override
2483    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2484        // reader
2485        synchronized (mPackages) {
2486            final int N = mPermissionGroups.size();
2487            ArrayList<PermissionGroupInfo> out
2488                    = new ArrayList<PermissionGroupInfo>(N);
2489            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2490                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2491            }
2492            return out;
2493        }
2494    }
2495
2496    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2497            int userId) {
2498        if (!sUserManager.exists(userId)) return null;
2499        PackageSetting ps = mSettings.mPackages.get(packageName);
2500        if (ps != null) {
2501            if (ps.pkg == null) {
2502                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2503                        flags, userId);
2504                if (pInfo != null) {
2505                    return pInfo.applicationInfo;
2506                }
2507                return null;
2508            }
2509            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2510                    ps.readUserState(userId), userId);
2511        }
2512        return null;
2513    }
2514
2515    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2516            int userId) {
2517        if (!sUserManager.exists(userId)) return null;
2518        PackageSetting ps = mSettings.mPackages.get(packageName);
2519        if (ps != null) {
2520            PackageParser.Package pkg = ps.pkg;
2521            if (pkg == null) {
2522                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2523                    return null;
2524                }
2525                // Only data remains, so we aren't worried about code paths
2526                pkg = new PackageParser.Package(packageName);
2527                pkg.applicationInfo.packageName = packageName;
2528                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2529                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2530                pkg.applicationInfo.dataDir =
2531                        getDataPathForPackage(packageName, 0).getPath();
2532                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2533                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2534            }
2535            return generatePackageInfo(pkg, flags, userId);
2536        }
2537        return null;
2538    }
2539
2540    @Override
2541    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2542        if (!sUserManager.exists(userId)) return null;
2543        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2544        // writer
2545        synchronized (mPackages) {
2546            PackageParser.Package p = mPackages.get(packageName);
2547            if (DEBUG_PACKAGE_INFO) Log.v(
2548                    TAG, "getApplicationInfo " + packageName
2549                    + ": " + p);
2550            if (p != null) {
2551                PackageSetting ps = mSettings.mPackages.get(packageName);
2552                if (ps == null) return null;
2553                // Note: isEnabledLP() does not apply here - always return info
2554                return PackageParser.generateApplicationInfo(
2555                        p, flags, ps.readUserState(userId), userId);
2556            }
2557            if ("android".equals(packageName)||"system".equals(packageName)) {
2558                return mAndroidApplication;
2559            }
2560            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2561                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2562            }
2563        }
2564        return null;
2565    }
2566
2567
2568    @Override
2569    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2570        mContext.enforceCallingOrSelfPermission(
2571                android.Manifest.permission.CLEAR_APP_CACHE, null);
2572        // Queue up an async operation since clearing cache may take a little while.
2573        mHandler.post(new Runnable() {
2574            public void run() {
2575                mHandler.removeCallbacks(this);
2576                int retCode = -1;
2577                synchronized (mInstallLock) {
2578                    retCode = mInstaller.freeCache(freeStorageSize);
2579                    if (retCode < 0) {
2580                        Slog.w(TAG, "Couldn't clear application caches");
2581                    }
2582                }
2583                if (observer != null) {
2584                    try {
2585                        observer.onRemoveCompleted(null, (retCode >= 0));
2586                    } catch (RemoteException e) {
2587                        Slog.w(TAG, "RemoveException when invoking call back");
2588                    }
2589                }
2590            }
2591        });
2592    }
2593
2594    @Override
2595    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2596        mContext.enforceCallingOrSelfPermission(
2597                android.Manifest.permission.CLEAR_APP_CACHE, null);
2598        // Queue up an async operation since clearing cache may take a little while.
2599        mHandler.post(new Runnable() {
2600            public void run() {
2601                mHandler.removeCallbacks(this);
2602                int retCode = -1;
2603                synchronized (mInstallLock) {
2604                    retCode = mInstaller.freeCache(freeStorageSize);
2605                    if (retCode < 0) {
2606                        Slog.w(TAG, "Couldn't clear application caches");
2607                    }
2608                }
2609                if(pi != null) {
2610                    try {
2611                        // Callback via pending intent
2612                        int code = (retCode >= 0) ? 1 : 0;
2613                        pi.sendIntent(null, code, null,
2614                                null, null);
2615                    } catch (SendIntentException e1) {
2616                        Slog.i(TAG, "Failed to send pending intent");
2617                    }
2618                }
2619            }
2620        });
2621    }
2622
2623    void freeStorage(long freeStorageSize) throws IOException {
2624        synchronized (mInstallLock) {
2625            if (mInstaller.freeCache(freeStorageSize) < 0) {
2626                throw new IOException("Failed to free enough space");
2627            }
2628        }
2629    }
2630
2631    @Override
2632    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2633        if (!sUserManager.exists(userId)) return null;
2634        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2635        synchronized (mPackages) {
2636            PackageParser.Activity a = mActivities.mActivities.get(component);
2637
2638            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2639            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2640                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2641                if (ps == null) return null;
2642                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2643                        userId);
2644            }
2645            if (mResolveComponentName.equals(component)) {
2646                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2647                        new PackageUserState(), userId);
2648            }
2649        }
2650        return null;
2651    }
2652
2653    @Override
2654    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2655            String resolvedType) {
2656        synchronized (mPackages) {
2657            PackageParser.Activity a = mActivities.mActivities.get(component);
2658            if (a == null) {
2659                return false;
2660            }
2661            for (int i=0; i<a.intents.size(); i++) {
2662                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2663                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2664                    return true;
2665                }
2666            }
2667            return false;
2668        }
2669    }
2670
2671    @Override
2672    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2673        if (!sUserManager.exists(userId)) return null;
2674        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2675        synchronized (mPackages) {
2676            PackageParser.Activity a = mReceivers.mActivities.get(component);
2677            if (DEBUG_PACKAGE_INFO) Log.v(
2678                TAG, "getReceiverInfo " + component + ": " + a);
2679            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2680                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2681                if (ps == null) return null;
2682                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2683                        userId);
2684            }
2685        }
2686        return null;
2687    }
2688
2689    @Override
2690    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2691        if (!sUserManager.exists(userId)) return null;
2692        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2693        synchronized (mPackages) {
2694            PackageParser.Service s = mServices.mServices.get(component);
2695            if (DEBUG_PACKAGE_INFO) Log.v(
2696                TAG, "getServiceInfo " + component + ": " + s);
2697            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2698                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2699                if (ps == null) return null;
2700                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2701                        userId);
2702            }
2703        }
2704        return null;
2705    }
2706
2707    @Override
2708    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2709        if (!sUserManager.exists(userId)) return null;
2710        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2711        synchronized (mPackages) {
2712            PackageParser.Provider p = mProviders.mProviders.get(component);
2713            if (DEBUG_PACKAGE_INFO) Log.v(
2714                TAG, "getProviderInfo " + component + ": " + p);
2715            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2716                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2717                if (ps == null) return null;
2718                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2719                        userId);
2720            }
2721        }
2722        return null;
2723    }
2724
2725    @Override
2726    public String[] getSystemSharedLibraryNames() {
2727        Set<String> libSet;
2728        synchronized (mPackages) {
2729            libSet = mSharedLibraries.keySet();
2730            int size = libSet.size();
2731            if (size > 0) {
2732                String[] libs = new String[size];
2733                libSet.toArray(libs);
2734                return libs;
2735            }
2736        }
2737        return null;
2738    }
2739
2740    /**
2741     * @hide
2742     */
2743    PackageParser.Package findSharedNonSystemLibrary(String libName) {
2744        synchronized (mPackages) {
2745            PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName);
2746            if (lib != null && lib.apk != null) {
2747                return mPackages.get(lib.apk);
2748            }
2749        }
2750        return null;
2751    }
2752
2753    @Override
2754    public FeatureInfo[] getSystemAvailableFeatures() {
2755        Collection<FeatureInfo> featSet;
2756        synchronized (mPackages) {
2757            featSet = mAvailableFeatures.values();
2758            int size = featSet.size();
2759            if (size > 0) {
2760                FeatureInfo[] features = new FeatureInfo[size+1];
2761                featSet.toArray(features);
2762                FeatureInfo fi = new FeatureInfo();
2763                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2764                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2765                features[size] = fi;
2766                return features;
2767            }
2768        }
2769        return null;
2770    }
2771
2772    @Override
2773    public boolean hasSystemFeature(String name) {
2774        synchronized (mPackages) {
2775            return mAvailableFeatures.containsKey(name);
2776        }
2777    }
2778
2779    private void checkValidCaller(int uid, int userId) {
2780        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2781            return;
2782
2783        throw new SecurityException("Caller uid=" + uid
2784                + " is not privileged to communicate with user=" + userId);
2785    }
2786
2787    @Override
2788    public int checkPermission(String permName, String pkgName, int userId) {
2789        if (!sUserManager.exists(userId)) {
2790            return PackageManager.PERMISSION_DENIED;
2791        }
2792
2793        synchronized (mPackages) {
2794            final PackageParser.Package p = mPackages.get(pkgName);
2795            if (p != null && p.mExtras != null) {
2796                final PackageSetting ps = (PackageSetting) p.mExtras;
2797                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2798                    return PackageManager.PERMISSION_GRANTED;
2799                }
2800            }
2801        }
2802
2803        return PackageManager.PERMISSION_DENIED;
2804    }
2805
2806    @Override
2807    public int checkUidPermission(String permName, int uid) {
2808        final int userId = UserHandle.getUserId(uid);
2809
2810        if (!sUserManager.exists(userId)) {
2811            return PackageManager.PERMISSION_DENIED;
2812        }
2813
2814        synchronized (mPackages) {
2815            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2816            if (obj != null) {
2817                final SettingBase ps = (SettingBase) obj;
2818                if (ps.getPermissionsState().hasPermission(permName, userId)) {
2819                    return PackageManager.PERMISSION_GRANTED;
2820                }
2821            } else {
2822                ArraySet<String> perms = mSystemPermissions.get(uid);
2823                if (perms != null && perms.contains(permName)) {
2824                    return PackageManager.PERMISSION_GRANTED;
2825                }
2826            }
2827        }
2828
2829        return PackageManager.PERMISSION_DENIED;
2830    }
2831
2832    /**
2833     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2834     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2835     * @param checkShell TODO(yamasani):
2836     * @param message the message to log on security exception
2837     */
2838    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2839            boolean checkShell, String message) {
2840        if (userId < 0) {
2841            throw new IllegalArgumentException("Invalid userId " + userId);
2842        }
2843        if (checkShell) {
2844            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2845        }
2846        if (userId == UserHandle.getUserId(callingUid)) return;
2847        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2848            if (requireFullPermission) {
2849                mContext.enforceCallingOrSelfPermission(
2850                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2851            } else {
2852                try {
2853                    mContext.enforceCallingOrSelfPermission(
2854                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2855                } catch (SecurityException se) {
2856                    mContext.enforceCallingOrSelfPermission(
2857                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2858                }
2859            }
2860        }
2861    }
2862
2863    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2864        if (callingUid == Process.SHELL_UID) {
2865            if (userHandle >= 0
2866                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2867                throw new SecurityException("Shell does not have permission to access user "
2868                        + userHandle);
2869            } else if (userHandle < 0) {
2870                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2871                        + Debug.getCallers(3));
2872            }
2873        }
2874    }
2875
2876    private BasePermission findPermissionTreeLP(String permName) {
2877        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2878            if (permName.startsWith(bp.name) &&
2879                    permName.length() > bp.name.length() &&
2880                    permName.charAt(bp.name.length()) == '.') {
2881                return bp;
2882            }
2883        }
2884        return null;
2885    }
2886
2887    private BasePermission checkPermissionTreeLP(String permName) {
2888        if (permName != null) {
2889            BasePermission bp = findPermissionTreeLP(permName);
2890            if (bp != null) {
2891                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2892                    return bp;
2893                }
2894                throw new SecurityException("Calling uid "
2895                        + Binder.getCallingUid()
2896                        + " is not allowed to add to permission tree "
2897                        + bp.name + " owned by uid " + bp.uid);
2898            }
2899        }
2900        throw new SecurityException("No permission tree found for " + permName);
2901    }
2902
2903    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2904        if (s1 == null) {
2905            return s2 == null;
2906        }
2907        if (s2 == null) {
2908            return false;
2909        }
2910        if (s1.getClass() != s2.getClass()) {
2911            return false;
2912        }
2913        return s1.equals(s2);
2914    }
2915
2916    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2917        if (pi1.icon != pi2.icon) return false;
2918        if (pi1.logo != pi2.logo) return false;
2919        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2920        if (!compareStrings(pi1.name, pi2.name)) return false;
2921        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2922        // We'll take care of setting this one.
2923        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2924        // These are not currently stored in settings.
2925        //if (!compareStrings(pi1.group, pi2.group)) return false;
2926        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2927        //if (pi1.labelRes != pi2.labelRes) return false;
2928        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2929        return true;
2930    }
2931
2932    int permissionInfoFootprint(PermissionInfo info) {
2933        int size = info.name.length();
2934        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2935        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2936        return size;
2937    }
2938
2939    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2940        int size = 0;
2941        for (BasePermission perm : mSettings.mPermissions.values()) {
2942            if (perm.uid == tree.uid) {
2943                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2944            }
2945        }
2946        return size;
2947    }
2948
2949    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2950        // We calculate the max size of permissions defined by this uid and throw
2951        // if that plus the size of 'info' would exceed our stated maximum.
2952        if (tree.uid != Process.SYSTEM_UID) {
2953            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2954            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2955                throw new SecurityException("Permission tree size cap exceeded");
2956            }
2957        }
2958    }
2959
2960    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2961        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2962            throw new SecurityException("Label must be specified in permission");
2963        }
2964        BasePermission tree = checkPermissionTreeLP(info.name);
2965        BasePermission bp = mSettings.mPermissions.get(info.name);
2966        boolean added = bp == null;
2967        boolean changed = true;
2968        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2969        if (added) {
2970            enforcePermissionCapLocked(info, tree);
2971            bp = new BasePermission(info.name, tree.sourcePackage,
2972                    BasePermission.TYPE_DYNAMIC);
2973        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2974            throw new SecurityException(
2975                    "Not allowed to modify non-dynamic permission "
2976                    + info.name);
2977        } else {
2978            if (bp.protectionLevel == fixedLevel
2979                    && bp.perm.owner.equals(tree.perm.owner)
2980                    && bp.uid == tree.uid
2981                    && comparePermissionInfos(bp.perm.info, info)) {
2982                changed = false;
2983            }
2984        }
2985        bp.protectionLevel = fixedLevel;
2986        info = new PermissionInfo(info);
2987        info.protectionLevel = fixedLevel;
2988        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2989        bp.perm.info.packageName = tree.perm.info.packageName;
2990        bp.uid = tree.uid;
2991        if (added) {
2992            mSettings.mPermissions.put(info.name, bp);
2993        }
2994        if (changed) {
2995            if (!async) {
2996                mSettings.writeLPr();
2997            } else {
2998                scheduleWriteSettingsLocked();
2999            }
3000        }
3001        return added;
3002    }
3003
3004    @Override
3005    public boolean addPermission(PermissionInfo info) {
3006        synchronized (mPackages) {
3007            return addPermissionLocked(info, false);
3008        }
3009    }
3010
3011    @Override
3012    public boolean addPermissionAsync(PermissionInfo info) {
3013        synchronized (mPackages) {
3014            return addPermissionLocked(info, true);
3015        }
3016    }
3017
3018    @Override
3019    public void removePermission(String name) {
3020        synchronized (mPackages) {
3021            checkPermissionTreeLP(name);
3022            BasePermission bp = mSettings.mPermissions.get(name);
3023            if (bp != null) {
3024                if (bp.type != BasePermission.TYPE_DYNAMIC) {
3025                    throw new SecurityException(
3026                            "Not allowed to modify non-dynamic permission "
3027                            + name);
3028                }
3029                mSettings.mPermissions.remove(name);
3030                mSettings.writeLPr();
3031            }
3032        }
3033    }
3034
3035    private static void enforceDeclaredAsUsedAndRuntimePermission(PackageParser.Package pkg,
3036            BasePermission bp) {
3037        int index = pkg.requestedPermissions.indexOf(bp.name);
3038        if (index == -1) {
3039            throw new SecurityException("Package " + pkg.packageName
3040                    + " has not requested permission " + bp.name);
3041        }
3042        if (!bp.isRuntime()) {
3043            throw new SecurityException("Permission " + bp.name
3044                    + " is not a changeable permission type");
3045        }
3046    }
3047
3048    @Override
3049    public boolean grantPermission(String packageName, String name, int userId) {
3050        if (!RUNTIME_PERMISSIONS_ENABLED) {
3051            return false;
3052        }
3053
3054        if (!sUserManager.exists(userId)) {
3055            return false;
3056        }
3057
3058        mContext.enforceCallingOrSelfPermission(
3059                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3060                "grantPermission");
3061
3062        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3063                "grantPermission");
3064
3065        boolean gidsChanged = false;
3066        final SettingBase sb;
3067
3068        synchronized (mPackages) {
3069            final PackageParser.Package pkg = mPackages.get(packageName);
3070            if (pkg == null) {
3071                throw new IllegalArgumentException("Unknown package: " + packageName);
3072            }
3073
3074            final BasePermission bp = mSettings.mPermissions.get(name);
3075            if (bp == null) {
3076                throw new IllegalArgumentException("Unknown permission: " + name);
3077            }
3078
3079            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3080
3081            sb = (SettingBase) pkg.mExtras;
3082            if (sb == null) {
3083                throw new IllegalArgumentException("Unknown package: " + packageName);
3084            }
3085
3086            final PermissionsState permissionsState = sb.getPermissionsState();
3087
3088            final int result = permissionsState.grantRuntimePermission(bp, userId);
3089            switch (result) {
3090                case PermissionsState.PERMISSION_OPERATION_FAILURE: {
3091                    return false;
3092                }
3093
3094                case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: {
3095                    gidsChanged = true;
3096                } break;
3097            }
3098
3099            // Not critical if that is lost - app has to request again.
3100            mSettings.writeRuntimePermissionsForUserLPr(userId, false);
3101        }
3102
3103        if (gidsChanged) {
3104            killSettingPackagesForUser(sb, userId, KILL_APP_REASON_GIDS_CHANGED);
3105        }
3106
3107        return true;
3108    }
3109
3110    @Override
3111    public boolean revokePermission(String packageName, String name, int userId) {
3112        if (!RUNTIME_PERMISSIONS_ENABLED) {
3113            return false;
3114        }
3115
3116        if (!sUserManager.exists(userId)) {
3117            return false;
3118        }
3119
3120        mContext.enforceCallingOrSelfPermission(
3121                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS,
3122                "revokePermission");
3123
3124        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false,
3125                "revokePermission");
3126
3127        final SettingBase sb;
3128
3129        synchronized (mPackages) {
3130            final PackageParser.Package pkg = mPackages.get(packageName);
3131            if (pkg == null) {
3132                throw new IllegalArgumentException("Unknown package: " + packageName);
3133            }
3134
3135            final BasePermission bp = mSettings.mPermissions.get(name);
3136            if (bp == null) {
3137                throw new IllegalArgumentException("Unknown permission: " + name);
3138            }
3139
3140            enforceDeclaredAsUsedAndRuntimePermission(pkg, bp);
3141
3142            sb = (SettingBase) pkg.mExtras;
3143            if (sb == null) {
3144                throw new IllegalArgumentException("Unknown package: " + packageName);
3145            }
3146
3147            final PermissionsState permissionsState = sb.getPermissionsState();
3148
3149            if (permissionsState.revokeRuntimePermission(bp, userId) ==
3150                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
3151                return false;
3152            }
3153
3154            // Critical, after this call all should never have the permission.
3155            mSettings.writeRuntimePermissionsForUserLPr(userId, true);
3156        }
3157
3158        killSettingPackagesForUser(sb, userId, KILL_APP_REASON_PERMISSIONS_REVOKED);
3159
3160        return true;
3161    }
3162
3163    @Override
3164    public boolean isProtectedBroadcast(String actionName) {
3165        synchronized (mPackages) {
3166            return mProtectedBroadcasts.contains(actionName);
3167        }
3168    }
3169
3170    @Override
3171    public int checkSignatures(String pkg1, String pkg2) {
3172        synchronized (mPackages) {
3173            final PackageParser.Package p1 = mPackages.get(pkg1);
3174            final PackageParser.Package p2 = mPackages.get(pkg2);
3175            if (p1 == null || p1.mExtras == null
3176                    || p2 == null || p2.mExtras == null) {
3177                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3178            }
3179            return compareSignatures(p1.mSignatures, p2.mSignatures);
3180        }
3181    }
3182
3183    @Override
3184    public int checkUidSignatures(int uid1, int uid2) {
3185        // Map to base uids.
3186        uid1 = UserHandle.getAppId(uid1);
3187        uid2 = UserHandle.getAppId(uid2);
3188        // reader
3189        synchronized (mPackages) {
3190            Signature[] s1;
3191            Signature[] s2;
3192            Object obj = mSettings.getUserIdLPr(uid1);
3193            if (obj != null) {
3194                if (obj instanceof SharedUserSetting) {
3195                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
3196                } else if (obj instanceof PackageSetting) {
3197                    s1 = ((PackageSetting)obj).signatures.mSignatures;
3198                } else {
3199                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3200                }
3201            } else {
3202                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3203            }
3204            obj = mSettings.getUserIdLPr(uid2);
3205            if (obj != null) {
3206                if (obj instanceof SharedUserSetting) {
3207                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
3208                } else if (obj instanceof PackageSetting) {
3209                    s2 = ((PackageSetting)obj).signatures.mSignatures;
3210                } else {
3211                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3212                }
3213            } else {
3214                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
3215            }
3216            return compareSignatures(s1, s2);
3217        }
3218    }
3219
3220    private void killSettingPackagesForUser(SettingBase sb, int userId, String reason) {
3221        final long identity = Binder.clearCallingIdentity();
3222        try {
3223            if (sb instanceof SharedUserSetting) {
3224                SharedUserSetting sus = (SharedUserSetting) sb;
3225                final int packageCount = sus.packages.size();
3226                for (int i = 0; i < packageCount; i++) {
3227                    PackageSetting susPs = sus.packages.valueAt(i);
3228                    if (userId == UserHandle.USER_ALL) {
3229                        killApplication(susPs.pkg.packageName, susPs.appId, reason);
3230                    } else {
3231                        final int uid = UserHandle.getUid(userId, susPs.appId);
3232                        killUid(uid, reason);
3233                    }
3234                }
3235            } else if (sb instanceof PackageSetting) {
3236                PackageSetting ps = (PackageSetting) sb;
3237                if (userId == UserHandle.USER_ALL) {
3238                    killApplication(ps.pkg.packageName, ps.appId, reason);
3239                } else {
3240                    final int uid = UserHandle.getUid(userId, ps.appId);
3241                    killUid(uid, reason);
3242                }
3243            }
3244        } finally {
3245            Binder.restoreCallingIdentity(identity);
3246        }
3247    }
3248
3249    private static void killUid(int uid, String reason) {
3250        IActivityManager am = ActivityManagerNative.getDefault();
3251        if (am != null) {
3252            try {
3253                am.killUid(uid, reason);
3254            } catch (RemoteException e) {
3255                /* ignore - same process */
3256            }
3257        }
3258    }
3259
3260    /**
3261     * Compares two sets of signatures. Returns:
3262     * <br />
3263     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
3264     * <br />
3265     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
3266     * <br />
3267     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
3268     * <br />
3269     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
3270     * <br />
3271     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
3272     */
3273    static int compareSignatures(Signature[] s1, Signature[] s2) {
3274        if (s1 == null) {
3275            return s2 == null
3276                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
3277                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
3278        }
3279
3280        if (s2 == null) {
3281            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
3282        }
3283
3284        if (s1.length != s2.length) {
3285            return PackageManager.SIGNATURE_NO_MATCH;
3286        }
3287
3288        // Since both signature sets are of size 1, we can compare without HashSets.
3289        if (s1.length == 1) {
3290            return s1[0].equals(s2[0]) ?
3291                    PackageManager.SIGNATURE_MATCH :
3292                    PackageManager.SIGNATURE_NO_MATCH;
3293        }
3294
3295        ArraySet<Signature> set1 = new ArraySet<Signature>();
3296        for (Signature sig : s1) {
3297            set1.add(sig);
3298        }
3299        ArraySet<Signature> set2 = new ArraySet<Signature>();
3300        for (Signature sig : s2) {
3301            set2.add(sig);
3302        }
3303        // Make sure s2 contains all signatures in s1.
3304        if (set1.equals(set2)) {
3305            return PackageManager.SIGNATURE_MATCH;
3306        }
3307        return PackageManager.SIGNATURE_NO_MATCH;
3308    }
3309
3310    /**
3311     * If the database version for this type of package (internal storage or
3312     * external storage) is less than the version where package signatures
3313     * were updated, return true.
3314     */
3315    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3316        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
3317                DatabaseVersion.SIGNATURE_END_ENTITY))
3318                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
3319                        DatabaseVersion.SIGNATURE_END_ENTITY));
3320    }
3321
3322    /**
3323     * Used for backward compatibility to make sure any packages with
3324     * certificate chains get upgraded to the new style. {@code existingSigs}
3325     * will be in the old format (since they were stored on disk from before the
3326     * system upgrade) and {@code scannedSigs} will be in the newer format.
3327     */
3328    private int compareSignaturesCompat(PackageSignatures existingSigs,
3329            PackageParser.Package scannedPkg) {
3330        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
3331            return PackageManager.SIGNATURE_NO_MATCH;
3332        }
3333
3334        ArraySet<Signature> existingSet = new ArraySet<Signature>();
3335        for (Signature sig : existingSigs.mSignatures) {
3336            existingSet.add(sig);
3337        }
3338        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
3339        for (Signature sig : scannedPkg.mSignatures) {
3340            try {
3341                Signature[] chainSignatures = sig.getChainSignatures();
3342                for (Signature chainSig : chainSignatures) {
3343                    scannedCompatSet.add(chainSig);
3344                }
3345            } catch (CertificateEncodingException e) {
3346                scannedCompatSet.add(sig);
3347            }
3348        }
3349        /*
3350         * Make sure the expanded scanned set contains all signatures in the
3351         * existing one.
3352         */
3353        if (scannedCompatSet.equals(existingSet)) {
3354            // Migrate the old signatures to the new scheme.
3355            existingSigs.assignSignatures(scannedPkg.mSignatures);
3356            // The new KeySets will be re-added later in the scanning process.
3357            synchronized (mPackages) {
3358                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
3359            }
3360            return PackageManager.SIGNATURE_MATCH;
3361        }
3362        return PackageManager.SIGNATURE_NO_MATCH;
3363    }
3364
3365    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
3366        if (isExternal(scannedPkg)) {
3367            return mSettings.isExternalDatabaseVersionOlderThan(
3368                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3369        } else {
3370            return mSettings.isInternalDatabaseVersionOlderThan(
3371                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
3372        }
3373    }
3374
3375    private int compareSignaturesRecover(PackageSignatures existingSigs,
3376            PackageParser.Package scannedPkg) {
3377        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
3378            return PackageManager.SIGNATURE_NO_MATCH;
3379        }
3380
3381        String msg = null;
3382        try {
3383            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
3384                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
3385                        + scannedPkg.packageName);
3386                return PackageManager.SIGNATURE_MATCH;
3387            }
3388        } catch (CertificateException e) {
3389            msg = e.getMessage();
3390        }
3391
3392        logCriticalInfo(Log.INFO,
3393                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
3394        return PackageManager.SIGNATURE_NO_MATCH;
3395    }
3396
3397    @Override
3398    public String[] getPackagesForUid(int uid) {
3399        uid = UserHandle.getAppId(uid);
3400        // reader
3401        synchronized (mPackages) {
3402            Object obj = mSettings.getUserIdLPr(uid);
3403            if (obj instanceof SharedUserSetting) {
3404                final SharedUserSetting sus = (SharedUserSetting) obj;
3405                final int N = sus.packages.size();
3406                final String[] res = new String[N];
3407                final Iterator<PackageSetting> it = sus.packages.iterator();
3408                int i = 0;
3409                while (it.hasNext()) {
3410                    res[i++] = it.next().name;
3411                }
3412                return res;
3413            } else if (obj instanceof PackageSetting) {
3414                final PackageSetting ps = (PackageSetting) obj;
3415                return new String[] { ps.name };
3416            }
3417        }
3418        return null;
3419    }
3420
3421    @Override
3422    public String getNameForUid(int uid) {
3423        // reader
3424        synchronized (mPackages) {
3425            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3426            if (obj instanceof SharedUserSetting) {
3427                final SharedUserSetting sus = (SharedUserSetting) obj;
3428                return sus.name + ":" + sus.userId;
3429            } else if (obj instanceof PackageSetting) {
3430                final PackageSetting ps = (PackageSetting) obj;
3431                return ps.name;
3432            }
3433        }
3434        return null;
3435    }
3436
3437    @Override
3438    public int getUidForSharedUser(String sharedUserName) {
3439        if(sharedUserName == null) {
3440            return -1;
3441        }
3442        // reader
3443        synchronized (mPackages) {
3444            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
3445            if (suid == null) {
3446                return -1;
3447            }
3448            return suid.userId;
3449        }
3450    }
3451
3452    @Override
3453    public int getFlagsForUid(int uid) {
3454        synchronized (mPackages) {
3455            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3456            if (obj instanceof SharedUserSetting) {
3457                final SharedUserSetting sus = (SharedUserSetting) obj;
3458                return sus.pkgFlags;
3459            } else if (obj instanceof PackageSetting) {
3460                final PackageSetting ps = (PackageSetting) obj;
3461                return ps.pkgFlags;
3462            }
3463        }
3464        return 0;
3465    }
3466
3467    @Override
3468    public int getPrivateFlagsForUid(int uid) {
3469        synchronized (mPackages) {
3470            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3471            if (obj instanceof SharedUserSetting) {
3472                final SharedUserSetting sus = (SharedUserSetting) obj;
3473                return sus.pkgPrivateFlags;
3474            } else if (obj instanceof PackageSetting) {
3475                final PackageSetting ps = (PackageSetting) obj;
3476                return ps.pkgPrivateFlags;
3477            }
3478        }
3479        return 0;
3480    }
3481
3482    @Override
3483    public boolean isUidPrivileged(int uid) {
3484        uid = UserHandle.getAppId(uid);
3485        // reader
3486        synchronized (mPackages) {
3487            Object obj = mSettings.getUserIdLPr(uid);
3488            if (obj instanceof SharedUserSetting) {
3489                final SharedUserSetting sus = (SharedUserSetting) obj;
3490                final Iterator<PackageSetting> it = sus.packages.iterator();
3491                while (it.hasNext()) {
3492                    if (it.next().isPrivileged()) {
3493                        return true;
3494                    }
3495                }
3496            } else if (obj instanceof PackageSetting) {
3497                final PackageSetting ps = (PackageSetting) obj;
3498                return ps.isPrivileged();
3499            }
3500        }
3501        return false;
3502    }
3503
3504    @Override
3505    public String[] getAppOpPermissionPackages(String permissionName) {
3506        synchronized (mPackages) {
3507            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
3508            if (pkgs == null) {
3509                return null;
3510            }
3511            return pkgs.toArray(new String[pkgs.size()]);
3512        }
3513    }
3514
3515    @Override
3516    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3517            int flags, int userId) {
3518        if (!sUserManager.exists(userId)) return null;
3519        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3520        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3521        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3522    }
3523
3524    @Override
3525    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3526            IntentFilter filter, int match, ComponentName activity) {
3527        final int userId = UserHandle.getCallingUserId();
3528        if (DEBUG_PREFERRED) {
3529            Log.v(TAG, "setLastChosenActivity intent=" + intent
3530                + " resolvedType=" + resolvedType
3531                + " flags=" + flags
3532                + " filter=" + filter
3533                + " match=" + match
3534                + " activity=" + activity);
3535            filter.dump(new PrintStreamPrinter(System.out), "    ");
3536        }
3537        intent.setComponent(null);
3538        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3539        // Find any earlier preferred or last chosen entries and nuke them
3540        findPreferredActivity(intent, resolvedType,
3541                flags, query, 0, false, true, false, userId);
3542        // Add the new activity as the last chosen for this filter
3543        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3544                "Setting last chosen");
3545    }
3546
3547    @Override
3548    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3549        final int userId = UserHandle.getCallingUserId();
3550        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3551        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3552        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3553                false, false, false, userId);
3554    }
3555
3556    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3557            int flags, List<ResolveInfo> query, int userId) {
3558        if (query != null) {
3559            final int N = query.size();
3560            if (N == 1) {
3561                return query.get(0);
3562            } else if (N > 1) {
3563                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3564                // If there is more than one activity with the same priority,
3565                // then let the user decide between them.
3566                ResolveInfo r0 = query.get(0);
3567                ResolveInfo r1 = query.get(1);
3568                if (DEBUG_INTENT_MATCHING || debug) {
3569                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3570                            + r1.activityInfo.name + "=" + r1.priority);
3571                }
3572                // If the first activity has a higher priority, or a different
3573                // default, then it is always desireable to pick it.
3574                if (r0.priority != r1.priority
3575                        || r0.preferredOrder != r1.preferredOrder
3576                        || r0.isDefault != r1.isDefault) {
3577                    return query.get(0);
3578                }
3579                // If we have saved a preference for a preferred activity for
3580                // this Intent, use that.
3581                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3582                        flags, query, r0.priority, true, false, debug, userId);
3583                if (ri != null) {
3584                    return ri;
3585                }
3586                if (userId != 0) {
3587                    ri = new ResolveInfo(mResolveInfo);
3588                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3589                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3590                            ri.activityInfo.applicationInfo);
3591                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3592                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3593                    return ri;
3594                }
3595                return mResolveInfo;
3596            }
3597        }
3598        return null;
3599    }
3600
3601    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3602            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3603        final int N = query.size();
3604        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3605                .get(userId);
3606        // Get the list of persistent preferred activities that handle the intent
3607        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3608        List<PersistentPreferredActivity> pprefs = ppir != null
3609                ? ppir.queryIntent(intent, resolvedType,
3610                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3611                : null;
3612        if (pprefs != null && pprefs.size() > 0) {
3613            final int M = pprefs.size();
3614            for (int i=0; i<M; i++) {
3615                final PersistentPreferredActivity ppa = pprefs.get(i);
3616                if (DEBUG_PREFERRED || debug) {
3617                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3618                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3619                            + "\n  component=" + ppa.mComponent);
3620                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3621                }
3622                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3623                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3624                if (DEBUG_PREFERRED || debug) {
3625                    Slog.v(TAG, "Found persistent preferred activity:");
3626                    if (ai != null) {
3627                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3628                    } else {
3629                        Slog.v(TAG, "  null");
3630                    }
3631                }
3632                if (ai == null) {
3633                    // This previously registered persistent preferred activity
3634                    // component is no longer known. Ignore it and do NOT remove it.
3635                    continue;
3636                }
3637                for (int j=0; j<N; j++) {
3638                    final ResolveInfo ri = query.get(j);
3639                    if (!ri.activityInfo.applicationInfo.packageName
3640                            .equals(ai.applicationInfo.packageName)) {
3641                        continue;
3642                    }
3643                    if (!ri.activityInfo.name.equals(ai.name)) {
3644                        continue;
3645                    }
3646                    //  Found a persistent preference that can handle the intent.
3647                    if (DEBUG_PREFERRED || debug) {
3648                        Slog.v(TAG, "Returning persistent preferred activity: " +
3649                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3650                    }
3651                    return ri;
3652                }
3653            }
3654        }
3655        return null;
3656    }
3657
3658    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3659            List<ResolveInfo> query, int priority, boolean always,
3660            boolean removeMatches, boolean debug, int userId) {
3661        if (!sUserManager.exists(userId)) return null;
3662        // writer
3663        synchronized (mPackages) {
3664            if (intent.getSelector() != null) {
3665                intent = intent.getSelector();
3666            }
3667            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3668
3669            // Try to find a matching persistent preferred activity.
3670            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3671                    debug, userId);
3672
3673            // If a persistent preferred activity matched, use it.
3674            if (pri != null) {
3675                return pri;
3676            }
3677
3678            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3679            // Get the list of preferred activities that handle the intent
3680            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3681            List<PreferredActivity> prefs = pir != null
3682                    ? pir.queryIntent(intent, resolvedType,
3683                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3684                    : null;
3685            if (prefs != null && prefs.size() > 0) {
3686                boolean changed = false;
3687                try {
3688                    // First figure out how good the original match set is.
3689                    // We will only allow preferred activities that came
3690                    // from the same match quality.
3691                    int match = 0;
3692
3693                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3694
3695                    final int N = query.size();
3696                    for (int j=0; j<N; j++) {
3697                        final ResolveInfo ri = query.get(j);
3698                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3699                                + ": 0x" + Integer.toHexString(match));
3700                        if (ri.match > match) {
3701                            match = ri.match;
3702                        }
3703                    }
3704
3705                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3706                            + Integer.toHexString(match));
3707
3708                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3709                    final int M = prefs.size();
3710                    for (int i=0; i<M; i++) {
3711                        final PreferredActivity pa = prefs.get(i);
3712                        if (DEBUG_PREFERRED || debug) {
3713                            Slog.v(TAG, "Checking PreferredActivity ds="
3714                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3715                                    + "\n  component=" + pa.mPref.mComponent);
3716                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3717                        }
3718                        if (pa.mPref.mMatch != match) {
3719                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3720                                    + Integer.toHexString(pa.mPref.mMatch));
3721                            continue;
3722                        }
3723                        // If it's not an "always" type preferred activity and that's what we're
3724                        // looking for, skip it.
3725                        if (always && !pa.mPref.mAlways) {
3726                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3727                            continue;
3728                        }
3729                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3730                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3731                        if (DEBUG_PREFERRED || debug) {
3732                            Slog.v(TAG, "Found preferred activity:");
3733                            if (ai != null) {
3734                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3735                            } else {
3736                                Slog.v(TAG, "  null");
3737                            }
3738                        }
3739                        if (ai == null) {
3740                            // This previously registered preferred activity
3741                            // component is no longer known.  Most likely an update
3742                            // to the app was installed and in the new version this
3743                            // component no longer exists.  Clean it up by removing
3744                            // it from the preferred activities list, and skip it.
3745                            Slog.w(TAG, "Removing dangling preferred activity: "
3746                                    + pa.mPref.mComponent);
3747                            pir.removeFilter(pa);
3748                            changed = true;
3749                            continue;
3750                        }
3751                        for (int j=0; j<N; j++) {
3752                            final ResolveInfo ri = query.get(j);
3753                            if (!ri.activityInfo.applicationInfo.packageName
3754                                    .equals(ai.applicationInfo.packageName)) {
3755                                continue;
3756                            }
3757                            if (!ri.activityInfo.name.equals(ai.name)) {
3758                                continue;
3759                            }
3760
3761                            if (removeMatches) {
3762                                pir.removeFilter(pa);
3763                                changed = true;
3764                                if (DEBUG_PREFERRED) {
3765                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3766                                }
3767                                break;
3768                            }
3769
3770                            // Okay we found a previously set preferred or last chosen app.
3771                            // If the result set is different from when this
3772                            // was created, we need to clear it and re-ask the
3773                            // user their preference, if we're looking for an "always" type entry.
3774                            if (always && !pa.mPref.sameSet(query)) {
3775                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3776                                        + intent + " type " + resolvedType);
3777                                if (DEBUG_PREFERRED) {
3778                                    Slog.v(TAG, "Removing preferred activity since set changed "
3779                                            + pa.mPref.mComponent);
3780                                }
3781                                pir.removeFilter(pa);
3782                                // Re-add the filter as a "last chosen" entry (!always)
3783                                PreferredActivity lastChosen = new PreferredActivity(
3784                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3785                                pir.addFilter(lastChosen);
3786                                changed = true;
3787                                return null;
3788                            }
3789
3790                            // Yay! Either the set matched or we're looking for the last chosen
3791                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3792                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3793                            return ri;
3794                        }
3795                    }
3796                } finally {
3797                    if (changed) {
3798                        if (DEBUG_PREFERRED) {
3799                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3800                        }
3801                        scheduleWritePackageRestrictionsLocked(userId);
3802                    }
3803                }
3804            }
3805        }
3806        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3807        return null;
3808    }
3809
3810    /*
3811     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3812     */
3813    @Override
3814    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3815            int targetUserId) {
3816        mContext.enforceCallingOrSelfPermission(
3817                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3818        List<CrossProfileIntentFilter> matches =
3819                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3820        if (matches != null) {
3821            int size = matches.size();
3822            for (int i = 0; i < size; i++) {
3823                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3824            }
3825        }
3826        return false;
3827    }
3828
3829    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3830            String resolvedType, int userId) {
3831        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3832        if (resolver != null) {
3833            return resolver.queryIntent(intent, resolvedType, false, userId);
3834        }
3835        return null;
3836    }
3837
3838    @Override
3839    public List<ResolveInfo> queryIntentActivities(Intent intent,
3840            String resolvedType, int flags, int userId) {
3841        if (!sUserManager.exists(userId)) return Collections.emptyList();
3842        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3843        ComponentName comp = intent.getComponent();
3844        if (comp == null) {
3845            if (intent.getSelector() != null) {
3846                intent = intent.getSelector();
3847                comp = intent.getComponent();
3848            }
3849        }
3850
3851        if (comp != null) {
3852            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3853            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3854            if (ai != null) {
3855                final ResolveInfo ri = new ResolveInfo();
3856                ri.activityInfo = ai;
3857                list.add(ri);
3858            }
3859            return list;
3860        }
3861
3862        // reader
3863        synchronized (mPackages) {
3864            final String pkgName = intent.getPackage();
3865            if (pkgName == null) {
3866                List<CrossProfileIntentFilter> matchingFilters =
3867                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3868                // Check for results that need to skip the current profile.
3869                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3870                        resolvedType, flags, userId);
3871                if (resolveInfo != null) {
3872                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3873                    result.add(resolveInfo);
3874                    return filterIfNotPrimaryUser(result, userId);
3875                }
3876                // Check for cross profile results.
3877                resolveInfo = queryCrossProfileIntents(
3878                        matchingFilters, intent, resolvedType, flags, userId);
3879
3880                // Check for results in the current profile. Adding GET_RESOLVED_FILTER flags
3881                // as we need it later
3882                List<ResolveInfo> result = mActivities.queryIntent(
3883                        intent, resolvedType, flags, userId);
3884                if (resolveInfo != null) {
3885                    result.add(resolveInfo);
3886                    Collections.sort(result, mResolvePrioritySorter);
3887                }
3888                result = filterIfNotPrimaryUser(result, userId);
3889                if (result.size() > 1) {
3890                    return filterCandidatesWithDomainPreferedActivitiesLPw(result);
3891                }
3892
3893                return result;
3894            }
3895            final PackageParser.Package pkg = mPackages.get(pkgName);
3896            if (pkg != null) {
3897                return filterIfNotPrimaryUser(
3898                        mActivities.queryIntentForPackage(
3899                                intent, resolvedType, flags, pkg.activities, userId),
3900                        userId);
3901            }
3902            return new ArrayList<ResolveInfo>();
3903        }
3904    }
3905
3906    /**
3907     * Filter out activities with primaryUserOnly flag set, when current user is not the owner.
3908     *
3909     * @return filtered list
3910     */
3911    private List<ResolveInfo> filterIfNotPrimaryUser(List<ResolveInfo> resolveInfos, int userId) {
3912        if (userId == UserHandle.USER_OWNER) {
3913            return resolveInfos;
3914        }
3915        for (int i = resolveInfos.size() - 1; i >= 0; i--) {
3916            ResolveInfo info = resolveInfos.get(i);
3917            if ((info.activityInfo.flags & ActivityInfo.FLAG_PRIMARY_USER_ONLY) != 0) {
3918                resolveInfos.remove(i);
3919            }
3920        }
3921        return resolveInfos;
3922    }
3923
3924    private List<ResolveInfo> filterCandidatesWithDomainPreferedActivitiesLPw(
3925            List<ResolveInfo> candidates) {
3926        if (DEBUG_PREFERRED) {
3927            Slog.v("TAG", "Filtering results with prefered activities. Candidates count: " +
3928                    candidates.size());
3929        }
3930        final int userId = UserHandle.getCallingUserId();
3931        ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(candidates);
3932        synchronized (mPackages) {
3933            final int count = result.size();
3934            for (int n = count-1; n >= 0; n--) {
3935                ResolveInfo info = result.get(n);
3936                if (!info.filterNeedsVerification) {
3937                    continue;
3938                }
3939                String packageName = info.activityInfo.packageName;
3940                PackageSetting ps = mSettings.mPackages.get(packageName);
3941                if (ps != null) {
3942                    // Try to get the status from User settings first
3943                    int status = ps.getDomainVerificationStatusForUser(userId);
3944                    // if none available, get the master status
3945                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
3946                        if (ps.getIntentFilterVerificationInfo() != null) {
3947                            status = ps.getIntentFilterVerificationInfo().getStatus();
3948                        }
3949                    }
3950                    if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) {
3951                        result.clear();
3952                        result.add(info);
3953                        // We break the for loop as we are good to go
3954                        break;
3955                    } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) {
3956                        result.remove(n);
3957                    }
3958                }
3959            }
3960        }
3961        if (DEBUG_PREFERRED) {
3962            Slog.v("TAG", "Filtered results with prefered activities. New candidates count: " +
3963                    result.size());
3964        }
3965        return result;
3966    }
3967
3968    private ResolveInfo querySkipCurrentProfileIntents(
3969            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3970            int flags, int sourceUserId) {
3971        if (matchingFilters != null) {
3972            int size = matchingFilters.size();
3973            for (int i = 0; i < size; i ++) {
3974                CrossProfileIntentFilter filter = matchingFilters.get(i);
3975                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3976                    // Checking if there are activities in the target user that can handle the
3977                    // intent.
3978                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3979                            flags, sourceUserId);
3980                    if (resolveInfo != null) {
3981                        return resolveInfo;
3982                    }
3983                }
3984            }
3985        }
3986        return null;
3987    }
3988
3989    // Return matching ResolveInfo if any for skip current profile intent filters.
3990    private ResolveInfo queryCrossProfileIntents(
3991            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3992            int flags, int sourceUserId) {
3993        if (matchingFilters != null) {
3994            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3995            // match the same intent. For performance reasons, it is better not to
3996            // run queryIntent twice for the same userId
3997            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3998            int size = matchingFilters.size();
3999            for (int i = 0; i < size; i++) {
4000                CrossProfileIntentFilter filter = matchingFilters.get(i);
4001                int targetUserId = filter.getTargetUserId();
4002                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
4003                        && !alreadyTriedUserIds.get(targetUserId)) {
4004                    // Checking if there are activities in the target user that can handle the
4005                    // intent.
4006                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
4007                            flags, sourceUserId);
4008                    if (resolveInfo != null) return resolveInfo;
4009                    alreadyTriedUserIds.put(targetUserId, true);
4010                }
4011            }
4012        }
4013        return null;
4014    }
4015
4016    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
4017            String resolvedType, int flags, int sourceUserId) {
4018        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
4019                resolvedType, flags, filter.getTargetUserId());
4020        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
4021            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
4022        }
4023        return null;
4024    }
4025
4026    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
4027            int sourceUserId, int targetUserId) {
4028        ResolveInfo forwardingResolveInfo = new ResolveInfo();
4029        String className;
4030        if (targetUserId == UserHandle.USER_OWNER) {
4031            className = FORWARD_INTENT_TO_USER_OWNER;
4032        } else {
4033            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
4034        }
4035        ComponentName forwardingActivityComponentName = new ComponentName(
4036                mAndroidApplication.packageName, className);
4037        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
4038                sourceUserId);
4039        if (targetUserId == UserHandle.USER_OWNER) {
4040            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
4041            forwardingResolveInfo.noResourceId = true;
4042        }
4043        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
4044        forwardingResolveInfo.priority = 0;
4045        forwardingResolveInfo.preferredOrder = 0;
4046        forwardingResolveInfo.match = 0;
4047        forwardingResolveInfo.isDefault = true;
4048        forwardingResolveInfo.filter = filter;
4049        forwardingResolveInfo.targetUserId = targetUserId;
4050        return forwardingResolveInfo;
4051    }
4052
4053    @Override
4054    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
4055            Intent[] specifics, String[] specificTypes, Intent intent,
4056            String resolvedType, int flags, int userId) {
4057        if (!sUserManager.exists(userId)) return Collections.emptyList();
4058        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
4059                false, "query intent activity options");
4060        final String resultsAction = intent.getAction();
4061
4062        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
4063                | PackageManager.GET_RESOLVED_FILTER, userId);
4064
4065        if (DEBUG_INTENT_MATCHING) {
4066            Log.v(TAG, "Query " + intent + ": " + results);
4067        }
4068
4069        int specificsPos = 0;
4070        int N;
4071
4072        // todo: note that the algorithm used here is O(N^2).  This
4073        // isn't a problem in our current environment, but if we start running
4074        // into situations where we have more than 5 or 10 matches then this
4075        // should probably be changed to something smarter...
4076
4077        // First we go through and resolve each of the specific items
4078        // that were supplied, taking care of removing any corresponding
4079        // duplicate items in the generic resolve list.
4080        if (specifics != null) {
4081            for (int i=0; i<specifics.length; i++) {
4082                final Intent sintent = specifics[i];
4083                if (sintent == null) {
4084                    continue;
4085                }
4086
4087                if (DEBUG_INTENT_MATCHING) {
4088                    Log.v(TAG, "Specific #" + i + ": " + sintent);
4089                }
4090
4091                String action = sintent.getAction();
4092                if (resultsAction != null && resultsAction.equals(action)) {
4093                    // If this action was explicitly requested, then don't
4094                    // remove things that have it.
4095                    action = null;
4096                }
4097
4098                ResolveInfo ri = null;
4099                ActivityInfo ai = null;
4100
4101                ComponentName comp = sintent.getComponent();
4102                if (comp == null) {
4103                    ri = resolveIntent(
4104                        sintent,
4105                        specificTypes != null ? specificTypes[i] : null,
4106                            flags, userId);
4107                    if (ri == null) {
4108                        continue;
4109                    }
4110                    if (ri == mResolveInfo) {
4111                        // ACK!  Must do something better with this.
4112                    }
4113                    ai = ri.activityInfo;
4114                    comp = new ComponentName(ai.applicationInfo.packageName,
4115                            ai.name);
4116                } else {
4117                    ai = getActivityInfo(comp, flags, userId);
4118                    if (ai == null) {
4119                        continue;
4120                    }
4121                }
4122
4123                // Look for any generic query activities that are duplicates
4124                // of this specific one, and remove them from the results.
4125                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
4126                N = results.size();
4127                int j;
4128                for (j=specificsPos; j<N; j++) {
4129                    ResolveInfo sri = results.get(j);
4130                    if ((sri.activityInfo.name.equals(comp.getClassName())
4131                            && sri.activityInfo.applicationInfo.packageName.equals(
4132                                    comp.getPackageName()))
4133                        || (action != null && sri.filter.matchAction(action))) {
4134                        results.remove(j);
4135                        if (DEBUG_INTENT_MATCHING) Log.v(
4136                            TAG, "Removing duplicate item from " + j
4137                            + " due to specific " + specificsPos);
4138                        if (ri == null) {
4139                            ri = sri;
4140                        }
4141                        j--;
4142                        N--;
4143                    }
4144                }
4145
4146                // Add this specific item to its proper place.
4147                if (ri == null) {
4148                    ri = new ResolveInfo();
4149                    ri.activityInfo = ai;
4150                }
4151                results.add(specificsPos, ri);
4152                ri.specificIndex = i;
4153                specificsPos++;
4154            }
4155        }
4156
4157        // Now we go through the remaining generic results and remove any
4158        // duplicate actions that are found here.
4159        N = results.size();
4160        for (int i=specificsPos; i<N-1; i++) {
4161            final ResolveInfo rii = results.get(i);
4162            if (rii.filter == null) {
4163                continue;
4164            }
4165
4166            // Iterate over all of the actions of this result's intent
4167            // filter...  typically this should be just one.
4168            final Iterator<String> it = rii.filter.actionsIterator();
4169            if (it == null) {
4170                continue;
4171            }
4172            while (it.hasNext()) {
4173                final String action = it.next();
4174                if (resultsAction != null && resultsAction.equals(action)) {
4175                    // If this action was explicitly requested, then don't
4176                    // remove things that have it.
4177                    continue;
4178                }
4179                for (int j=i+1; j<N; j++) {
4180                    final ResolveInfo rij = results.get(j);
4181                    if (rij.filter != null && rij.filter.hasAction(action)) {
4182                        results.remove(j);
4183                        if (DEBUG_INTENT_MATCHING) Log.v(
4184                            TAG, "Removing duplicate item from " + j
4185                            + " due to action " + action + " at " + i);
4186                        j--;
4187                        N--;
4188                    }
4189                }
4190            }
4191
4192            // If the caller didn't request filter information, drop it now
4193            // so we don't have to marshall/unmarshall it.
4194            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4195                rii.filter = null;
4196            }
4197        }
4198
4199        // Filter out the caller activity if so requested.
4200        if (caller != null) {
4201            N = results.size();
4202            for (int i=0; i<N; i++) {
4203                ActivityInfo ainfo = results.get(i).activityInfo;
4204                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
4205                        && caller.getClassName().equals(ainfo.name)) {
4206                    results.remove(i);
4207                    break;
4208                }
4209            }
4210        }
4211
4212        // If the caller didn't request filter information,
4213        // drop them now so we don't have to
4214        // marshall/unmarshall it.
4215        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
4216            N = results.size();
4217            for (int i=0; i<N; i++) {
4218                results.get(i).filter = null;
4219            }
4220        }
4221
4222        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
4223        return results;
4224    }
4225
4226    @Override
4227    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
4228            int userId) {
4229        if (!sUserManager.exists(userId)) return Collections.emptyList();
4230        ComponentName comp = intent.getComponent();
4231        if (comp == null) {
4232            if (intent.getSelector() != null) {
4233                intent = intent.getSelector();
4234                comp = intent.getComponent();
4235            }
4236        }
4237        if (comp != null) {
4238            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4239            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
4240            if (ai != null) {
4241                ResolveInfo ri = new ResolveInfo();
4242                ri.activityInfo = ai;
4243                list.add(ri);
4244            }
4245            return list;
4246        }
4247
4248        // reader
4249        synchronized (mPackages) {
4250            String pkgName = intent.getPackage();
4251            if (pkgName == null) {
4252                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
4253            }
4254            final PackageParser.Package pkg = mPackages.get(pkgName);
4255            if (pkg != null) {
4256                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
4257                        userId);
4258            }
4259            return null;
4260        }
4261    }
4262
4263    @Override
4264    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
4265        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
4266        if (!sUserManager.exists(userId)) return null;
4267        if (query != null) {
4268            if (query.size() >= 1) {
4269                // If there is more than one service with the same priority,
4270                // just arbitrarily pick the first one.
4271                return query.get(0);
4272            }
4273        }
4274        return null;
4275    }
4276
4277    @Override
4278    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
4279            int userId) {
4280        if (!sUserManager.exists(userId)) return Collections.emptyList();
4281        ComponentName comp = intent.getComponent();
4282        if (comp == null) {
4283            if (intent.getSelector() != null) {
4284                intent = intent.getSelector();
4285                comp = intent.getComponent();
4286            }
4287        }
4288        if (comp != null) {
4289            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4290            final ServiceInfo si = getServiceInfo(comp, flags, userId);
4291            if (si != null) {
4292                final ResolveInfo ri = new ResolveInfo();
4293                ri.serviceInfo = si;
4294                list.add(ri);
4295            }
4296            return list;
4297        }
4298
4299        // reader
4300        synchronized (mPackages) {
4301            String pkgName = intent.getPackage();
4302            if (pkgName == null) {
4303                return mServices.queryIntent(intent, resolvedType, flags, userId);
4304            }
4305            final PackageParser.Package pkg = mPackages.get(pkgName);
4306            if (pkg != null) {
4307                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
4308                        userId);
4309            }
4310            return null;
4311        }
4312    }
4313
4314    @Override
4315    public List<ResolveInfo> queryIntentContentProviders(
4316            Intent intent, String resolvedType, int flags, int userId) {
4317        if (!sUserManager.exists(userId)) return Collections.emptyList();
4318        ComponentName comp = intent.getComponent();
4319        if (comp == null) {
4320            if (intent.getSelector() != null) {
4321                intent = intent.getSelector();
4322                comp = intent.getComponent();
4323            }
4324        }
4325        if (comp != null) {
4326            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
4327            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
4328            if (pi != null) {
4329                final ResolveInfo ri = new ResolveInfo();
4330                ri.providerInfo = pi;
4331                list.add(ri);
4332            }
4333            return list;
4334        }
4335
4336        // reader
4337        synchronized (mPackages) {
4338            String pkgName = intent.getPackage();
4339            if (pkgName == null) {
4340                return mProviders.queryIntent(intent, resolvedType, flags, userId);
4341            }
4342            final PackageParser.Package pkg = mPackages.get(pkgName);
4343            if (pkg != null) {
4344                return mProviders.queryIntentForPackage(
4345                        intent, resolvedType, flags, pkg.providers, userId);
4346            }
4347            return null;
4348        }
4349    }
4350
4351    @Override
4352    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
4353        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4354
4355        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
4356
4357        // writer
4358        synchronized (mPackages) {
4359            ArrayList<PackageInfo> list;
4360            if (listUninstalled) {
4361                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
4362                for (PackageSetting ps : mSettings.mPackages.values()) {
4363                    PackageInfo pi;
4364                    if (ps.pkg != null) {
4365                        pi = generatePackageInfo(ps.pkg, flags, userId);
4366                    } else {
4367                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4368                    }
4369                    if (pi != null) {
4370                        list.add(pi);
4371                    }
4372                }
4373            } else {
4374                list = new ArrayList<PackageInfo>(mPackages.size());
4375                for (PackageParser.Package p : mPackages.values()) {
4376                    PackageInfo pi = generatePackageInfo(p, flags, userId);
4377                    if (pi != null) {
4378                        list.add(pi);
4379                    }
4380                }
4381            }
4382
4383            return new ParceledListSlice<PackageInfo>(list);
4384        }
4385    }
4386
4387    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
4388            String[] permissions, boolean[] tmp, int flags, int userId) {
4389        int numMatch = 0;
4390        final PermissionsState permissionsState = ps.getPermissionsState();
4391        for (int i=0; i<permissions.length; i++) {
4392            final String permission = permissions[i];
4393            if (permissionsState.hasPermission(permission, userId)) {
4394                tmp[i] = true;
4395                numMatch++;
4396            } else {
4397                tmp[i] = false;
4398            }
4399        }
4400        if (numMatch == 0) {
4401            return;
4402        }
4403        PackageInfo pi;
4404        if (ps.pkg != null) {
4405            pi = generatePackageInfo(ps.pkg, flags, userId);
4406        } else {
4407            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
4408        }
4409        // The above might return null in cases of uninstalled apps or install-state
4410        // skew across users/profiles.
4411        if (pi != null) {
4412            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
4413                if (numMatch == permissions.length) {
4414                    pi.requestedPermissions = permissions;
4415                } else {
4416                    pi.requestedPermissions = new String[numMatch];
4417                    numMatch = 0;
4418                    for (int i=0; i<permissions.length; i++) {
4419                        if (tmp[i]) {
4420                            pi.requestedPermissions[numMatch] = permissions[i];
4421                            numMatch++;
4422                        }
4423                    }
4424                }
4425            }
4426            list.add(pi);
4427        }
4428    }
4429
4430    @Override
4431    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
4432            String[] permissions, int flags, int userId) {
4433        if (!sUserManager.exists(userId)) return null;
4434        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4435
4436        // writer
4437        synchronized (mPackages) {
4438            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
4439            boolean[] tmpBools = new boolean[permissions.length];
4440            if (listUninstalled) {
4441                for (PackageSetting ps : mSettings.mPackages.values()) {
4442                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
4443                }
4444            } else {
4445                for (PackageParser.Package pkg : mPackages.values()) {
4446                    PackageSetting ps = (PackageSetting)pkg.mExtras;
4447                    if (ps != null) {
4448                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
4449                                userId);
4450                    }
4451                }
4452            }
4453
4454            return new ParceledListSlice<PackageInfo>(list);
4455        }
4456    }
4457
4458    @Override
4459    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
4460        if (!sUserManager.exists(userId)) return null;
4461        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
4462
4463        // writer
4464        synchronized (mPackages) {
4465            ArrayList<ApplicationInfo> list;
4466            if (listUninstalled) {
4467                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
4468                for (PackageSetting ps : mSettings.mPackages.values()) {
4469                    ApplicationInfo ai;
4470                    if (ps.pkg != null) {
4471                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
4472                                ps.readUserState(userId), userId);
4473                    } else {
4474                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
4475                    }
4476                    if (ai != null) {
4477                        list.add(ai);
4478                    }
4479                }
4480            } else {
4481                list = new ArrayList<ApplicationInfo>(mPackages.size());
4482                for (PackageParser.Package p : mPackages.values()) {
4483                    if (p.mExtras != null) {
4484                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4485                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
4486                        if (ai != null) {
4487                            list.add(ai);
4488                        }
4489                    }
4490                }
4491            }
4492
4493            return new ParceledListSlice<ApplicationInfo>(list);
4494        }
4495    }
4496
4497    public List<ApplicationInfo> getPersistentApplications(int flags) {
4498        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
4499
4500        // reader
4501        synchronized (mPackages) {
4502            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
4503            final int userId = UserHandle.getCallingUserId();
4504            while (i.hasNext()) {
4505                final PackageParser.Package p = i.next();
4506                if (p.applicationInfo != null
4507                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
4508                        && (!mSafeMode || isSystemApp(p))) {
4509                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
4510                    if (ps != null) {
4511                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
4512                                ps.readUserState(userId), userId);
4513                        if (ai != null) {
4514                            finalList.add(ai);
4515                        }
4516                    }
4517                }
4518            }
4519        }
4520
4521        return finalList;
4522    }
4523
4524    @Override
4525    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
4526        if (!sUserManager.exists(userId)) return null;
4527        // reader
4528        synchronized (mPackages) {
4529            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
4530            PackageSetting ps = provider != null
4531                    ? mSettings.mPackages.get(provider.owner.packageName)
4532                    : null;
4533            return ps != null
4534                    && mSettings.isEnabledLPr(provider.info, flags, userId)
4535                    && (!mSafeMode || (provider.info.applicationInfo.flags
4536                            &ApplicationInfo.FLAG_SYSTEM) != 0)
4537                    ? PackageParser.generateProviderInfo(provider, flags,
4538                            ps.readUserState(userId), userId)
4539                    : null;
4540        }
4541    }
4542
4543    /**
4544     * @deprecated
4545     */
4546    @Deprecated
4547    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
4548        // reader
4549        synchronized (mPackages) {
4550            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
4551                    .entrySet().iterator();
4552            final int userId = UserHandle.getCallingUserId();
4553            while (i.hasNext()) {
4554                Map.Entry<String, PackageParser.Provider> entry = i.next();
4555                PackageParser.Provider p = entry.getValue();
4556                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4557
4558                if (ps != null && p.syncable
4559                        && (!mSafeMode || (p.info.applicationInfo.flags
4560                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
4561                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
4562                            ps.readUserState(userId), userId);
4563                    if (info != null) {
4564                        outNames.add(entry.getKey());
4565                        outInfo.add(info);
4566                    }
4567                }
4568            }
4569        }
4570    }
4571
4572    @Override
4573    public List<ProviderInfo> queryContentProviders(String processName,
4574            int uid, int flags) {
4575        ArrayList<ProviderInfo> finalList = null;
4576        // reader
4577        synchronized (mPackages) {
4578            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4579            final int userId = processName != null ?
4580                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4581            while (i.hasNext()) {
4582                final PackageParser.Provider p = i.next();
4583                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4584                if (ps != null && p.info.authority != null
4585                        && (processName == null
4586                                || (p.info.processName.equals(processName)
4587                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4588                        && mSettings.isEnabledLPr(p.info, flags, userId)
4589                        && (!mSafeMode
4590                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4591                    if (finalList == null) {
4592                        finalList = new ArrayList<ProviderInfo>(3);
4593                    }
4594                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4595                            ps.readUserState(userId), userId);
4596                    if (info != null) {
4597                        finalList.add(info);
4598                    }
4599                }
4600            }
4601        }
4602
4603        if (finalList != null) {
4604            Collections.sort(finalList, mProviderInitOrderSorter);
4605        }
4606
4607        return finalList;
4608    }
4609
4610    @Override
4611    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4612            int flags) {
4613        // reader
4614        synchronized (mPackages) {
4615            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4616            return PackageParser.generateInstrumentationInfo(i, flags);
4617        }
4618    }
4619
4620    @Override
4621    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4622            int flags) {
4623        ArrayList<InstrumentationInfo> finalList =
4624            new ArrayList<InstrumentationInfo>();
4625
4626        // reader
4627        synchronized (mPackages) {
4628            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4629            while (i.hasNext()) {
4630                final PackageParser.Instrumentation p = i.next();
4631                if (targetPackage == null
4632                        || targetPackage.equals(p.info.targetPackage)) {
4633                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4634                            flags);
4635                    if (ii != null) {
4636                        finalList.add(ii);
4637                    }
4638                }
4639            }
4640        }
4641
4642        return finalList;
4643    }
4644
4645    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4646        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4647        if (overlays == null) {
4648            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4649            return;
4650        }
4651        for (PackageParser.Package opkg : overlays.values()) {
4652            // Not much to do if idmap fails: we already logged the error
4653            // and we certainly don't want to abort installation of pkg simply
4654            // because an overlay didn't fit properly. For these reasons,
4655            // ignore the return value of createIdmapForPackagePairLI.
4656            createIdmapForPackagePairLI(pkg, opkg);
4657        }
4658    }
4659
4660    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4661            PackageParser.Package opkg) {
4662        if (!opkg.mTrustedOverlay) {
4663            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4664                    opkg.baseCodePath + ": overlay not trusted");
4665            return false;
4666        }
4667        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4668        if (overlaySet == null) {
4669            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4670                    opkg.baseCodePath + " but target package has no known overlays");
4671            return false;
4672        }
4673        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4674        // TODO: generate idmap for split APKs
4675        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4676            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4677                    + opkg.baseCodePath);
4678            return false;
4679        }
4680        PackageParser.Package[] overlayArray =
4681            overlaySet.values().toArray(new PackageParser.Package[0]);
4682        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4683            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4684                return p1.mOverlayPriority - p2.mOverlayPriority;
4685            }
4686        };
4687        Arrays.sort(overlayArray, cmp);
4688
4689        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4690        int i = 0;
4691        for (PackageParser.Package p : overlayArray) {
4692            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4693        }
4694        return true;
4695    }
4696
4697    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4698        final File[] files = dir.listFiles();
4699        if (ArrayUtils.isEmpty(files)) {
4700            Log.d(TAG, "No files in app dir " + dir);
4701            return;
4702        }
4703
4704        if (DEBUG_PACKAGE_SCANNING) {
4705            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4706                    + " flags=0x" + Integer.toHexString(parseFlags));
4707        }
4708
4709        for (File file : files) {
4710            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4711                    && !PackageInstallerService.isStageName(file.getName());
4712            if (!isPackage) {
4713                // Ignore entries which are not packages
4714                continue;
4715            }
4716            try {
4717                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4718                        scanFlags, currentTime, null);
4719            } catch (PackageManagerException e) {
4720                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4721
4722                // Delete invalid userdata apps
4723                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4724                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4725                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4726                    if (file.isDirectory()) {
4727                        mInstaller.rmPackageDir(file.getAbsolutePath());
4728                    } else {
4729                        file.delete();
4730                    }
4731                }
4732            }
4733        }
4734    }
4735
4736    private static File getSettingsProblemFile() {
4737        File dataDir = Environment.getDataDirectory();
4738        File systemDir = new File(dataDir, "system");
4739        File fname = new File(systemDir, "uiderrors.txt");
4740        return fname;
4741    }
4742
4743    static void reportSettingsProblem(int priority, String msg) {
4744        logCriticalInfo(priority, msg);
4745    }
4746
4747    static void logCriticalInfo(int priority, String msg) {
4748        Slog.println(priority, TAG, msg);
4749        EventLogTags.writePmCriticalInfo(msg);
4750        try {
4751            File fname = getSettingsProblemFile();
4752            FileOutputStream out = new FileOutputStream(fname, true);
4753            PrintWriter pw = new FastPrintWriter(out);
4754            SimpleDateFormat formatter = new SimpleDateFormat();
4755            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4756            pw.println(dateString + ": " + msg);
4757            pw.close();
4758            FileUtils.setPermissions(
4759                    fname.toString(),
4760                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4761                    -1, -1);
4762        } catch (java.io.IOException e) {
4763        }
4764    }
4765
4766    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4767            PackageParser.Package pkg, File srcFile, int parseFlags)
4768            throws PackageManagerException {
4769        if (ps != null
4770                && ps.codePath.equals(srcFile)
4771                && ps.timeStamp == srcFile.lastModified()
4772                && !isCompatSignatureUpdateNeeded(pkg)
4773                && !isRecoverSignatureUpdateNeeded(pkg)) {
4774            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4775            if (ps.signatures.mSignatures != null
4776                    && ps.signatures.mSignatures.length != 0
4777                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4778                // Optimization: reuse the existing cached certificates
4779                // if the package appears to be unchanged.
4780                pkg.mSignatures = ps.signatures.mSignatures;
4781                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4782                synchronized (mPackages) {
4783                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4784                }
4785                return;
4786            }
4787
4788            Slog.w(TAG, "PackageSetting for " + ps.name
4789                    + " is missing signatures.  Collecting certs again to recover them.");
4790        } else {
4791            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4792        }
4793
4794        try {
4795            pp.collectCertificates(pkg, parseFlags);
4796            pp.collectManifestDigest(pkg);
4797        } catch (PackageParserException e) {
4798            throw PackageManagerException.from(e);
4799        }
4800    }
4801
4802    /*
4803     *  Scan a package and return the newly parsed package.
4804     *  Returns null in case of errors and the error code is stored in mLastScanError
4805     */
4806    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4807            long currentTime, UserHandle user) throws PackageManagerException {
4808        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4809        parseFlags |= mDefParseFlags;
4810        PackageParser pp = new PackageParser();
4811        pp.setSeparateProcesses(mSeparateProcesses);
4812        pp.setOnlyCoreApps(mOnlyCore);
4813        pp.setDisplayMetrics(mMetrics);
4814
4815        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4816            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4817        }
4818
4819        final PackageParser.Package pkg;
4820        try {
4821            pkg = pp.parsePackage(scanFile, parseFlags);
4822        } catch (PackageParserException e) {
4823            throw PackageManagerException.from(e);
4824        }
4825
4826        PackageSetting ps = null;
4827        PackageSetting updatedPkg;
4828        // reader
4829        synchronized (mPackages) {
4830            // Look to see if we already know about this package.
4831            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4832            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4833                // This package has been renamed to its original name.  Let's
4834                // use that.
4835                ps = mSettings.peekPackageLPr(oldName);
4836            }
4837            // If there was no original package, see one for the real package name.
4838            if (ps == null) {
4839                ps = mSettings.peekPackageLPr(pkg.packageName);
4840            }
4841            // Check to see if this package could be hiding/updating a system
4842            // package.  Must look for it either under the original or real
4843            // package name depending on our state.
4844            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4845            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4846        }
4847        boolean updatedPkgBetter = false;
4848        // First check if this is a system package that may involve an update
4849        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4850            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4851            // it needs to drop FLAG_PRIVILEGED.
4852            if (locationIsPrivileged(scanFile)) {
4853                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4854            } else {
4855                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4856            }
4857
4858            if (ps != null && !ps.codePath.equals(scanFile)) {
4859                // The path has changed from what was last scanned...  check the
4860                // version of the new path against what we have stored to determine
4861                // what to do.
4862                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4863                if (pkg.mVersionCode <= ps.versionCode) {
4864                    // The system package has been updated and the code path does not match
4865                    // Ignore entry. Skip it.
4866                    Slog.i(TAG, "Package " + ps.name + " at " + scanFile
4867                            + " ignored: updated version " + ps.versionCode
4868                            + " better than this " + pkg.mVersionCode);
4869                    if (!updatedPkg.codePath.equals(scanFile)) {
4870                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4871                                + ps.name + " changing from " + updatedPkg.codePathString
4872                                + " to " + scanFile);
4873                        updatedPkg.codePath = scanFile;
4874                        updatedPkg.codePathString = scanFile.toString();
4875                        updatedPkg.resourcePath = scanFile;
4876                        updatedPkg.resourcePathString = scanFile.toString();
4877                    }
4878                    updatedPkg.pkg = pkg;
4879                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4880                } else {
4881                    // The current app on the system partition is better than
4882                    // what we have updated to on the data partition; switch
4883                    // back to the system partition version.
4884                    // At this point, its safely assumed that package installation for
4885                    // apps in system partition will go through. If not there won't be a working
4886                    // version of the app
4887                    // writer
4888                    synchronized (mPackages) {
4889                        // Just remove the loaded entries from package lists.
4890                        mPackages.remove(ps.name);
4891                    }
4892
4893                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4894                            + " reverting from " + ps.codePathString
4895                            + ": new version " + pkg.mVersionCode
4896                            + " better than installed " + ps.versionCode);
4897
4898                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4899                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4900                            getAppDexInstructionSets(ps));
4901                    synchronized (mInstallLock) {
4902                        args.cleanUpResourcesLI();
4903                    }
4904                    synchronized (mPackages) {
4905                        mSettings.enableSystemPackageLPw(ps.name);
4906                    }
4907                    updatedPkgBetter = true;
4908                }
4909            }
4910        }
4911
4912        if (updatedPkg != null) {
4913            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4914            // initially
4915            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4916
4917            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4918            // flag set initially
4919            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4920                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4921            }
4922        }
4923
4924        // Verify certificates against what was last scanned
4925        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4926
4927        /*
4928         * A new system app appeared, but we already had a non-system one of the
4929         * same name installed earlier.
4930         */
4931        boolean shouldHideSystemApp = false;
4932        if (updatedPkg == null && ps != null
4933                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4934            /*
4935             * Check to make sure the signatures match first. If they don't,
4936             * wipe the installed application and its data.
4937             */
4938            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4939                    != PackageManager.SIGNATURE_MATCH) {
4940                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4941                        + " signatures don't match existing userdata copy; removing");
4942                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4943                ps = null;
4944            } else {
4945                /*
4946                 * If the newly-added system app is an older version than the
4947                 * already installed version, hide it. It will be scanned later
4948                 * and re-added like an update.
4949                 */
4950                if (pkg.mVersionCode <= ps.versionCode) {
4951                    shouldHideSystemApp = true;
4952                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4953                            + " but new version " + pkg.mVersionCode + " better than installed "
4954                            + ps.versionCode + "; hiding system");
4955                } else {
4956                    /*
4957                     * The newly found system app is a newer version that the
4958                     * one previously installed. Simply remove the
4959                     * already-installed application and replace it with our own
4960                     * while keeping the application data.
4961                     */
4962                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4963                            + " reverting from " + ps.codePathString + ": new version "
4964                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4965                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4966                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4967                            getAppDexInstructionSets(ps));
4968                    synchronized (mInstallLock) {
4969                        args.cleanUpResourcesLI();
4970                    }
4971                }
4972            }
4973        }
4974
4975        // The apk is forward locked (not public) if its code and resources
4976        // are kept in different files. (except for app in either system or
4977        // vendor path).
4978        // TODO grab this value from PackageSettings
4979        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4980            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4981                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4982            }
4983        }
4984
4985        // TODO: extend to support forward-locked splits
4986        String resourcePath = null;
4987        String baseResourcePath = null;
4988        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4989            if (ps != null && ps.resourcePathString != null) {
4990                resourcePath = ps.resourcePathString;
4991                baseResourcePath = ps.resourcePathString;
4992            } else {
4993                // Should not happen at all. Just log an error.
4994                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4995            }
4996        } else {
4997            resourcePath = pkg.codePath;
4998            baseResourcePath = pkg.baseCodePath;
4999        }
5000
5001        // Set application objects path explicitly.
5002        pkg.applicationInfo.setCodePath(pkg.codePath);
5003        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
5004        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
5005        pkg.applicationInfo.setResourcePath(resourcePath);
5006        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
5007        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
5008
5009        // Note that we invoke the following method only if we are about to unpack an application
5010        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
5011                | SCAN_UPDATE_SIGNATURE, currentTime, user);
5012
5013        /*
5014         * If the system app should be overridden by a previously installed
5015         * data, hide the system app now and let the /data/app scan pick it up
5016         * again.
5017         */
5018        if (shouldHideSystemApp) {
5019            synchronized (mPackages) {
5020                /*
5021                 * We have to grant systems permissions before we hide, because
5022                 * grantPermissions will assume the package update is trying to
5023                 * expand its permissions.
5024                 */
5025                grantPermissionsLPw(pkg, true, pkg.packageName);
5026                mSettings.disableSystemPackageLPw(pkg.packageName);
5027            }
5028        }
5029
5030        return scannedPkg;
5031    }
5032
5033    private static String fixProcessName(String defProcessName,
5034            String processName, int uid) {
5035        if (processName == null) {
5036            return defProcessName;
5037        }
5038        return processName;
5039    }
5040
5041    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
5042            throws PackageManagerException {
5043        if (pkgSetting.signatures.mSignatures != null) {
5044            // Already existing package. Make sure signatures match
5045            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
5046                    == PackageManager.SIGNATURE_MATCH;
5047            if (!match) {
5048                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
5049                        == PackageManager.SIGNATURE_MATCH;
5050            }
5051            if (!match) {
5052                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
5053                        == PackageManager.SIGNATURE_MATCH;
5054            }
5055            if (!match) {
5056                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5057                        + pkg.packageName + " signatures do not match the "
5058                        + "previously installed version; ignoring!");
5059            }
5060        }
5061
5062        // Check for shared user signatures
5063        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
5064            // Already existing package. Make sure signatures match
5065            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5066                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
5067            if (!match) {
5068                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
5069                        == PackageManager.SIGNATURE_MATCH;
5070            }
5071            if (!match) {
5072                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
5073                        == PackageManager.SIGNATURE_MATCH;
5074            }
5075            if (!match) {
5076                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
5077                        "Package " + pkg.packageName
5078                        + " has no signatures that match those in shared user "
5079                        + pkgSetting.sharedUser.name + "; ignoring!");
5080            }
5081        }
5082    }
5083
5084    /**
5085     * Enforces that only the system UID or root's UID can call a method exposed
5086     * via Binder.
5087     *
5088     * @param message used as message if SecurityException is thrown
5089     * @throws SecurityException if the caller is not system or root
5090     */
5091    private static final void enforceSystemOrRoot(String message) {
5092        final int uid = Binder.getCallingUid();
5093        if (uid != Process.SYSTEM_UID && uid != 0) {
5094            throw new SecurityException(message);
5095        }
5096    }
5097
5098    @Override
5099    public void performBootDexOpt() {
5100        enforceSystemOrRoot("Only the system can request dexopt be performed");
5101
5102        // Before everything else, see whether we need to fstrim.
5103        try {
5104            IMountService ms = PackageHelper.getMountService();
5105            if (ms != null) {
5106                final boolean isUpgrade = isUpgrade();
5107                boolean doTrim = isUpgrade;
5108                if (doTrim) {
5109                    Slog.w(TAG, "Running disk maintenance immediately due to system update");
5110                } else {
5111                    final long interval = android.provider.Settings.Global.getLong(
5112                            mContext.getContentResolver(),
5113                            android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL,
5114                            DEFAULT_MANDATORY_FSTRIM_INTERVAL);
5115                    if (interval > 0) {
5116                        final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance();
5117                        if (timeSinceLast > interval) {
5118                            doTrim = true;
5119                            Slog.w(TAG, "No disk maintenance in " + timeSinceLast
5120                                    + "; running immediately");
5121                        }
5122                    }
5123                }
5124                if (doTrim) {
5125                    if (!isFirstBoot()) {
5126                        try {
5127                            ActivityManagerNative.getDefault().showBootMessage(
5128                                    mContext.getResources().getString(
5129                                            R.string.android_upgrading_fstrim), true);
5130                        } catch (RemoteException e) {
5131                        }
5132                    }
5133                    ms.runMaintenance();
5134                }
5135            } else {
5136                Slog.e(TAG, "Mount service unavailable!");
5137            }
5138        } catch (RemoteException e) {
5139            // Can't happen; MountService is local
5140        }
5141
5142        final ArraySet<PackageParser.Package> pkgs;
5143        synchronized (mPackages) {
5144            pkgs = mPackageDexOptimizer.clearDeferredDexOptPackages();
5145        }
5146
5147        if (pkgs != null) {
5148            // Sort apps by importance for dexopt ordering. Important apps are given more priority
5149            // in case the device runs out of space.
5150            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
5151            // Give priority to core apps.
5152            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5153                PackageParser.Package pkg = it.next();
5154                if (pkg.coreApp) {
5155                    if (DEBUG_DEXOPT) {
5156                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
5157                    }
5158                    sortedPkgs.add(pkg);
5159                    it.remove();
5160                }
5161            }
5162            // Give priority to system apps that listen for pre boot complete.
5163            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
5164            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
5165            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5166                PackageParser.Package pkg = it.next();
5167                if (pkgNames.contains(pkg.packageName)) {
5168                    if (DEBUG_DEXOPT) {
5169                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
5170                    }
5171                    sortedPkgs.add(pkg);
5172                    it.remove();
5173                }
5174            }
5175            // Give priority to system apps.
5176            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5177                PackageParser.Package pkg = it.next();
5178                if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
5179                    if (DEBUG_DEXOPT) {
5180                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
5181                    }
5182                    sortedPkgs.add(pkg);
5183                    it.remove();
5184                }
5185            }
5186            // Give priority to updated system apps.
5187            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5188                PackageParser.Package pkg = it.next();
5189                if (pkg.isUpdatedSystemApp()) {
5190                    if (DEBUG_DEXOPT) {
5191                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
5192                    }
5193                    sortedPkgs.add(pkg);
5194                    it.remove();
5195                }
5196            }
5197            // Give priority to apps that listen for boot complete.
5198            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
5199            pkgNames = getPackageNamesForIntent(intent);
5200            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
5201                PackageParser.Package pkg = it.next();
5202                if (pkgNames.contains(pkg.packageName)) {
5203                    if (DEBUG_DEXOPT) {
5204                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
5205                    }
5206                    sortedPkgs.add(pkg);
5207                    it.remove();
5208                }
5209            }
5210            // Filter out packages that aren't recently used.
5211            filterRecentlyUsedApps(pkgs);
5212            // Add all remaining apps.
5213            for (PackageParser.Package pkg : pkgs) {
5214                if (DEBUG_DEXOPT) {
5215                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
5216                }
5217                sortedPkgs.add(pkg);
5218            }
5219
5220            // If we want to be lazy, filter everything that wasn't recently used.
5221            if (mLazyDexOpt) {
5222                filterRecentlyUsedApps(sortedPkgs);
5223            }
5224
5225            int i = 0;
5226            int total = sortedPkgs.size();
5227            File dataDir = Environment.getDataDirectory();
5228            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
5229            if (lowThreshold == 0) {
5230                throw new IllegalStateException("Invalid low memory threshold");
5231            }
5232            for (PackageParser.Package pkg : sortedPkgs) {
5233                long usableSpace = dataDir.getUsableSpace();
5234                if (usableSpace < lowThreshold) {
5235                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
5236                    break;
5237                }
5238                performBootDexOpt(pkg, ++i, total);
5239            }
5240        }
5241    }
5242
5243    private void filterRecentlyUsedApps(Collection<PackageParser.Package> pkgs) {
5244        // Filter out packages that aren't recently used.
5245        //
5246        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
5247        // should do a full dexopt.
5248        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
5249            int total = pkgs.size();
5250            int skipped = 0;
5251            long now = System.currentTimeMillis();
5252            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
5253                PackageParser.Package pkg = i.next();
5254                long then = pkg.mLastPackageUsageTimeInMills;
5255                if (then + mDexOptLRUThresholdInMills < now) {
5256                    if (DEBUG_DEXOPT) {
5257                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
5258                              ((then == 0) ? "never" : new Date(then)));
5259                    }
5260                    i.remove();
5261                    skipped++;
5262                }
5263            }
5264            if (DEBUG_DEXOPT) {
5265                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
5266            }
5267        }
5268    }
5269
5270    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
5271        List<ResolveInfo> ris = null;
5272        try {
5273            ris = AppGlobals.getPackageManager().queryIntentReceivers(
5274                    intent, null, 0, UserHandle.USER_OWNER);
5275        } catch (RemoteException e) {
5276        }
5277        ArraySet<String> pkgNames = new ArraySet<String>();
5278        if (ris != null) {
5279            for (ResolveInfo ri : ris) {
5280                pkgNames.add(ri.activityInfo.packageName);
5281            }
5282        }
5283        return pkgNames;
5284    }
5285
5286    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
5287        if (DEBUG_DEXOPT) {
5288            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
5289        }
5290        if (!isFirstBoot()) {
5291            try {
5292                ActivityManagerNative.getDefault().showBootMessage(
5293                        mContext.getResources().getString(R.string.android_upgrading_apk,
5294                                curr, total), true);
5295            } catch (RemoteException e) {
5296            }
5297        }
5298        PackageParser.Package p = pkg;
5299        synchronized (mInstallLock) {
5300            mPackageDexOptimizer.performDexOpt(p, null /* instruction sets */,
5301                    false /* force dex */, false /* defer */, true /* include dependencies */);
5302        }
5303    }
5304
5305    @Override
5306    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
5307        return performDexOpt(packageName, instructionSet, false);
5308    }
5309
5310    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
5311        boolean dexopt = mLazyDexOpt || backgroundDexopt;
5312        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
5313        if (!dexopt && !updateUsage) {
5314            // We aren't going to dexopt or update usage, so bail early.
5315            return false;
5316        }
5317        PackageParser.Package p;
5318        final String targetInstructionSet;
5319        synchronized (mPackages) {
5320            p = mPackages.get(packageName);
5321            if (p == null) {
5322                return false;
5323            }
5324            if (updateUsage) {
5325                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
5326            }
5327            mPackageUsage.write(false);
5328            if (!dexopt) {
5329                // We aren't going to dexopt, so bail early.
5330                return false;
5331            }
5332
5333            targetInstructionSet = instructionSet != null ? instructionSet :
5334                    getPrimaryInstructionSet(p.applicationInfo);
5335            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
5336                return false;
5337            }
5338        }
5339
5340        synchronized (mInstallLock) {
5341            final String[] instructionSets = new String[] { targetInstructionSet };
5342            int result = mPackageDexOptimizer.performDexOpt(p, instructionSets,
5343                    false /* forceDex */, false /* defer */, true /* inclDependencies */);
5344            return result == PackageDexOptimizer.DEX_OPT_PERFORMED;
5345        }
5346    }
5347
5348    public ArraySet<String> getPackagesThatNeedDexOpt() {
5349        ArraySet<String> pkgs = null;
5350        synchronized (mPackages) {
5351            for (PackageParser.Package p : mPackages.values()) {
5352                if (DEBUG_DEXOPT) {
5353                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
5354                }
5355                if (!p.mDexOptPerformed.isEmpty()) {
5356                    continue;
5357                }
5358                if (pkgs == null) {
5359                    pkgs = new ArraySet<String>();
5360                }
5361                pkgs.add(p.packageName);
5362            }
5363        }
5364        return pkgs;
5365    }
5366
5367    public void shutdown() {
5368        mPackageUsage.write(true);
5369    }
5370
5371    @Override
5372    public void forceDexOpt(String packageName) {
5373        enforceSystemOrRoot("forceDexOpt");
5374
5375        PackageParser.Package pkg;
5376        synchronized (mPackages) {
5377            pkg = mPackages.get(packageName);
5378            if (pkg == null) {
5379                throw new IllegalArgumentException("Missing package: " + packageName);
5380            }
5381        }
5382
5383        synchronized (mInstallLock) {
5384            final String[] instructionSets = new String[] {
5385                    getPrimaryInstructionSet(pkg.applicationInfo) };
5386            final int res = mPackageDexOptimizer.performDexOpt(pkg, instructionSets,
5387                    true /*forceDex*/, false /* defer */, true /* inclDependencies */);
5388            if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) {
5389                throw new IllegalStateException("Failed to dexopt: " + res);
5390            }
5391        }
5392    }
5393
5394    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5395        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5396            Slog.w(TAG, "Unable to update from " + oldPkg.name
5397                    + " to " + newPkg.packageName
5398                    + ": old package not in system partition");
5399            return false;
5400        } else if (mPackages.get(oldPkg.name) != null) {
5401            Slog.w(TAG, "Unable to update from " + oldPkg.name
5402                    + " to " + newPkg.packageName
5403                    + ": old package still exists");
5404            return false;
5405        }
5406        return true;
5407    }
5408
5409    private File getDataPathForPackage(String packageName, int userId) {
5410        /*
5411         * Until we fully support multiple users, return the directory we
5412         * previously would have. The PackageManagerTests will need to be
5413         * revised when this is changed back..
5414         */
5415        if (userId == 0) {
5416            return new File(mAppDataDir, packageName);
5417        } else {
5418            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5419                + File.separator + packageName);
5420        }
5421    }
5422
5423    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5424        int[] users = sUserManager.getUserIds();
5425        int res = mInstaller.install(packageName, uid, uid, seinfo);
5426        if (res < 0) {
5427            return res;
5428        }
5429        for (int user : users) {
5430            if (user != 0) {
5431                res = mInstaller.createUserData(packageName,
5432                        UserHandle.getUid(user, uid), user, seinfo);
5433                if (res < 0) {
5434                    return res;
5435                }
5436            }
5437        }
5438        return res;
5439    }
5440
5441    private int removeDataDirsLI(String packageName) {
5442        int[] users = sUserManager.getUserIds();
5443        int res = 0;
5444        for (int user : users) {
5445            int resInner = mInstaller.remove(packageName, user);
5446            if (resInner < 0) {
5447                res = resInner;
5448            }
5449        }
5450
5451        return res;
5452    }
5453
5454    private int deleteCodeCacheDirsLI(String packageName) {
5455        int[] users = sUserManager.getUserIds();
5456        int res = 0;
5457        for (int user : users) {
5458            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5459            if (resInner < 0) {
5460                res = resInner;
5461            }
5462        }
5463        return res;
5464    }
5465
5466    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5467            PackageParser.Package changingLib) {
5468        if (file.path != null) {
5469            usesLibraryFiles.add(file.path);
5470            return;
5471        }
5472        PackageParser.Package p = mPackages.get(file.apk);
5473        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5474            // If we are doing this while in the middle of updating a library apk,
5475            // then we need to make sure to use that new apk for determining the
5476            // dependencies here.  (We haven't yet finished committing the new apk
5477            // to the package manager state.)
5478            if (p == null || p.packageName.equals(changingLib.packageName)) {
5479                p = changingLib;
5480            }
5481        }
5482        if (p != null) {
5483            usesLibraryFiles.addAll(p.getAllCodePaths());
5484        }
5485    }
5486
5487    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5488            PackageParser.Package changingLib) throws PackageManagerException {
5489        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5490            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5491            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5492            for (int i=0; i<N; i++) {
5493                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5494                if (file == null) {
5495                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5496                            "Package " + pkg.packageName + " requires unavailable shared library "
5497                            + pkg.usesLibraries.get(i) + "; failing!");
5498                }
5499                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5500            }
5501            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5502            for (int i=0; i<N; i++) {
5503                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5504                if (file == null) {
5505                    Slog.w(TAG, "Package " + pkg.packageName
5506                            + " desires unavailable shared library "
5507                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5508                } else {
5509                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5510                }
5511            }
5512            N = usesLibraryFiles.size();
5513            if (N > 0) {
5514                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5515            } else {
5516                pkg.usesLibraryFiles = null;
5517            }
5518        }
5519    }
5520
5521    private static boolean hasString(List<String> list, List<String> which) {
5522        if (list == null) {
5523            return false;
5524        }
5525        for (int i=list.size()-1; i>=0; i--) {
5526            for (int j=which.size()-1; j>=0; j--) {
5527                if (which.get(j).equals(list.get(i))) {
5528                    return true;
5529                }
5530            }
5531        }
5532        return false;
5533    }
5534
5535    private void updateAllSharedLibrariesLPw() {
5536        for (PackageParser.Package pkg : mPackages.values()) {
5537            try {
5538                updateSharedLibrariesLPw(pkg, null);
5539            } catch (PackageManagerException e) {
5540                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5541            }
5542        }
5543    }
5544
5545    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5546            PackageParser.Package changingPkg) {
5547        ArrayList<PackageParser.Package> res = null;
5548        for (PackageParser.Package pkg : mPackages.values()) {
5549            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5550                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5551                if (res == null) {
5552                    res = new ArrayList<PackageParser.Package>();
5553                }
5554                res.add(pkg);
5555                try {
5556                    updateSharedLibrariesLPw(pkg, changingPkg);
5557                } catch (PackageManagerException e) {
5558                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5559                }
5560            }
5561        }
5562        return res;
5563    }
5564
5565    /**
5566     * Derive the value of the {@code cpuAbiOverride} based on the provided
5567     * value and an optional stored value from the package settings.
5568     */
5569    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5570        String cpuAbiOverride = null;
5571
5572        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5573            cpuAbiOverride = null;
5574        } else if (abiOverride != null) {
5575            cpuAbiOverride = abiOverride;
5576        } else if (settings != null) {
5577            cpuAbiOverride = settings.cpuAbiOverrideString;
5578        }
5579
5580        return cpuAbiOverride;
5581    }
5582
5583    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5584            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5585        boolean success = false;
5586        try {
5587            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5588                    currentTime, user);
5589            success = true;
5590            return res;
5591        } finally {
5592            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5593                removeDataDirsLI(pkg.packageName);
5594            }
5595        }
5596    }
5597
5598    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5599            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5600        final File scanFile = new File(pkg.codePath);
5601        if (pkg.applicationInfo.getCodePath() == null ||
5602                pkg.applicationInfo.getResourcePath() == null) {
5603            // Bail out. The resource and code paths haven't been set.
5604            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5605                    "Code and resource paths haven't been set correctly");
5606        }
5607
5608        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5609            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5610        } else {
5611            // Only allow system apps to be flagged as core apps.
5612            pkg.coreApp = false;
5613        }
5614
5615        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5616            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5617        }
5618
5619        if (mCustomResolverComponentName != null &&
5620                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5621            setUpCustomResolverActivity(pkg);
5622        }
5623
5624        if (pkg.packageName.equals("android")) {
5625            synchronized (mPackages) {
5626                if (mAndroidApplication != null) {
5627                    Slog.w(TAG, "*************************************************");
5628                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5629                    Slog.w(TAG, " file=" + scanFile);
5630                    Slog.w(TAG, "*************************************************");
5631                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5632                            "Core android package being redefined.  Skipping.");
5633                }
5634
5635                // Set up information for our fall-back user intent resolution activity.
5636                mPlatformPackage = pkg;
5637                pkg.mVersionCode = mSdkVersion;
5638                mAndroidApplication = pkg.applicationInfo;
5639
5640                if (!mResolverReplaced) {
5641                    mResolveActivity.applicationInfo = mAndroidApplication;
5642                    mResolveActivity.name = ResolverActivity.class.getName();
5643                    mResolveActivity.packageName = mAndroidApplication.packageName;
5644                    mResolveActivity.processName = "system:ui";
5645                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5646                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5647                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5648                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5649                    mResolveActivity.exported = true;
5650                    mResolveActivity.enabled = true;
5651                    mResolveInfo.activityInfo = mResolveActivity;
5652                    mResolveInfo.priority = 0;
5653                    mResolveInfo.preferredOrder = 0;
5654                    mResolveInfo.match = 0;
5655                    mResolveComponentName = new ComponentName(
5656                            mAndroidApplication.packageName, mResolveActivity.name);
5657                }
5658            }
5659        }
5660
5661        if (DEBUG_PACKAGE_SCANNING) {
5662            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5663                Log.d(TAG, "Scanning package " + pkg.packageName);
5664        }
5665
5666        if (mPackages.containsKey(pkg.packageName)
5667                || mSharedLibraries.containsKey(pkg.packageName)) {
5668            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5669                    "Application package " + pkg.packageName
5670                    + " already installed.  Skipping duplicate.");
5671        }
5672
5673        // If we're only installing presumed-existing packages, require that the
5674        // scanned APK is both already known and at the path previously established
5675        // for it.  Previously unknown packages we pick up normally, but if we have an
5676        // a priori expectation about this package's install presence, enforce it.
5677        if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) {
5678            PackageSetting known = mSettings.peekPackageLPr(pkg.packageName);
5679            if (known != null) {
5680                if (DEBUG_PACKAGE_SCANNING) {
5681                    Log.d(TAG, "Examining " + pkg.codePath
5682                            + " and requiring known paths " + known.codePathString
5683                            + " & " + known.resourcePathString);
5684                }
5685                if (!pkg.applicationInfo.getCodePath().equals(known.codePathString)
5686                        || !pkg.applicationInfo.getResourcePath().equals(known.resourcePathString)) {
5687                    throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED,
5688                            "Application package " + pkg.packageName
5689                            + " found at " + pkg.applicationInfo.getCodePath()
5690                            + " but expected at " + known.codePathString + "; ignoring.");
5691                }
5692            }
5693        }
5694
5695        // Initialize package source and resource directories
5696        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5697        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5698
5699        SharedUserSetting suid = null;
5700        PackageSetting pkgSetting = null;
5701
5702        if (!isSystemApp(pkg)) {
5703            // Only system apps can use these features.
5704            pkg.mOriginalPackages = null;
5705            pkg.mRealPackage = null;
5706            pkg.mAdoptPermissions = null;
5707        }
5708
5709        // writer
5710        synchronized (mPackages) {
5711            if (pkg.mSharedUserId != null) {
5712                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5713                if (suid == null) {
5714                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5715                            "Creating application package " + pkg.packageName
5716                            + " for shared user failed");
5717                }
5718                if (DEBUG_PACKAGE_SCANNING) {
5719                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5720                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5721                                + "): packages=" + suid.packages);
5722                }
5723            }
5724
5725            // Check if we are renaming from an original package name.
5726            PackageSetting origPackage = null;
5727            String realName = null;
5728            if (pkg.mOriginalPackages != null) {
5729                // This package may need to be renamed to a previously
5730                // installed name.  Let's check on that...
5731                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5732                if (pkg.mOriginalPackages.contains(renamed)) {
5733                    // This package had originally been installed as the
5734                    // original name, and we have already taken care of
5735                    // transitioning to the new one.  Just update the new
5736                    // one to continue using the old name.
5737                    realName = pkg.mRealPackage;
5738                    if (!pkg.packageName.equals(renamed)) {
5739                        // Callers into this function may have already taken
5740                        // care of renaming the package; only do it here if
5741                        // it is not already done.
5742                        pkg.setPackageName(renamed);
5743                    }
5744
5745                } else {
5746                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5747                        if ((origPackage = mSettings.peekPackageLPr(
5748                                pkg.mOriginalPackages.get(i))) != null) {
5749                            // We do have the package already installed under its
5750                            // original name...  should we use it?
5751                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5752                                // New package is not compatible with original.
5753                                origPackage = null;
5754                                continue;
5755                            } else if (origPackage.sharedUser != null) {
5756                                // Make sure uid is compatible between packages.
5757                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5758                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5759                                            + " to " + pkg.packageName + ": old uid "
5760                                            + origPackage.sharedUser.name
5761                                            + " differs from " + pkg.mSharedUserId);
5762                                    origPackage = null;
5763                                    continue;
5764                                }
5765                            } else {
5766                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5767                                        + pkg.packageName + " to old name " + origPackage.name);
5768                            }
5769                            break;
5770                        }
5771                    }
5772                }
5773            }
5774
5775            if (mTransferedPackages.contains(pkg.packageName)) {
5776                Slog.w(TAG, "Package " + pkg.packageName
5777                        + " was transferred to another, but its .apk remains");
5778            }
5779
5780            // Just create the setting, don't add it yet. For already existing packages
5781            // the PkgSetting exists already and doesn't have to be created.
5782            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5783                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5784                    pkg.applicationInfo.primaryCpuAbi,
5785                    pkg.applicationInfo.secondaryCpuAbi,
5786                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5787                    user, false);
5788            if (pkgSetting == null) {
5789                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5790                        "Creating application package " + pkg.packageName + " failed");
5791            }
5792
5793            if (pkgSetting.origPackage != null) {
5794                // If we are first transitioning from an original package,
5795                // fix up the new package's name now.  We need to do this after
5796                // looking up the package under its new name, so getPackageLP
5797                // can take care of fiddling things correctly.
5798                pkg.setPackageName(origPackage.name);
5799
5800                // File a report about this.
5801                String msg = "New package " + pkgSetting.realName
5802                        + " renamed to replace old package " + pkgSetting.name;
5803                reportSettingsProblem(Log.WARN, msg);
5804
5805                // Make a note of it.
5806                mTransferedPackages.add(origPackage.name);
5807
5808                // No longer need to retain this.
5809                pkgSetting.origPackage = null;
5810            }
5811
5812            if (realName != null) {
5813                // Make a note of it.
5814                mTransferedPackages.add(pkg.packageName);
5815            }
5816
5817            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5818                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5819            }
5820
5821            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5822                // Check all shared libraries and map to their actual file path.
5823                // We only do this here for apps not on a system dir, because those
5824                // are the only ones that can fail an install due to this.  We
5825                // will take care of the system apps by updating all of their
5826                // library paths after the scan is done.
5827                updateSharedLibrariesLPw(pkg, null);
5828            }
5829
5830            if (mFoundPolicyFile) {
5831                SELinuxMMAC.assignSeinfoValue(pkg);
5832            }
5833
5834            pkg.applicationInfo.uid = pkgSetting.appId;
5835            pkg.mExtras = pkgSetting;
5836            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5837                try {
5838                    verifySignaturesLP(pkgSetting, pkg);
5839                    // We just determined the app is signed correctly, so bring
5840                    // over the latest parsed certs.
5841                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5842                } catch (PackageManagerException e) {
5843                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5844                        throw e;
5845                    }
5846                    // The signature has changed, but this package is in the system
5847                    // image...  let's recover!
5848                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5849                    // However...  if this package is part of a shared user, but it
5850                    // doesn't match the signature of the shared user, let's fail.
5851                    // What this means is that you can't change the signatures
5852                    // associated with an overall shared user, which doesn't seem all
5853                    // that unreasonable.
5854                    if (pkgSetting.sharedUser != null) {
5855                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5856                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5857                            throw new PackageManagerException(
5858                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5859                                            "Signature mismatch for shared user : "
5860                                            + pkgSetting.sharedUser);
5861                        }
5862                    }
5863                    // File a report about this.
5864                    String msg = "System package " + pkg.packageName
5865                        + " signature changed; retaining data.";
5866                    reportSettingsProblem(Log.WARN, msg);
5867                }
5868            } else {
5869                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5870                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5871                            + pkg.packageName + " upgrade keys do not match the "
5872                            + "previously installed version");
5873                } else {
5874                    // We just determined the app is signed correctly, so bring
5875                    // over the latest parsed certs.
5876                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5877                }
5878            }
5879            // Verify that this new package doesn't have any content providers
5880            // that conflict with existing packages.  Only do this if the
5881            // package isn't already installed, since we don't want to break
5882            // things that are installed.
5883            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5884                final int N = pkg.providers.size();
5885                int i;
5886                for (i=0; i<N; i++) {
5887                    PackageParser.Provider p = pkg.providers.get(i);
5888                    if (p.info.authority != null) {
5889                        String names[] = p.info.authority.split(";");
5890                        for (int j = 0; j < names.length; j++) {
5891                            if (mProvidersByAuthority.containsKey(names[j])) {
5892                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5893                                final String otherPackageName =
5894                                        ((other != null && other.getComponentName() != null) ?
5895                                                other.getComponentName().getPackageName() : "?");
5896                                throw new PackageManagerException(
5897                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5898                                                "Can't install because provider name " + names[j]
5899                                                + " (in package " + pkg.applicationInfo.packageName
5900                                                + ") is already used by " + otherPackageName);
5901                            }
5902                        }
5903                    }
5904                }
5905            }
5906
5907            if (pkg.mAdoptPermissions != null) {
5908                // This package wants to adopt ownership of permissions from
5909                // another package.
5910                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5911                    final String origName = pkg.mAdoptPermissions.get(i);
5912                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5913                    if (orig != null) {
5914                        if (verifyPackageUpdateLPr(orig, pkg)) {
5915                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5916                                    + pkg.packageName);
5917                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5918                        }
5919                    }
5920                }
5921            }
5922        }
5923
5924        final String pkgName = pkg.packageName;
5925
5926        final long scanFileTime = scanFile.lastModified();
5927        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5928        pkg.applicationInfo.processName = fixProcessName(
5929                pkg.applicationInfo.packageName,
5930                pkg.applicationInfo.processName,
5931                pkg.applicationInfo.uid);
5932
5933        File dataPath;
5934        if (mPlatformPackage == pkg) {
5935            // The system package is special.
5936            dataPath = new File(Environment.getDataDirectory(), "system");
5937
5938            pkg.applicationInfo.dataDir = dataPath.getPath();
5939
5940        } else {
5941            // This is a normal package, need to make its data directory.
5942            dataPath = getDataPathForPackage(pkg.packageName, 0);
5943
5944            boolean uidError = false;
5945            if (dataPath.exists()) {
5946                int currentUid = 0;
5947                try {
5948                    StructStat stat = Os.stat(dataPath.getPath());
5949                    currentUid = stat.st_uid;
5950                } catch (ErrnoException e) {
5951                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5952                }
5953
5954                // If we have mismatched owners for the data path, we have a problem.
5955                if (currentUid != pkg.applicationInfo.uid) {
5956                    boolean recovered = false;
5957                    if (currentUid == 0) {
5958                        // The directory somehow became owned by root.  Wow.
5959                        // This is probably because the system was stopped while
5960                        // installd was in the middle of messing with its libs
5961                        // directory.  Ask installd to fix that.
5962                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5963                                pkg.applicationInfo.uid);
5964                        if (ret >= 0) {
5965                            recovered = true;
5966                            String msg = "Package " + pkg.packageName
5967                                    + " unexpectedly changed to uid 0; recovered to " +
5968                                    + pkg.applicationInfo.uid;
5969                            reportSettingsProblem(Log.WARN, msg);
5970                        }
5971                    }
5972                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5973                            || (scanFlags&SCAN_BOOTING) != 0)) {
5974                        // If this is a system app, we can at least delete its
5975                        // current data so the application will still work.
5976                        int ret = removeDataDirsLI(pkgName);
5977                        if (ret >= 0) {
5978                            // TODO: Kill the processes first
5979                            // Old data gone!
5980                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5981                                    ? "System package " : "Third party package ";
5982                            String msg = prefix + pkg.packageName
5983                                    + " has changed from uid: "
5984                                    + currentUid + " to "
5985                                    + pkg.applicationInfo.uid + "; old data erased";
5986                            reportSettingsProblem(Log.WARN, msg);
5987                            recovered = true;
5988
5989                            // And now re-install the app.
5990                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5991                                                   pkg.applicationInfo.seinfo);
5992                            if (ret == -1) {
5993                                // Ack should not happen!
5994                                msg = prefix + pkg.packageName
5995                                        + " could not have data directory re-created after delete.";
5996                                reportSettingsProblem(Log.WARN, msg);
5997                                throw new PackageManagerException(
5998                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5999                            }
6000                        }
6001                        if (!recovered) {
6002                            mHasSystemUidErrors = true;
6003                        }
6004                    } else if (!recovered) {
6005                        // If we allow this install to proceed, we will be broken.
6006                        // Abort, abort!
6007                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
6008                                "scanPackageLI");
6009                    }
6010                    if (!recovered) {
6011                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
6012                            + pkg.applicationInfo.uid + "/fs_"
6013                            + currentUid;
6014                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
6015                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
6016                        String msg = "Package " + pkg.packageName
6017                                + " has mismatched uid: "
6018                                + currentUid + " on disk, "
6019                                + pkg.applicationInfo.uid + " in settings";
6020                        // writer
6021                        synchronized (mPackages) {
6022                            mSettings.mReadMessages.append(msg);
6023                            mSettings.mReadMessages.append('\n');
6024                            uidError = true;
6025                            if (!pkgSetting.uidError) {
6026                                reportSettingsProblem(Log.ERROR, msg);
6027                            }
6028                        }
6029                    }
6030                }
6031                pkg.applicationInfo.dataDir = dataPath.getPath();
6032                if (mShouldRestoreconData) {
6033                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
6034                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
6035                                pkg.applicationInfo.uid);
6036                }
6037            } else {
6038                if (DEBUG_PACKAGE_SCANNING) {
6039                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6040                        Log.v(TAG, "Want this data dir: " + dataPath);
6041                }
6042                //invoke installer to do the actual installation
6043                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
6044                                           pkg.applicationInfo.seinfo);
6045                if (ret < 0) {
6046                    // Error from installer
6047                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
6048                            "Unable to create data dirs [errorCode=" + ret + "]");
6049                }
6050
6051                if (dataPath.exists()) {
6052                    pkg.applicationInfo.dataDir = dataPath.getPath();
6053                } else {
6054                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
6055                    pkg.applicationInfo.dataDir = null;
6056                }
6057            }
6058
6059            pkgSetting.uidError = uidError;
6060        }
6061
6062        final String path = scanFile.getPath();
6063        final String codePath = pkg.applicationInfo.getCodePath();
6064        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
6065        if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) {
6066            setBundledAppAbisAndRoots(pkg, pkgSetting);
6067
6068            // If we haven't found any native libraries for the app, check if it has
6069            // renderscript code. We'll need to force the app to 32 bit if it has
6070            // renderscript bitcode.
6071            if (pkg.applicationInfo.primaryCpuAbi == null
6072                    && pkg.applicationInfo.secondaryCpuAbi == null
6073                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
6074                NativeLibraryHelper.Handle handle = null;
6075                try {
6076                    handle = NativeLibraryHelper.Handle.create(scanFile);
6077                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6078                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6079                    }
6080                } catch (IOException ioe) {
6081                    Slog.w(TAG, "Error scanning system app : " + ioe);
6082                } finally {
6083                    IoUtils.closeQuietly(handle);
6084                }
6085            }
6086
6087            setNativeLibraryPaths(pkg);
6088        } else {
6089            // TODO: We can probably be smarter about this stuff. For installed apps,
6090            // we can calculate this information at install time once and for all. For
6091            // system apps, we can probably assume that this information doesn't change
6092            // after the first boot scan. As things stand, we do lots of unnecessary work.
6093
6094            // Give ourselves some initial paths; we'll come back for another
6095            // pass once we've determined ABI below.
6096            setNativeLibraryPaths(pkg);
6097
6098            final boolean isAsec = pkg.isForwardLocked() || isExternal(pkg);
6099            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
6100            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
6101
6102            NativeLibraryHelper.Handle handle = null;
6103            try {
6104                handle = NativeLibraryHelper.Handle.create(scanFile);
6105                // TODO(multiArch): This can be null for apps that didn't go through the
6106                // usual installation process. We can calculate it again, like we
6107                // do during install time.
6108                //
6109                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
6110                // unnecessary.
6111                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
6112
6113                // Null out the abis so that they can be recalculated.
6114                pkg.applicationInfo.primaryCpuAbi = null;
6115                pkg.applicationInfo.secondaryCpuAbi = null;
6116                if (isMultiArch(pkg.applicationInfo)) {
6117                    // Warn if we've set an abiOverride for multi-lib packages..
6118                    // By definition, we need to copy both 32 and 64 bit libraries for
6119                    // such packages.
6120                    if (pkg.cpuAbiOverride != null
6121                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
6122                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
6123                    }
6124
6125                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
6126                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
6127                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
6128                        if (isAsec) {
6129                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
6130                        } else {
6131                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6132                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
6133                                    useIsaSpecificSubdirs);
6134                        }
6135                    }
6136
6137                    maybeThrowExceptionForMultiArchCopy(
6138                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
6139
6140                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
6141                        if (isAsec) {
6142                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
6143                        } else {
6144                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6145                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
6146                                    useIsaSpecificSubdirs);
6147                        }
6148                    }
6149
6150                    maybeThrowExceptionForMultiArchCopy(
6151                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
6152
6153                    if (abi64 >= 0) {
6154                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
6155                    }
6156
6157                    if (abi32 >= 0) {
6158                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
6159                        if (abi64 >= 0) {
6160                            pkg.applicationInfo.secondaryCpuAbi = abi;
6161                        } else {
6162                            pkg.applicationInfo.primaryCpuAbi = abi;
6163                        }
6164                    }
6165                } else {
6166                    String[] abiList = (cpuAbiOverride != null) ?
6167                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
6168
6169                    // Enable gross and lame hacks for apps that are built with old
6170                    // SDK tools. We must scan their APKs for renderscript bitcode and
6171                    // not launch them if it's present. Don't bother checking on devices
6172                    // that don't have 64 bit support.
6173                    boolean needsRenderScriptOverride = false;
6174                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
6175                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6176                        abiList = Build.SUPPORTED_32_BIT_ABIS;
6177                        needsRenderScriptOverride = true;
6178                    }
6179
6180                    final int copyRet;
6181                    if (isAsec) {
6182                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6183                    } else {
6184                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
6185                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
6186                    }
6187
6188                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
6189                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6190                                "Error unpackaging native libs for app, errorCode=" + copyRet);
6191                    }
6192
6193                    if (copyRet >= 0) {
6194                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
6195                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
6196                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
6197                    } else if (needsRenderScriptOverride) {
6198                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
6199                    }
6200                }
6201            } catch (IOException ioe) {
6202                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
6203            } finally {
6204                IoUtils.closeQuietly(handle);
6205            }
6206
6207            // Now that we've calculated the ABIs and determined if it's an internal app,
6208            // we will go ahead and populate the nativeLibraryPath.
6209            setNativeLibraryPaths(pkg);
6210
6211            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
6212            final int[] userIds = sUserManager.getUserIds();
6213            synchronized (mInstallLock) {
6214                // Create a native library symlink only if we have native libraries
6215                // and if the native libraries are 32 bit libraries. We do not provide
6216                // this symlink for 64 bit libraries.
6217                if (pkg.applicationInfo.primaryCpuAbi != null &&
6218                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
6219                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
6220                    for (int userId : userIds) {
6221                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
6222                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
6223                                    "Failed linking native library dir (user=" + userId + ")");
6224                        }
6225                    }
6226                }
6227            }
6228        }
6229
6230        // This is a special case for the "system" package, where the ABI is
6231        // dictated by the zygote configuration (and init.rc). We should keep track
6232        // of this ABI so that we can deal with "normal" applications that run under
6233        // the same UID correctly.
6234        if (mPlatformPackage == pkg) {
6235            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
6236                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
6237        }
6238
6239        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6240        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6241        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
6242        // Copy the derived override back to the parsed package, so that we can
6243        // update the package settings accordingly.
6244        pkg.cpuAbiOverride = cpuAbiOverride;
6245
6246        if (DEBUG_ABI_SELECTION) {
6247            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
6248                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
6249                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
6250        }
6251
6252        // Push the derived path down into PackageSettings so we know what to
6253        // clean up at uninstall time.
6254        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
6255
6256        if (DEBUG_ABI_SELECTION) {
6257            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
6258                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
6259                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
6260        }
6261
6262        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
6263            // We don't do this here during boot because we can do it all
6264            // at once after scanning all existing packages.
6265            //
6266            // We also do this *before* we perform dexopt on this package, so that
6267            // we can avoid redundant dexopts, and also to make sure we've got the
6268            // code and package path correct.
6269            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
6270                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
6271        }
6272
6273        if ((scanFlags & SCAN_NO_DEX) == 0) {
6274            int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instruction sets */,
6275                    forceDex, (scanFlags & SCAN_DEFER_DEX) != 0, false /* inclDependencies */);
6276            if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6277                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
6278            }
6279        }
6280        if (mFactoryTest && pkg.requestedPermissions.contains(
6281                android.Manifest.permission.FACTORY_TEST)) {
6282            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
6283        }
6284
6285        ArrayList<PackageParser.Package> clientLibPkgs = null;
6286
6287        // writer
6288        synchronized (mPackages) {
6289            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6290                // Only system apps can add new shared libraries.
6291                if (pkg.libraryNames != null) {
6292                    for (int i=0; i<pkg.libraryNames.size(); i++) {
6293                        String name = pkg.libraryNames.get(i);
6294                        boolean allowed = false;
6295                        if (pkg.isUpdatedSystemApp()) {
6296                            // New library entries can only be added through the
6297                            // system image.  This is important to get rid of a lot
6298                            // of nasty edge cases: for example if we allowed a non-
6299                            // system update of the app to add a library, then uninstalling
6300                            // the update would make the library go away, and assumptions
6301                            // we made such as through app install filtering would now
6302                            // have allowed apps on the device which aren't compatible
6303                            // with it.  Better to just have the restriction here, be
6304                            // conservative, and create many fewer cases that can negatively
6305                            // impact the user experience.
6306                            final PackageSetting sysPs = mSettings
6307                                    .getDisabledSystemPkgLPr(pkg.packageName);
6308                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
6309                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
6310                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
6311                                        allowed = true;
6312                                        allowed = true;
6313                                        break;
6314                                    }
6315                                }
6316                            }
6317                        } else {
6318                            allowed = true;
6319                        }
6320                        if (allowed) {
6321                            if (!mSharedLibraries.containsKey(name)) {
6322                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
6323                            } else if (!name.equals(pkg.packageName)) {
6324                                Slog.w(TAG, "Package " + pkg.packageName + " library "
6325                                        + name + " already exists; skipping");
6326                            }
6327                        } else {
6328                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
6329                                    + name + " that is not declared on system image; skipping");
6330                        }
6331                    }
6332                    if ((scanFlags&SCAN_BOOTING) == 0) {
6333                        // If we are not booting, we need to update any applications
6334                        // that are clients of our shared library.  If we are booting,
6335                        // this will all be done once the scan is complete.
6336                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
6337                    }
6338                }
6339            }
6340        }
6341
6342        // We also need to dexopt any apps that are dependent on this library.  Note that
6343        // if these fail, we should abort the install since installing the library will
6344        // result in some apps being broken.
6345        if (clientLibPkgs != null) {
6346            if ((scanFlags & SCAN_NO_DEX) == 0) {
6347                for (int i = 0; i < clientLibPkgs.size(); i++) {
6348                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
6349                    int result = mPackageDexOptimizer.performDexOpt(clientPkg,
6350                            null /* instruction sets */, forceDex,
6351                            (scanFlags & SCAN_DEFER_DEX) != 0, false);
6352                    if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6353                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
6354                                "scanPackageLI failed to dexopt clientLibPkgs");
6355                    }
6356                }
6357            }
6358        }
6359
6360        // Request the ActivityManager to kill the process(only for existing packages)
6361        // so that we do not end up in a confused state while the user is still using the older
6362        // version of the application while the new one gets installed.
6363        if ((scanFlags & SCAN_REPLACING) != 0) {
6364            killApplication(pkg.applicationInfo.packageName,
6365                        pkg.applicationInfo.uid, "update pkg");
6366        }
6367
6368        // Also need to kill any apps that are dependent on the library.
6369        if (clientLibPkgs != null) {
6370            for (int i=0; i<clientLibPkgs.size(); i++) {
6371                PackageParser.Package clientPkg = clientLibPkgs.get(i);
6372                killApplication(clientPkg.applicationInfo.packageName,
6373                        clientPkg.applicationInfo.uid, "update lib");
6374            }
6375        }
6376
6377        // writer
6378        synchronized (mPackages) {
6379            // We don't expect installation to fail beyond this point
6380
6381            // Add the new setting to mSettings
6382            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
6383            // Add the new setting to mPackages
6384            mPackages.put(pkg.applicationInfo.packageName, pkg);
6385            // Make sure we don't accidentally delete its data.
6386            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
6387            while (iter.hasNext()) {
6388                PackageCleanItem item = iter.next();
6389                if (pkgName.equals(item.packageName)) {
6390                    iter.remove();
6391                }
6392            }
6393
6394            // Take care of first install / last update times.
6395            if (currentTime != 0) {
6396                if (pkgSetting.firstInstallTime == 0) {
6397                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
6398                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
6399                    pkgSetting.lastUpdateTime = currentTime;
6400                }
6401            } else if (pkgSetting.firstInstallTime == 0) {
6402                // We need *something*.  Take time time stamp of the file.
6403                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6404            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6405                if (scanFileTime != pkgSetting.timeStamp) {
6406                    // A package on the system image has changed; consider this
6407                    // to be an update.
6408                    pkgSetting.lastUpdateTime = scanFileTime;
6409                }
6410            }
6411
6412            // Add the package's KeySets to the global KeySetManagerService
6413            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6414            try {
6415                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6416                if (pkg.mKeySetMapping != null) {
6417                    ksms.addDefinedKeySetsToPackageLPw(pkg.packageName, pkg.mKeySetMapping);
6418                    if (pkg.mUpgradeKeySets != null) {
6419                        ksms.addUpgradeKeySetsToPackageLPw(pkg.packageName, pkg.mUpgradeKeySets);
6420                    }
6421                }
6422            } catch (NullPointerException e) {
6423                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6424            } catch (IllegalArgumentException e) {
6425                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6426            }
6427
6428            int N = pkg.providers.size();
6429            StringBuilder r = null;
6430            int i;
6431            for (i=0; i<N; i++) {
6432                PackageParser.Provider p = pkg.providers.get(i);
6433                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6434                        p.info.processName, pkg.applicationInfo.uid);
6435                mProviders.addProvider(p);
6436                p.syncable = p.info.isSyncable;
6437                if (p.info.authority != null) {
6438                    String names[] = p.info.authority.split(";");
6439                    p.info.authority = null;
6440                    for (int j = 0; j < names.length; j++) {
6441                        if (j == 1 && p.syncable) {
6442                            // We only want the first authority for a provider to possibly be
6443                            // syncable, so if we already added this provider using a different
6444                            // authority clear the syncable flag. We copy the provider before
6445                            // changing it because the mProviders object contains a reference
6446                            // to a provider that we don't want to change.
6447                            // Only do this for the second authority since the resulting provider
6448                            // object can be the same for all future authorities for this provider.
6449                            p = new PackageParser.Provider(p);
6450                            p.syncable = false;
6451                        }
6452                        if (!mProvidersByAuthority.containsKey(names[j])) {
6453                            mProvidersByAuthority.put(names[j], p);
6454                            if (p.info.authority == null) {
6455                                p.info.authority = names[j];
6456                            } else {
6457                                p.info.authority = p.info.authority + ";" + names[j];
6458                            }
6459                            if (DEBUG_PACKAGE_SCANNING) {
6460                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6461                                    Log.d(TAG, "Registered content provider: " + names[j]
6462                                            + ", className = " + p.info.name + ", isSyncable = "
6463                                            + p.info.isSyncable);
6464                            }
6465                        } else {
6466                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6467                            Slog.w(TAG, "Skipping provider name " + names[j] +
6468                                    " (in package " + pkg.applicationInfo.packageName +
6469                                    "): name already used by "
6470                                    + ((other != null && other.getComponentName() != null)
6471                                            ? other.getComponentName().getPackageName() : "?"));
6472                        }
6473                    }
6474                }
6475                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6476                    if (r == null) {
6477                        r = new StringBuilder(256);
6478                    } else {
6479                        r.append(' ');
6480                    }
6481                    r.append(p.info.name);
6482                }
6483            }
6484            if (r != null) {
6485                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6486            }
6487
6488            N = pkg.services.size();
6489            r = null;
6490            for (i=0; i<N; i++) {
6491                PackageParser.Service s = pkg.services.get(i);
6492                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6493                        s.info.processName, pkg.applicationInfo.uid);
6494                mServices.addService(s);
6495                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6496                    if (r == null) {
6497                        r = new StringBuilder(256);
6498                    } else {
6499                        r.append(' ');
6500                    }
6501                    r.append(s.info.name);
6502                }
6503            }
6504            if (r != null) {
6505                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6506            }
6507
6508            N = pkg.receivers.size();
6509            r = null;
6510            for (i=0; i<N; i++) {
6511                PackageParser.Activity a = pkg.receivers.get(i);
6512                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6513                        a.info.processName, pkg.applicationInfo.uid);
6514                mReceivers.addActivity(a, "receiver");
6515                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6516                    if (r == null) {
6517                        r = new StringBuilder(256);
6518                    } else {
6519                        r.append(' ');
6520                    }
6521                    r.append(a.info.name);
6522                }
6523            }
6524            if (r != null) {
6525                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6526            }
6527
6528            N = pkg.activities.size();
6529            r = null;
6530            for (i=0; i<N; i++) {
6531                PackageParser.Activity a = pkg.activities.get(i);
6532                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6533                        a.info.processName, pkg.applicationInfo.uid);
6534                mActivities.addActivity(a, "activity");
6535                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6536                    if (r == null) {
6537                        r = new StringBuilder(256);
6538                    } else {
6539                        r.append(' ');
6540                    }
6541                    r.append(a.info.name);
6542                }
6543            }
6544            if (r != null) {
6545                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6546            }
6547
6548            N = pkg.permissionGroups.size();
6549            r = null;
6550            for (i=0; i<N; i++) {
6551                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6552                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6553                if (cur == null) {
6554                    mPermissionGroups.put(pg.info.name, pg);
6555                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6556                        if (r == null) {
6557                            r = new StringBuilder(256);
6558                        } else {
6559                            r.append(' ');
6560                        }
6561                        r.append(pg.info.name);
6562                    }
6563                } else {
6564                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6565                            + pg.info.packageName + " ignored: original from "
6566                            + cur.info.packageName);
6567                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6568                        if (r == null) {
6569                            r = new StringBuilder(256);
6570                        } else {
6571                            r.append(' ');
6572                        }
6573                        r.append("DUP:");
6574                        r.append(pg.info.name);
6575                    }
6576                }
6577            }
6578            if (r != null) {
6579                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6580            }
6581
6582            N = pkg.permissions.size();
6583            r = null;
6584            for (i=0; i<N; i++) {
6585                PackageParser.Permission p = pkg.permissions.get(i);
6586                ArrayMap<String, BasePermission> permissionMap =
6587                        p.tree ? mSettings.mPermissionTrees
6588                        : mSettings.mPermissions;
6589                p.group = mPermissionGroups.get(p.info.group);
6590                if (p.info.group == null || p.group != null) {
6591                    BasePermission bp = permissionMap.get(p.info.name);
6592
6593                    // Allow system apps to redefine non-system permissions
6594                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6595                        final boolean currentOwnerIsSystem = (bp.perm != null
6596                                && isSystemApp(bp.perm.owner));
6597                        if (isSystemApp(p.owner)) {
6598                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6599                                // It's a built-in permission and no owner, take ownership now
6600                                bp.packageSetting = pkgSetting;
6601                                bp.perm = p;
6602                                bp.uid = pkg.applicationInfo.uid;
6603                                bp.sourcePackage = p.info.packageName;
6604                            } else if (!currentOwnerIsSystem) {
6605                                String msg = "New decl " + p.owner + " of permission  "
6606                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6607                                reportSettingsProblem(Log.WARN, msg);
6608                                bp = null;
6609                            }
6610                        }
6611                    }
6612
6613                    if (bp == null) {
6614                        bp = new BasePermission(p.info.name, p.info.packageName,
6615                                BasePermission.TYPE_NORMAL);
6616                        permissionMap.put(p.info.name, bp);
6617                    }
6618
6619                    if (bp.perm == null) {
6620                        if (bp.sourcePackage == null
6621                                || bp.sourcePackage.equals(p.info.packageName)) {
6622                            BasePermission tree = findPermissionTreeLP(p.info.name);
6623                            if (tree == null
6624                                    || tree.sourcePackage.equals(p.info.packageName)) {
6625                                bp.packageSetting = pkgSetting;
6626                                bp.perm = p;
6627                                bp.uid = pkg.applicationInfo.uid;
6628                                bp.sourcePackage = p.info.packageName;
6629                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6630                                    if (r == null) {
6631                                        r = new StringBuilder(256);
6632                                    } else {
6633                                        r.append(' ');
6634                                    }
6635                                    r.append(p.info.name);
6636                                }
6637                            } else {
6638                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6639                                        + p.info.packageName + " ignored: base tree "
6640                                        + tree.name + " is from package "
6641                                        + tree.sourcePackage);
6642                            }
6643                        } else {
6644                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6645                                    + p.info.packageName + " ignored: original from "
6646                                    + bp.sourcePackage);
6647                        }
6648                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6649                        if (r == null) {
6650                            r = new StringBuilder(256);
6651                        } else {
6652                            r.append(' ');
6653                        }
6654                        r.append("DUP:");
6655                        r.append(p.info.name);
6656                    }
6657                    if (bp.perm == p) {
6658                        bp.protectionLevel = p.info.protectionLevel;
6659                    }
6660                } else {
6661                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6662                            + p.info.packageName + " ignored: no group "
6663                            + p.group);
6664                }
6665            }
6666            if (r != null) {
6667                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6668            }
6669
6670            N = pkg.instrumentation.size();
6671            r = null;
6672            for (i=0; i<N; i++) {
6673                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6674                a.info.packageName = pkg.applicationInfo.packageName;
6675                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6676                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6677                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6678                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6679                a.info.dataDir = pkg.applicationInfo.dataDir;
6680
6681                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6682                // need other information about the application, like the ABI and what not ?
6683                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6684                mInstrumentation.put(a.getComponentName(), a);
6685                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6686                    if (r == null) {
6687                        r = new StringBuilder(256);
6688                    } else {
6689                        r.append(' ');
6690                    }
6691                    r.append(a.info.name);
6692                }
6693            }
6694            if (r != null) {
6695                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6696            }
6697
6698            if (pkg.protectedBroadcasts != null) {
6699                N = pkg.protectedBroadcasts.size();
6700                for (i=0; i<N; i++) {
6701                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6702                }
6703            }
6704
6705            pkgSetting.setTimeStamp(scanFileTime);
6706
6707            // Create idmap files for pairs of (packages, overlay packages).
6708            // Note: "android", ie framework-res.apk, is handled by native layers.
6709            if (pkg.mOverlayTarget != null) {
6710                // This is an overlay package.
6711                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6712                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6713                        mOverlays.put(pkg.mOverlayTarget,
6714                                new ArrayMap<String, PackageParser.Package>());
6715                    }
6716                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6717                    map.put(pkg.packageName, pkg);
6718                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6719                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6720                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6721                                "scanPackageLI failed to createIdmap");
6722                    }
6723                }
6724            } else if (mOverlays.containsKey(pkg.packageName) &&
6725                    !pkg.packageName.equals("android")) {
6726                // This is a regular package, with one or more known overlay packages.
6727                createIdmapsForPackageLI(pkg);
6728            }
6729        }
6730
6731        return pkg;
6732    }
6733
6734    /**
6735     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6736     * i.e, so that all packages can be run inside a single process if required.
6737     *
6738     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6739     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6740     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6741     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6742     * updating a package that belongs to a shared user.
6743     *
6744     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6745     * adds unnecessary complexity.
6746     */
6747    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6748            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6749        String requiredInstructionSet = null;
6750        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6751            requiredInstructionSet = VMRuntime.getInstructionSet(
6752                     scannedPackage.applicationInfo.primaryCpuAbi);
6753        }
6754
6755        PackageSetting requirer = null;
6756        for (PackageSetting ps : packagesForUser) {
6757            // If packagesForUser contains scannedPackage, we skip it. This will happen
6758            // when scannedPackage is an update of an existing package. Without this check,
6759            // we will never be able to change the ABI of any package belonging to a shared
6760            // user, even if it's compatible with other packages.
6761            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6762                if (ps.primaryCpuAbiString == null) {
6763                    continue;
6764                }
6765
6766                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6767                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6768                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6769                    // this but there's not much we can do.
6770                    String errorMessage = "Instruction set mismatch, "
6771                            + ((requirer == null) ? "[caller]" : requirer)
6772                            + " requires " + requiredInstructionSet + " whereas " + ps
6773                            + " requires " + instructionSet;
6774                    Slog.w(TAG, errorMessage);
6775                }
6776
6777                if (requiredInstructionSet == null) {
6778                    requiredInstructionSet = instructionSet;
6779                    requirer = ps;
6780                }
6781            }
6782        }
6783
6784        if (requiredInstructionSet != null) {
6785            String adjustedAbi;
6786            if (requirer != null) {
6787                // requirer != null implies that either scannedPackage was null or that scannedPackage
6788                // did not require an ABI, in which case we have to adjust scannedPackage to match
6789                // the ABI of the set (which is the same as requirer's ABI)
6790                adjustedAbi = requirer.primaryCpuAbiString;
6791                if (scannedPackage != null) {
6792                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6793                }
6794            } else {
6795                // requirer == null implies that we're updating all ABIs in the set to
6796                // match scannedPackage.
6797                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6798            }
6799
6800            for (PackageSetting ps : packagesForUser) {
6801                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6802                    if (ps.primaryCpuAbiString != null) {
6803                        continue;
6804                    }
6805
6806                    ps.primaryCpuAbiString = adjustedAbi;
6807                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6808                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6809                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6810
6811                        int result = mPackageDexOptimizer.performDexOpt(ps.pkg,
6812                                null /* instruction sets */, forceDexOpt, deferDexOpt, true);
6813                        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
6814                            ps.primaryCpuAbiString = null;
6815                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6816                            return;
6817                        } else {
6818                            mInstaller.rmdex(ps.codePathString,
6819                                    getDexCodeInstructionSet(getPreferredInstructionSet()));
6820                        }
6821                    }
6822                }
6823            }
6824        }
6825    }
6826
6827    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6828        synchronized (mPackages) {
6829            mResolverReplaced = true;
6830            // Set up information for custom user intent resolution activity.
6831            mResolveActivity.applicationInfo = pkg.applicationInfo;
6832            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6833            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6834            mResolveActivity.processName = pkg.applicationInfo.packageName;
6835            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6836            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6837                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6838            mResolveActivity.theme = 0;
6839            mResolveActivity.exported = true;
6840            mResolveActivity.enabled = true;
6841            mResolveInfo.activityInfo = mResolveActivity;
6842            mResolveInfo.priority = 0;
6843            mResolveInfo.preferredOrder = 0;
6844            mResolveInfo.match = 0;
6845            mResolveComponentName = mCustomResolverComponentName;
6846            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6847                    mResolveComponentName);
6848        }
6849    }
6850
6851    private static String calculateBundledApkRoot(final String codePathString) {
6852        final File codePath = new File(codePathString);
6853        final File codeRoot;
6854        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6855            codeRoot = Environment.getRootDirectory();
6856        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6857            codeRoot = Environment.getOemDirectory();
6858        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6859            codeRoot = Environment.getVendorDirectory();
6860        } else {
6861            // Unrecognized code path; take its top real segment as the apk root:
6862            // e.g. /something/app/blah.apk => /something
6863            try {
6864                File f = codePath.getCanonicalFile();
6865                File parent = f.getParentFile();    // non-null because codePath is a file
6866                File tmp;
6867                while ((tmp = parent.getParentFile()) != null) {
6868                    f = parent;
6869                    parent = tmp;
6870                }
6871                codeRoot = f;
6872                Slog.w(TAG, "Unrecognized code path "
6873                        + codePath + " - using " + codeRoot);
6874            } catch (IOException e) {
6875                // Can't canonicalize the code path -- shenanigans?
6876                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6877                return Environment.getRootDirectory().getPath();
6878            }
6879        }
6880        return codeRoot.getPath();
6881    }
6882
6883    /**
6884     * Derive and set the location of native libraries for the given package,
6885     * which varies depending on where and how the package was installed.
6886     */
6887    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6888        final ApplicationInfo info = pkg.applicationInfo;
6889        final String codePath = pkg.codePath;
6890        final File codeFile = new File(codePath);
6891        final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp();
6892        final boolean asecApp = info.isForwardLocked() || isExternal(info);
6893
6894        info.nativeLibraryRootDir = null;
6895        info.nativeLibraryRootRequiresIsa = false;
6896        info.nativeLibraryDir = null;
6897        info.secondaryNativeLibraryDir = null;
6898
6899        if (isApkFile(codeFile)) {
6900            // Monolithic install
6901            if (bundledApp) {
6902                // If "/system/lib64/apkname" exists, assume that is the per-package
6903                // native library directory to use; otherwise use "/system/lib/apkname".
6904                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6905                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6906                        getPrimaryInstructionSet(info));
6907
6908                // This is a bundled system app so choose the path based on the ABI.
6909                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6910                // is just the default path.
6911                final String apkName = deriveCodePathName(codePath);
6912                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6913                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6914                        apkName).getAbsolutePath();
6915
6916                if (info.secondaryCpuAbi != null) {
6917                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6918                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6919                            secondaryLibDir, apkName).getAbsolutePath();
6920                }
6921            } else if (asecApp) {
6922                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6923                        .getAbsolutePath();
6924            } else {
6925                final String apkName = deriveCodePathName(codePath);
6926                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6927                        .getAbsolutePath();
6928            }
6929
6930            info.nativeLibraryRootRequiresIsa = false;
6931            info.nativeLibraryDir = info.nativeLibraryRootDir;
6932        } else {
6933            // Cluster install
6934            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6935            info.nativeLibraryRootRequiresIsa = true;
6936
6937            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6938                    getPrimaryInstructionSet(info)).getAbsolutePath();
6939
6940            if (info.secondaryCpuAbi != null) {
6941                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6942                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6943            }
6944        }
6945    }
6946
6947    /**
6948     * Calculate the abis and roots for a bundled app. These can uniquely
6949     * be determined from the contents of the system partition, i.e whether
6950     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6951     * of this information, and instead assume that the system was built
6952     * sensibly.
6953     */
6954    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6955                                           PackageSetting pkgSetting) {
6956        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6957
6958        // If "/system/lib64/apkname" exists, assume that is the per-package
6959        // native library directory to use; otherwise use "/system/lib/apkname".
6960        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6961        setBundledAppAbi(pkg, apkRoot, apkName);
6962        // pkgSetting might be null during rescan following uninstall of updates
6963        // to a bundled app, so accommodate that possibility.  The settings in
6964        // that case will be established later from the parsed package.
6965        //
6966        // If the settings aren't null, sync them up with what we've just derived.
6967        // note that apkRoot isn't stored in the package settings.
6968        if (pkgSetting != null) {
6969            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6970            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6971        }
6972    }
6973
6974    /**
6975     * Deduces the ABI of a bundled app and sets the relevant fields on the
6976     * parsed pkg object.
6977     *
6978     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6979     *        under which system libraries are installed.
6980     * @param apkName the name of the installed package.
6981     */
6982    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6983        final File codeFile = new File(pkg.codePath);
6984
6985        final boolean has64BitLibs;
6986        final boolean has32BitLibs;
6987        if (isApkFile(codeFile)) {
6988            // Monolithic install
6989            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6990            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6991        } else {
6992            // Cluster install
6993            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6994            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6995                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6996                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6997                has64BitLibs = (new File(rootDir, isa)).exists();
6998            } else {
6999                has64BitLibs = false;
7000            }
7001            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
7002                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
7003                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
7004                has32BitLibs = (new File(rootDir, isa)).exists();
7005            } else {
7006                has32BitLibs = false;
7007            }
7008        }
7009
7010        if (has64BitLibs && !has32BitLibs) {
7011            // The package has 64 bit libs, but not 32 bit libs. Its primary
7012            // ABI should be 64 bit. We can safely assume here that the bundled
7013            // native libraries correspond to the most preferred ABI in the list.
7014
7015            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7016            pkg.applicationInfo.secondaryCpuAbi = null;
7017        } else if (has32BitLibs && !has64BitLibs) {
7018            // The package has 32 bit libs but not 64 bit libs. Its primary
7019            // ABI should be 32 bit.
7020
7021            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7022            pkg.applicationInfo.secondaryCpuAbi = null;
7023        } else if (has32BitLibs && has64BitLibs) {
7024            // The application has both 64 and 32 bit bundled libraries. We check
7025            // here that the app declares multiArch support, and warn if it doesn't.
7026            //
7027            // We will be lenient here and record both ABIs. The primary will be the
7028            // ABI that's higher on the list, i.e, a device that's configured to prefer
7029            // 64 bit apps will see a 64 bit primary ABI,
7030
7031            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
7032                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
7033            }
7034
7035            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
7036                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7037                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7038            } else {
7039                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
7040                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
7041            }
7042        } else {
7043            pkg.applicationInfo.primaryCpuAbi = null;
7044            pkg.applicationInfo.secondaryCpuAbi = null;
7045        }
7046    }
7047
7048    private void killApplication(String pkgName, int appId, String reason) {
7049        // Request the ActivityManager to kill the process(only for existing packages)
7050        // so that we do not end up in a confused state while the user is still using the older
7051        // version of the application while the new one gets installed.
7052        IActivityManager am = ActivityManagerNative.getDefault();
7053        if (am != null) {
7054            try {
7055                am.killApplicationWithAppId(pkgName, appId, reason);
7056            } catch (RemoteException e) {
7057            }
7058        }
7059    }
7060
7061    void removePackageLI(PackageSetting ps, boolean chatty) {
7062        if (DEBUG_INSTALL) {
7063            if (chatty)
7064                Log.d(TAG, "Removing package " + ps.name);
7065        }
7066
7067        // writer
7068        synchronized (mPackages) {
7069            mPackages.remove(ps.name);
7070            final PackageParser.Package pkg = ps.pkg;
7071            if (pkg != null) {
7072                cleanPackageDataStructuresLILPw(pkg, chatty);
7073            }
7074        }
7075    }
7076
7077    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
7078        if (DEBUG_INSTALL) {
7079            if (chatty)
7080                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
7081        }
7082
7083        // writer
7084        synchronized (mPackages) {
7085            mPackages.remove(pkg.applicationInfo.packageName);
7086            cleanPackageDataStructuresLILPw(pkg, chatty);
7087        }
7088    }
7089
7090    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
7091        int N = pkg.providers.size();
7092        StringBuilder r = null;
7093        int i;
7094        for (i=0; i<N; i++) {
7095            PackageParser.Provider p = pkg.providers.get(i);
7096            mProviders.removeProvider(p);
7097            if (p.info.authority == null) {
7098
7099                /* There was another ContentProvider with this authority when
7100                 * this app was installed so this authority is null,
7101                 * Ignore it as we don't have to unregister the provider.
7102                 */
7103                continue;
7104            }
7105            String names[] = p.info.authority.split(";");
7106            for (int j = 0; j < names.length; j++) {
7107                if (mProvidersByAuthority.get(names[j]) == p) {
7108                    mProvidersByAuthority.remove(names[j]);
7109                    if (DEBUG_REMOVE) {
7110                        if (chatty)
7111                            Log.d(TAG, "Unregistered content provider: " + names[j]
7112                                    + ", className = " + p.info.name + ", isSyncable = "
7113                                    + p.info.isSyncable);
7114                    }
7115                }
7116            }
7117            if (DEBUG_REMOVE && chatty) {
7118                if (r == null) {
7119                    r = new StringBuilder(256);
7120                } else {
7121                    r.append(' ');
7122                }
7123                r.append(p.info.name);
7124            }
7125        }
7126        if (r != null) {
7127            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
7128        }
7129
7130        N = pkg.services.size();
7131        r = null;
7132        for (i=0; i<N; i++) {
7133            PackageParser.Service s = pkg.services.get(i);
7134            mServices.removeService(s);
7135            if (chatty) {
7136                if (r == null) {
7137                    r = new StringBuilder(256);
7138                } else {
7139                    r.append(' ');
7140                }
7141                r.append(s.info.name);
7142            }
7143        }
7144        if (r != null) {
7145            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
7146        }
7147
7148        N = pkg.receivers.size();
7149        r = null;
7150        for (i=0; i<N; i++) {
7151            PackageParser.Activity a = pkg.receivers.get(i);
7152            mReceivers.removeActivity(a, "receiver");
7153            if (DEBUG_REMOVE && chatty) {
7154                if (r == null) {
7155                    r = new StringBuilder(256);
7156                } else {
7157                    r.append(' ');
7158                }
7159                r.append(a.info.name);
7160            }
7161        }
7162        if (r != null) {
7163            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
7164        }
7165
7166        N = pkg.activities.size();
7167        r = null;
7168        for (i=0; i<N; i++) {
7169            PackageParser.Activity a = pkg.activities.get(i);
7170            mActivities.removeActivity(a, "activity");
7171            if (DEBUG_REMOVE && chatty) {
7172                if (r == null) {
7173                    r = new StringBuilder(256);
7174                } else {
7175                    r.append(' ');
7176                }
7177                r.append(a.info.name);
7178            }
7179        }
7180        if (r != null) {
7181            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
7182        }
7183
7184        N = pkg.permissions.size();
7185        r = null;
7186        for (i=0; i<N; i++) {
7187            PackageParser.Permission p = pkg.permissions.get(i);
7188            BasePermission bp = mSettings.mPermissions.get(p.info.name);
7189            if (bp == null) {
7190                bp = mSettings.mPermissionTrees.get(p.info.name);
7191            }
7192            if (bp != null && bp.perm == p) {
7193                bp.perm = null;
7194                if (DEBUG_REMOVE && chatty) {
7195                    if (r == null) {
7196                        r = new StringBuilder(256);
7197                    } else {
7198                        r.append(' ');
7199                    }
7200                    r.append(p.info.name);
7201                }
7202            }
7203            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7204                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
7205                if (appOpPerms != null) {
7206                    appOpPerms.remove(pkg.packageName);
7207                }
7208            }
7209        }
7210        if (r != null) {
7211            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7212        }
7213
7214        N = pkg.requestedPermissions.size();
7215        r = null;
7216        for (i=0; i<N; i++) {
7217            String perm = pkg.requestedPermissions.get(i);
7218            BasePermission bp = mSettings.mPermissions.get(perm);
7219            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7220                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
7221                if (appOpPerms != null) {
7222                    appOpPerms.remove(pkg.packageName);
7223                    if (appOpPerms.isEmpty()) {
7224                        mAppOpPermissionPackages.remove(perm);
7225                    }
7226                }
7227            }
7228        }
7229        if (r != null) {
7230            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
7231        }
7232
7233        N = pkg.instrumentation.size();
7234        r = null;
7235        for (i=0; i<N; i++) {
7236            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
7237            mInstrumentation.remove(a.getComponentName());
7238            if (DEBUG_REMOVE && chatty) {
7239                if (r == null) {
7240                    r = new StringBuilder(256);
7241                } else {
7242                    r.append(' ');
7243                }
7244                r.append(a.info.name);
7245            }
7246        }
7247        if (r != null) {
7248            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
7249        }
7250
7251        r = null;
7252        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
7253            // Only system apps can hold shared libraries.
7254            if (pkg.libraryNames != null) {
7255                for (i=0; i<pkg.libraryNames.size(); i++) {
7256                    String name = pkg.libraryNames.get(i);
7257                    SharedLibraryEntry cur = mSharedLibraries.get(name);
7258                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
7259                        mSharedLibraries.remove(name);
7260                        if (DEBUG_REMOVE && chatty) {
7261                            if (r == null) {
7262                                r = new StringBuilder(256);
7263                            } else {
7264                                r.append(' ');
7265                            }
7266                            r.append(name);
7267                        }
7268                    }
7269                }
7270            }
7271        }
7272        if (r != null) {
7273            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
7274        }
7275    }
7276
7277    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
7278        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
7279            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
7280                return true;
7281            }
7282        }
7283        return false;
7284    }
7285
7286    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
7287    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
7288    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
7289
7290    private void updatePermissionsLPw(String changingPkg,
7291            PackageParser.Package pkgInfo, int flags) {
7292        // Make sure there are no dangling permission trees.
7293        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
7294        while (it.hasNext()) {
7295            final BasePermission bp = it.next();
7296            if (bp.packageSetting == null) {
7297                // We may not yet have parsed the package, so just see if
7298                // we still know about its settings.
7299                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7300            }
7301            if (bp.packageSetting == null) {
7302                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
7303                        + " from package " + bp.sourcePackage);
7304                it.remove();
7305            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7306                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7307                    Slog.i(TAG, "Removing old permission tree: " + bp.name
7308                            + " from package " + bp.sourcePackage);
7309                    flags |= UPDATE_PERMISSIONS_ALL;
7310                    it.remove();
7311                }
7312            }
7313        }
7314
7315        // Make sure all dynamic permissions have been assigned to a package,
7316        // and make sure there are no dangling permissions.
7317        it = mSettings.mPermissions.values().iterator();
7318        while (it.hasNext()) {
7319            final BasePermission bp = it.next();
7320            if (bp.type == BasePermission.TYPE_DYNAMIC) {
7321                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
7322                        + bp.name + " pkg=" + bp.sourcePackage
7323                        + " info=" + bp.pendingInfo);
7324                if (bp.packageSetting == null && bp.pendingInfo != null) {
7325                    final BasePermission tree = findPermissionTreeLP(bp.name);
7326                    if (tree != null && tree.perm != null) {
7327                        bp.packageSetting = tree.packageSetting;
7328                        bp.perm = new PackageParser.Permission(tree.perm.owner,
7329                                new PermissionInfo(bp.pendingInfo));
7330                        bp.perm.info.packageName = tree.perm.info.packageName;
7331                        bp.perm.info.name = bp.name;
7332                        bp.uid = tree.uid;
7333                    }
7334                }
7335            }
7336            if (bp.packageSetting == null) {
7337                // We may not yet have parsed the package, so just see if
7338                // we still know about its settings.
7339                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
7340            }
7341            if (bp.packageSetting == null) {
7342                Slog.w(TAG, "Removing dangling permission: " + bp.name
7343                        + " from package " + bp.sourcePackage);
7344                it.remove();
7345            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
7346                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
7347                    Slog.i(TAG, "Removing old permission: " + bp.name
7348                            + " from package " + bp.sourcePackage);
7349                    flags |= UPDATE_PERMISSIONS_ALL;
7350                    it.remove();
7351                }
7352            }
7353        }
7354
7355        // Now update the permissions for all packages, in particular
7356        // replace the granted permissions of the system packages.
7357        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
7358            for (PackageParser.Package pkg : mPackages.values()) {
7359                if (pkg != pkgInfo) {
7360                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
7361                            changingPkg);
7362                }
7363            }
7364        }
7365
7366        if (pkgInfo != null) {
7367            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
7368        }
7369    }
7370
7371    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
7372            String packageOfInterest) {
7373        // IMPORTANT: There are two types of permissions: install and runtime.
7374        // Install time permissions are granted when the app is installed to
7375        // all device users and users added in the future. Runtime permissions
7376        // are granted at runtime explicitly to specific users. Normal and signature
7377        // protected permissions are install time permissions. Dangerous permissions
7378        // are install permissions if the app's target SDK is Lollipop MR1 or older,
7379        // otherwise they are runtime permissions. This function does not manage
7380        // runtime permissions except for the case an app targeting Lollipop MR1
7381        // being upgraded to target a newer SDK, in which case dangerous permissions
7382        // are transformed from install time to runtime ones.
7383
7384        final PackageSetting ps = (PackageSetting) pkg.mExtras;
7385        if (ps == null) {
7386            return;
7387        }
7388
7389        PermissionsState permissionsState = ps.getPermissionsState();
7390        PermissionsState origPermissions = permissionsState;
7391
7392        final int[] currentUserIds = UserManagerService.getInstance().getUserIds();
7393
7394        int[] upgradeUserIds = PermissionsState.USERS_NONE;
7395        int[] changedRuntimePermissionUserIds = PermissionsState.USERS_NONE;
7396
7397        boolean changedInstallPermission = false;
7398
7399        if (replace) {
7400            ps.installPermissionsFixed = false;
7401            if (!ps.isSharedUser()) {
7402                origPermissions = new PermissionsState(permissionsState);
7403                permissionsState.reset();
7404            }
7405        }
7406
7407        permissionsState.setGlobalGids(mGlobalGids);
7408
7409        final int N = pkg.requestedPermissions.size();
7410        for (int i=0; i<N; i++) {
7411            final String name = pkg.requestedPermissions.get(i);
7412            final BasePermission bp = mSettings.mPermissions.get(name);
7413
7414            if (DEBUG_INSTALL) {
7415                Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7416            }
7417
7418            if (bp == null || bp.packageSetting == null) {
7419                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7420                    Slog.w(TAG, "Unknown permission " + name
7421                            + " in package " + pkg.packageName);
7422                }
7423                continue;
7424            }
7425
7426            final String perm = bp.name;
7427            boolean allowedSig = false;
7428            int grant = GRANT_DENIED;
7429
7430            // Keep track of app op permissions.
7431            if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7432                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7433                if (pkgs == null) {
7434                    pkgs = new ArraySet<>();
7435                    mAppOpPermissionPackages.put(bp.name, pkgs);
7436                }
7437                pkgs.add(pkg.packageName);
7438            }
7439
7440            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7441            switch (level) {
7442                case PermissionInfo.PROTECTION_NORMAL: {
7443                    // For all apps normal permissions are install time ones.
7444                    grant = GRANT_INSTALL;
7445                } break;
7446
7447                case PermissionInfo.PROTECTION_DANGEROUS: {
7448                    if (!RUNTIME_PERMISSIONS_ENABLED
7449                            || pkg.applicationInfo.targetSdkVersion
7450                                    <= Build.VERSION_CODES.LOLLIPOP_MR1) {
7451                        // For legacy apps dangerous permissions are install time ones.
7452                        grant = GRANT_INSTALL;
7453                    } else if (ps.isSystem()) {
7454                        final int[] updatedUserIds = ps.getPermissionsUpdatedForUserIds();
7455                        if (origPermissions.hasInstallPermission(bp.name)) {
7456                            // If a system app had an install permission, then the app was
7457                            // upgraded and we grant the permissions as runtime to all users.
7458                            grant = GRANT_UPGRADE;
7459                            upgradeUserIds = currentUserIds;
7460                        } else if (!Arrays.equals(updatedUserIds, currentUserIds)) {
7461                            // If users changed since the last permissions update for a
7462                            // system app, we grant the permission as runtime to the new users.
7463                            grant = GRANT_UPGRADE;
7464                            upgradeUserIds = currentUserIds;
7465                            for (int userId : updatedUserIds) {
7466                                upgradeUserIds = ArrayUtils.removeInt(upgradeUserIds, userId);
7467                            }
7468                        } else {
7469                            // Otherwise, we grant the permission as runtime if the app
7470                            // already had it, i.e. we preserve runtime permissions.
7471                            grant = GRANT_RUNTIME;
7472                        }
7473                    } else if (origPermissions.hasInstallPermission(bp.name)) {
7474                        // For legacy apps that became modern, install becomes runtime.
7475                        grant = GRANT_UPGRADE;
7476                        upgradeUserIds = currentUserIds;
7477                    } else if (replace) {
7478                        // For upgraded modern apps keep runtime permissions unchanged.
7479                        grant = GRANT_RUNTIME;
7480                    }
7481                } break;
7482
7483                case PermissionInfo.PROTECTION_SIGNATURE: {
7484                    // For all apps signature permissions are install time ones.
7485                    allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions);
7486                    if (allowedSig) {
7487                        grant = GRANT_INSTALL;
7488                    }
7489                } break;
7490            }
7491
7492            if (DEBUG_INSTALL) {
7493                Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7494            }
7495
7496            if (grant != GRANT_DENIED) {
7497                if (!isSystemApp(ps) && ps.installPermissionsFixed) {
7498                    // If this is an existing, non-system package, then
7499                    // we can't add any new permissions to it.
7500                    if (!allowedSig && !origPermissions.hasInstallPermission(perm)) {
7501                        // Except...  if this is a permission that was added
7502                        // to the platform (note: need to only do this when
7503                        // updating the platform).
7504                        if (!isNewPlatformPermissionForPackage(perm, pkg)) {
7505                            grant = GRANT_DENIED;
7506                        }
7507                    }
7508                }
7509
7510                switch (grant) {
7511                    case GRANT_INSTALL: {
7512                        // Grant an install permission.
7513                        if (permissionsState.grantInstallPermission(bp) !=
7514                                PermissionsState.PERMISSION_OPERATION_FAILURE) {
7515                            changedInstallPermission = true;
7516                        }
7517                    } break;
7518
7519                    case GRANT_RUNTIME: {
7520                        // Grant previously granted runtime permissions.
7521                        for (int userId : UserManagerService.getInstance().getUserIds()) {
7522                            if (origPermissions.hasRuntimePermission(bp.name, userId)) {
7523                                if (permissionsState.grantRuntimePermission(bp, userId) ==
7524                                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7525                                    // If we cannot put the permission as it was, we have to write.
7526                                    changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7527                                            changedRuntimePermissionUserIds, userId);
7528                                }
7529                            }
7530                        }
7531                    } break;
7532
7533                    case GRANT_UPGRADE: {
7534                        // Grant runtime permissions for a previously held install permission.
7535                        permissionsState.revokeInstallPermission(bp);
7536                        for (int userId : upgradeUserIds) {
7537                            if (permissionsState.grantRuntimePermission(bp, userId) !=
7538                                    PermissionsState.PERMISSION_OPERATION_FAILURE) {
7539                                // If we granted the permission, we have to write.
7540                                changedRuntimePermissionUserIds = ArrayUtils.appendInt(
7541                                        changedRuntimePermissionUserIds, userId);
7542                            }
7543                        }
7544                    } break;
7545
7546                    default: {
7547                        if (packageOfInterest == null
7548                                || packageOfInterest.equals(pkg.packageName)) {
7549                            Slog.w(TAG, "Not granting permission " + perm
7550                                    + " to package " + pkg.packageName
7551                                    + " because it was previously installed without");
7552                        }
7553                    } break;
7554                }
7555            } else {
7556                if (permissionsState.revokeInstallPermission(bp) !=
7557                        PermissionsState.PERMISSION_OPERATION_FAILURE) {
7558                    changedInstallPermission = true;
7559                    Slog.i(TAG, "Un-granting permission " + perm
7560                            + " from package " + pkg.packageName
7561                            + " (protectionLevel=" + bp.protectionLevel
7562                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7563                            + ")");
7564                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7565                    // Don't print warning for app op permissions, since it is fine for them
7566                    // not to be granted, there is a UI for the user to decide.
7567                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7568                        Slog.w(TAG, "Not granting permission " + perm
7569                                + " to package " + pkg.packageName
7570                                + " (protectionLevel=" + bp.protectionLevel
7571                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7572                                + ")");
7573                    }
7574                }
7575            }
7576        }
7577
7578        if ((changedInstallPermission || replace) && !ps.installPermissionsFixed &&
7579                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7580            // This is the first that we have heard about this package, so the
7581            // permissions we have now selected are fixed until explicitly
7582            // changed.
7583            ps.installPermissionsFixed = true;
7584        }
7585
7586        ps.setPermissionsUpdatedForUserIds(currentUserIds);
7587
7588        // Persist the runtime permissions state for users with changes.
7589        if (RUNTIME_PERMISSIONS_ENABLED) {
7590            for (int userId : changedRuntimePermissionUserIds) {
7591                mSettings.writeRuntimePermissionsForUserLPr(userId, true);
7592            }
7593        }
7594    }
7595
7596    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7597        boolean allowed = false;
7598        final int NP = PackageParser.NEW_PERMISSIONS.length;
7599        for (int ip=0; ip<NP; ip++) {
7600            final PackageParser.NewPermissionInfo npi
7601                    = PackageParser.NEW_PERMISSIONS[ip];
7602            if (npi.name.equals(perm)
7603                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7604                allowed = true;
7605                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7606                        + pkg.packageName);
7607                break;
7608            }
7609        }
7610        return allowed;
7611    }
7612
7613    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7614            BasePermission bp, PermissionsState origPermissions) {
7615        boolean allowed;
7616        allowed = (compareSignatures(
7617                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7618                        == PackageManager.SIGNATURE_MATCH)
7619                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7620                        == PackageManager.SIGNATURE_MATCH);
7621        if (!allowed && (bp.protectionLevel
7622                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7623            if (isSystemApp(pkg)) {
7624                // For updated system applications, a system permission
7625                // is granted only if it had been defined by the original application.
7626                if (pkg.isUpdatedSystemApp()) {
7627                    final PackageSetting sysPs = mSettings
7628                            .getDisabledSystemPkgLPr(pkg.packageName);
7629                    if (sysPs.getPermissionsState().hasInstallPermission(perm)) {
7630                        // If the original was granted this permission, we take
7631                        // that grant decision as read and propagate it to the
7632                        // update.
7633                        if (sysPs.isPrivileged()) {
7634                            allowed = true;
7635                        }
7636                    } else {
7637                        // The system apk may have been updated with an older
7638                        // version of the one on the data partition, but which
7639                        // granted a new system permission that it didn't have
7640                        // before.  In this case we do want to allow the app to
7641                        // now get the new permission if the ancestral apk is
7642                        // privileged to get it.
7643                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7644                            for (int j=0;
7645                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7646                                if (perm.equals(
7647                                        sysPs.pkg.requestedPermissions.get(j))) {
7648                                    allowed = true;
7649                                    break;
7650                                }
7651                            }
7652                        }
7653                    }
7654                } else {
7655                    allowed = isPrivilegedApp(pkg);
7656                }
7657            }
7658        }
7659        if (!allowed && (bp.protectionLevel
7660                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7661            // For development permissions, a development permission
7662            // is granted only if it was already granted.
7663            allowed = origPermissions.hasInstallPermission(perm);
7664        }
7665        return allowed;
7666    }
7667
7668    final class ActivityIntentResolver
7669            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7670        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7671                boolean defaultOnly, int userId) {
7672            if (!sUserManager.exists(userId)) return null;
7673            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7674            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7675        }
7676
7677        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7678                int userId) {
7679            if (!sUserManager.exists(userId)) return null;
7680            mFlags = flags;
7681            return super.queryIntent(intent, resolvedType,
7682                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7683        }
7684
7685        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7686                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7687            if (!sUserManager.exists(userId)) return null;
7688            if (packageActivities == null) {
7689                return null;
7690            }
7691            mFlags = flags;
7692            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7693            final int N = packageActivities.size();
7694            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7695                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7696
7697            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7698            for (int i = 0; i < N; ++i) {
7699                intentFilters = packageActivities.get(i).intents;
7700                if (intentFilters != null && intentFilters.size() > 0) {
7701                    PackageParser.ActivityIntentInfo[] array =
7702                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7703                    intentFilters.toArray(array);
7704                    listCut.add(array);
7705                }
7706            }
7707            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7708        }
7709
7710        public final void addActivity(PackageParser.Activity a, String type) {
7711            final boolean systemApp = a.info.applicationInfo.isSystemApp();
7712            mActivities.put(a.getComponentName(), a);
7713            if (DEBUG_SHOW_INFO)
7714                Log.v(
7715                TAG, "  " + type + " " +
7716                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7717            if (DEBUG_SHOW_INFO)
7718                Log.v(TAG, "    Class=" + a.info.name);
7719            final int NI = a.intents.size();
7720            for (int j=0; j<NI; j++) {
7721                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7722                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7723                    intent.setPriority(0);
7724                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7725                            + a.className + " with priority > 0, forcing to 0");
7726                }
7727                if (DEBUG_SHOW_INFO) {
7728                    Log.v(TAG, "    IntentFilter:");
7729                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7730                }
7731                if (!intent.debugCheck()) {
7732                    Log.w(TAG, "==> For Activity " + a.info.name);
7733                }
7734                addFilter(intent);
7735            }
7736        }
7737
7738        public final void removeActivity(PackageParser.Activity a, String type) {
7739            mActivities.remove(a.getComponentName());
7740            if (DEBUG_SHOW_INFO) {
7741                Log.v(TAG, "  " + type + " "
7742                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7743                                : a.info.name) + ":");
7744                Log.v(TAG, "    Class=" + a.info.name);
7745            }
7746            final int NI = a.intents.size();
7747            for (int j=0; j<NI; j++) {
7748                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7749                if (DEBUG_SHOW_INFO) {
7750                    Log.v(TAG, "    IntentFilter:");
7751                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7752                }
7753                removeFilter(intent);
7754            }
7755        }
7756
7757        @Override
7758        protected boolean allowFilterResult(
7759                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7760            ActivityInfo filterAi = filter.activity.info;
7761            for (int i=dest.size()-1; i>=0; i--) {
7762                ActivityInfo destAi = dest.get(i).activityInfo;
7763                if (destAi.name == filterAi.name
7764                        && destAi.packageName == filterAi.packageName) {
7765                    return false;
7766                }
7767            }
7768            return true;
7769        }
7770
7771        @Override
7772        protected ActivityIntentInfo[] newArray(int size) {
7773            return new ActivityIntentInfo[size];
7774        }
7775
7776        @Override
7777        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7778            if (!sUserManager.exists(userId)) return true;
7779            PackageParser.Package p = filter.activity.owner;
7780            if (p != null) {
7781                PackageSetting ps = (PackageSetting)p.mExtras;
7782                if (ps != null) {
7783                    // System apps are never considered stopped for purposes of
7784                    // filtering, because there may be no way for the user to
7785                    // actually re-launch them.
7786                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7787                            && ps.getStopped(userId);
7788                }
7789            }
7790            return false;
7791        }
7792
7793        @Override
7794        protected boolean isPackageForFilter(String packageName,
7795                PackageParser.ActivityIntentInfo info) {
7796            return packageName.equals(info.activity.owner.packageName);
7797        }
7798
7799        @Override
7800        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7801                int match, int userId) {
7802            if (!sUserManager.exists(userId)) return null;
7803            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7804                return null;
7805            }
7806            final PackageParser.Activity activity = info.activity;
7807            if (mSafeMode && (activity.info.applicationInfo.flags
7808                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7809                return null;
7810            }
7811            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7812            if (ps == null) {
7813                return null;
7814            }
7815            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7816                    ps.readUserState(userId), userId);
7817            if (ai == null) {
7818                return null;
7819            }
7820            final ResolveInfo res = new ResolveInfo();
7821            res.activityInfo = ai;
7822            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7823                res.filter = info;
7824            }
7825            if (info != null) {
7826                res.filterNeedsVerification = info.needsVerification();
7827            }
7828            res.priority = info.getPriority();
7829            res.preferredOrder = activity.owner.mPreferredOrder;
7830            //System.out.println("Result: " + res.activityInfo.className +
7831            //                   " = " + res.priority);
7832            res.match = match;
7833            res.isDefault = info.hasDefault;
7834            res.labelRes = info.labelRes;
7835            res.nonLocalizedLabel = info.nonLocalizedLabel;
7836            if (userNeedsBadging(userId)) {
7837                res.noResourceId = true;
7838            } else {
7839                res.icon = info.icon;
7840            }
7841            res.system = res.activityInfo.applicationInfo.isSystemApp();
7842            return res;
7843        }
7844
7845        @Override
7846        protected void sortResults(List<ResolveInfo> results) {
7847            Collections.sort(results, mResolvePrioritySorter);
7848        }
7849
7850        @Override
7851        protected void dumpFilter(PrintWriter out, String prefix,
7852                PackageParser.ActivityIntentInfo filter) {
7853            out.print(prefix); out.print(
7854                    Integer.toHexString(System.identityHashCode(filter.activity)));
7855                    out.print(' ');
7856                    filter.activity.printComponentShortName(out);
7857                    out.print(" filter ");
7858                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7859        }
7860
7861        @Override
7862        protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) {
7863            return filter.activity;
7864        }
7865
7866        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
7867            PackageParser.Activity activity = (PackageParser.Activity)label;
7868            out.print(prefix); out.print(
7869                    Integer.toHexString(System.identityHashCode(activity)));
7870                    out.print(' ');
7871                    activity.printComponentShortName(out);
7872            if (count > 1) {
7873                out.print(" ("); out.print(count); out.print(" filters)");
7874            }
7875            out.println();
7876        }
7877
7878//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7879//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7880//            final List<ResolveInfo> retList = Lists.newArrayList();
7881//            while (i.hasNext()) {
7882//                final ResolveInfo resolveInfo = i.next();
7883//                if (isEnabledLP(resolveInfo.activityInfo)) {
7884//                    retList.add(resolveInfo);
7885//                }
7886//            }
7887//            return retList;
7888//        }
7889
7890        // Keys are String (activity class name), values are Activity.
7891        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7892                = new ArrayMap<ComponentName, PackageParser.Activity>();
7893        private int mFlags;
7894    }
7895
7896    private final class ServiceIntentResolver
7897            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7898        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7899                boolean defaultOnly, int userId) {
7900            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7901            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7902        }
7903
7904        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7905                int userId) {
7906            if (!sUserManager.exists(userId)) return null;
7907            mFlags = flags;
7908            return super.queryIntent(intent, resolvedType,
7909                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7910        }
7911
7912        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7913                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7914            if (!sUserManager.exists(userId)) return null;
7915            if (packageServices == null) {
7916                return null;
7917            }
7918            mFlags = flags;
7919            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7920            final int N = packageServices.size();
7921            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7922                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7923
7924            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7925            for (int i = 0; i < N; ++i) {
7926                intentFilters = packageServices.get(i).intents;
7927                if (intentFilters != null && intentFilters.size() > 0) {
7928                    PackageParser.ServiceIntentInfo[] array =
7929                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7930                    intentFilters.toArray(array);
7931                    listCut.add(array);
7932                }
7933            }
7934            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7935        }
7936
7937        public final void addService(PackageParser.Service s) {
7938            mServices.put(s.getComponentName(), s);
7939            if (DEBUG_SHOW_INFO) {
7940                Log.v(TAG, "  "
7941                        + (s.info.nonLocalizedLabel != null
7942                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7943                Log.v(TAG, "    Class=" + s.info.name);
7944            }
7945            final int NI = s.intents.size();
7946            int j;
7947            for (j=0; j<NI; j++) {
7948                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7949                if (DEBUG_SHOW_INFO) {
7950                    Log.v(TAG, "    IntentFilter:");
7951                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7952                }
7953                if (!intent.debugCheck()) {
7954                    Log.w(TAG, "==> For Service " + s.info.name);
7955                }
7956                addFilter(intent);
7957            }
7958        }
7959
7960        public final void removeService(PackageParser.Service s) {
7961            mServices.remove(s.getComponentName());
7962            if (DEBUG_SHOW_INFO) {
7963                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7964                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7965                Log.v(TAG, "    Class=" + s.info.name);
7966            }
7967            final int NI = s.intents.size();
7968            int j;
7969            for (j=0; j<NI; j++) {
7970                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7971                if (DEBUG_SHOW_INFO) {
7972                    Log.v(TAG, "    IntentFilter:");
7973                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7974                }
7975                removeFilter(intent);
7976            }
7977        }
7978
7979        @Override
7980        protected boolean allowFilterResult(
7981                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7982            ServiceInfo filterSi = filter.service.info;
7983            for (int i=dest.size()-1; i>=0; i--) {
7984                ServiceInfo destAi = dest.get(i).serviceInfo;
7985                if (destAi.name == filterSi.name
7986                        && destAi.packageName == filterSi.packageName) {
7987                    return false;
7988                }
7989            }
7990            return true;
7991        }
7992
7993        @Override
7994        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7995            return new PackageParser.ServiceIntentInfo[size];
7996        }
7997
7998        @Override
7999        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
8000            if (!sUserManager.exists(userId)) return true;
8001            PackageParser.Package p = filter.service.owner;
8002            if (p != null) {
8003                PackageSetting ps = (PackageSetting)p.mExtras;
8004                if (ps != null) {
8005                    // System apps are never considered stopped for purposes of
8006                    // filtering, because there may be no way for the user to
8007                    // actually re-launch them.
8008                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8009                            && ps.getStopped(userId);
8010                }
8011            }
8012            return false;
8013        }
8014
8015        @Override
8016        protected boolean isPackageForFilter(String packageName,
8017                PackageParser.ServiceIntentInfo info) {
8018            return packageName.equals(info.service.owner.packageName);
8019        }
8020
8021        @Override
8022        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
8023                int match, int userId) {
8024            if (!sUserManager.exists(userId)) return null;
8025            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
8026            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
8027                return null;
8028            }
8029            final PackageParser.Service service = info.service;
8030            if (mSafeMode && (service.info.applicationInfo.flags
8031                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
8032                return null;
8033            }
8034            PackageSetting ps = (PackageSetting) service.owner.mExtras;
8035            if (ps == null) {
8036                return null;
8037            }
8038            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
8039                    ps.readUserState(userId), userId);
8040            if (si == null) {
8041                return null;
8042            }
8043            final ResolveInfo res = new ResolveInfo();
8044            res.serviceInfo = si;
8045            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
8046                res.filter = filter;
8047            }
8048            res.priority = info.getPriority();
8049            res.preferredOrder = service.owner.mPreferredOrder;
8050            res.match = match;
8051            res.isDefault = info.hasDefault;
8052            res.labelRes = info.labelRes;
8053            res.nonLocalizedLabel = info.nonLocalizedLabel;
8054            res.icon = info.icon;
8055            res.system = res.serviceInfo.applicationInfo.isSystemApp();
8056            return res;
8057        }
8058
8059        @Override
8060        protected void sortResults(List<ResolveInfo> results) {
8061            Collections.sort(results, mResolvePrioritySorter);
8062        }
8063
8064        @Override
8065        protected void dumpFilter(PrintWriter out, String prefix,
8066                PackageParser.ServiceIntentInfo filter) {
8067            out.print(prefix); out.print(
8068                    Integer.toHexString(System.identityHashCode(filter.service)));
8069                    out.print(' ');
8070                    filter.service.printComponentShortName(out);
8071                    out.print(" filter ");
8072                    out.println(Integer.toHexString(System.identityHashCode(filter)));
8073        }
8074
8075        @Override
8076        protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) {
8077            return filter.service;
8078        }
8079
8080        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8081            PackageParser.Service service = (PackageParser.Service)label;
8082            out.print(prefix); out.print(
8083                    Integer.toHexString(System.identityHashCode(service)));
8084                    out.print(' ');
8085                    service.printComponentShortName(out);
8086            if (count > 1) {
8087                out.print(" ("); out.print(count); out.print(" filters)");
8088            }
8089            out.println();
8090        }
8091
8092//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
8093//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
8094//            final List<ResolveInfo> retList = Lists.newArrayList();
8095//            while (i.hasNext()) {
8096//                final ResolveInfo resolveInfo = (ResolveInfo) i;
8097//                if (isEnabledLP(resolveInfo.serviceInfo)) {
8098//                    retList.add(resolveInfo);
8099//                }
8100//            }
8101//            return retList;
8102//        }
8103
8104        // Keys are String (activity class name), values are Activity.
8105        private final ArrayMap<ComponentName, PackageParser.Service> mServices
8106                = new ArrayMap<ComponentName, PackageParser.Service>();
8107        private int mFlags;
8108    };
8109
8110    private final class ProviderIntentResolver
8111            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
8112        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
8113                boolean defaultOnly, int userId) {
8114            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
8115            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
8116        }
8117
8118        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
8119                int userId) {
8120            if (!sUserManager.exists(userId))
8121                return null;
8122            mFlags = flags;
8123            return super.queryIntent(intent, resolvedType,
8124                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
8125        }
8126
8127        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
8128                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
8129            if (!sUserManager.exists(userId))
8130                return null;
8131            if (packageProviders == null) {
8132                return null;
8133            }
8134            mFlags = flags;
8135            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
8136            final int N = packageProviders.size();
8137            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
8138                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
8139
8140            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
8141            for (int i = 0; i < N; ++i) {
8142                intentFilters = packageProviders.get(i).intents;
8143                if (intentFilters != null && intentFilters.size() > 0) {
8144                    PackageParser.ProviderIntentInfo[] array =
8145                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
8146                    intentFilters.toArray(array);
8147                    listCut.add(array);
8148                }
8149            }
8150            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
8151        }
8152
8153        public final void addProvider(PackageParser.Provider p) {
8154            if (mProviders.containsKey(p.getComponentName())) {
8155                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
8156                return;
8157            }
8158
8159            mProviders.put(p.getComponentName(), p);
8160            if (DEBUG_SHOW_INFO) {
8161                Log.v(TAG, "  "
8162                        + (p.info.nonLocalizedLabel != null
8163                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
8164                Log.v(TAG, "    Class=" + p.info.name);
8165            }
8166            final int NI = p.intents.size();
8167            int j;
8168            for (j = 0; j < NI; j++) {
8169                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8170                if (DEBUG_SHOW_INFO) {
8171                    Log.v(TAG, "    IntentFilter:");
8172                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8173                }
8174                if (!intent.debugCheck()) {
8175                    Log.w(TAG, "==> For Provider " + p.info.name);
8176                }
8177                addFilter(intent);
8178            }
8179        }
8180
8181        public final void removeProvider(PackageParser.Provider p) {
8182            mProviders.remove(p.getComponentName());
8183            if (DEBUG_SHOW_INFO) {
8184                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
8185                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
8186                Log.v(TAG, "    Class=" + p.info.name);
8187            }
8188            final int NI = p.intents.size();
8189            int j;
8190            for (j = 0; j < NI; j++) {
8191                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
8192                if (DEBUG_SHOW_INFO) {
8193                    Log.v(TAG, "    IntentFilter:");
8194                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
8195                }
8196                removeFilter(intent);
8197            }
8198        }
8199
8200        @Override
8201        protected boolean allowFilterResult(
8202                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
8203            ProviderInfo filterPi = filter.provider.info;
8204            for (int i = dest.size() - 1; i >= 0; i--) {
8205                ProviderInfo destPi = dest.get(i).providerInfo;
8206                if (destPi.name == filterPi.name
8207                        && destPi.packageName == filterPi.packageName) {
8208                    return false;
8209                }
8210            }
8211            return true;
8212        }
8213
8214        @Override
8215        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
8216            return new PackageParser.ProviderIntentInfo[size];
8217        }
8218
8219        @Override
8220        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
8221            if (!sUserManager.exists(userId))
8222                return true;
8223            PackageParser.Package p = filter.provider.owner;
8224            if (p != null) {
8225                PackageSetting ps = (PackageSetting) p.mExtras;
8226                if (ps != null) {
8227                    // System apps are never considered stopped for purposes of
8228                    // filtering, because there may be no way for the user to
8229                    // actually re-launch them.
8230                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
8231                            && ps.getStopped(userId);
8232                }
8233            }
8234            return false;
8235        }
8236
8237        @Override
8238        protected boolean isPackageForFilter(String packageName,
8239                PackageParser.ProviderIntentInfo info) {
8240            return packageName.equals(info.provider.owner.packageName);
8241        }
8242
8243        @Override
8244        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
8245                int match, int userId) {
8246            if (!sUserManager.exists(userId))
8247                return null;
8248            final PackageParser.ProviderIntentInfo info = filter;
8249            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
8250                return null;
8251            }
8252            final PackageParser.Provider provider = info.provider;
8253            if (mSafeMode && (provider.info.applicationInfo.flags
8254                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
8255                return null;
8256            }
8257            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
8258            if (ps == null) {
8259                return null;
8260            }
8261            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
8262                    ps.readUserState(userId), userId);
8263            if (pi == null) {
8264                return null;
8265            }
8266            final ResolveInfo res = new ResolveInfo();
8267            res.providerInfo = pi;
8268            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
8269                res.filter = filter;
8270            }
8271            res.priority = info.getPriority();
8272            res.preferredOrder = provider.owner.mPreferredOrder;
8273            res.match = match;
8274            res.isDefault = info.hasDefault;
8275            res.labelRes = info.labelRes;
8276            res.nonLocalizedLabel = info.nonLocalizedLabel;
8277            res.icon = info.icon;
8278            res.system = res.providerInfo.applicationInfo.isSystemApp();
8279            return res;
8280        }
8281
8282        @Override
8283        protected void sortResults(List<ResolveInfo> results) {
8284            Collections.sort(results, mResolvePrioritySorter);
8285        }
8286
8287        @Override
8288        protected void dumpFilter(PrintWriter out, String prefix,
8289                PackageParser.ProviderIntentInfo filter) {
8290            out.print(prefix);
8291            out.print(
8292                    Integer.toHexString(System.identityHashCode(filter.provider)));
8293            out.print(' ');
8294            filter.provider.printComponentShortName(out);
8295            out.print(" filter ");
8296            out.println(Integer.toHexString(System.identityHashCode(filter)));
8297        }
8298
8299        @Override
8300        protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) {
8301            return filter.provider;
8302        }
8303
8304        protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) {
8305            PackageParser.Provider provider = (PackageParser.Provider)label;
8306            out.print(prefix); out.print(
8307                    Integer.toHexString(System.identityHashCode(provider)));
8308                    out.print(' ');
8309                    provider.printComponentShortName(out);
8310            if (count > 1) {
8311                out.print(" ("); out.print(count); out.print(" filters)");
8312            }
8313            out.println();
8314        }
8315
8316        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
8317                = new ArrayMap<ComponentName, PackageParser.Provider>();
8318        private int mFlags;
8319    };
8320
8321    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
8322            new Comparator<ResolveInfo>() {
8323        public int compare(ResolveInfo r1, ResolveInfo r2) {
8324            int v1 = r1.priority;
8325            int v2 = r2.priority;
8326            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
8327            if (v1 != v2) {
8328                return (v1 > v2) ? -1 : 1;
8329            }
8330            v1 = r1.preferredOrder;
8331            v2 = r2.preferredOrder;
8332            if (v1 != v2) {
8333                return (v1 > v2) ? -1 : 1;
8334            }
8335            if (r1.isDefault != r2.isDefault) {
8336                return r1.isDefault ? -1 : 1;
8337            }
8338            v1 = r1.match;
8339            v2 = r2.match;
8340            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
8341            if (v1 != v2) {
8342                return (v1 > v2) ? -1 : 1;
8343            }
8344            if (r1.system != r2.system) {
8345                return r1.system ? -1 : 1;
8346            }
8347            return 0;
8348        }
8349    };
8350
8351    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
8352            new Comparator<ProviderInfo>() {
8353        public int compare(ProviderInfo p1, ProviderInfo p2) {
8354            final int v1 = p1.initOrder;
8355            final int v2 = p2.initOrder;
8356            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
8357        }
8358    };
8359
8360    static final void sendPackageBroadcast(String action, String pkg,
8361            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
8362            int[] userIds) {
8363        IActivityManager am = ActivityManagerNative.getDefault();
8364        if (am != null) {
8365            try {
8366                if (userIds == null) {
8367                    userIds = am.getRunningUserIds();
8368                }
8369                for (int id : userIds) {
8370                    final Intent intent = new Intent(action,
8371                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
8372                    if (extras != null) {
8373                        intent.putExtras(extras);
8374                    }
8375                    if (targetPkg != null) {
8376                        intent.setPackage(targetPkg);
8377                    }
8378                    // Modify the UID when posting to other users
8379                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
8380                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
8381                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
8382                        intent.putExtra(Intent.EXTRA_UID, uid);
8383                    }
8384                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
8385                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
8386                    if (DEBUG_BROADCASTS) {
8387                        RuntimeException here = new RuntimeException("here");
8388                        here.fillInStackTrace();
8389                        Slog.d(TAG, "Sending to user " + id + ": "
8390                                + intent.toShortString(false, true, false, false)
8391                                + " " + intent.getExtras(), here);
8392                    }
8393                    am.broadcastIntent(null, intent, null, finishedReceiver,
8394                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
8395                            finishedReceiver != null, false, id);
8396                }
8397            } catch (RemoteException ex) {
8398            }
8399        }
8400    }
8401
8402    /**
8403     * Check if the external storage media is available. This is true if there
8404     * is a mounted external storage medium or if the external storage is
8405     * emulated.
8406     */
8407    private boolean isExternalMediaAvailable() {
8408        return mMediaMounted || Environment.isExternalStorageEmulated();
8409    }
8410
8411    @Override
8412    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
8413        // writer
8414        synchronized (mPackages) {
8415            if (!isExternalMediaAvailable()) {
8416                // If the external storage is no longer mounted at this point,
8417                // the caller may not have been able to delete all of this
8418                // packages files and can not delete any more.  Bail.
8419                return null;
8420            }
8421            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
8422            if (lastPackage != null) {
8423                pkgs.remove(lastPackage);
8424            }
8425            if (pkgs.size() > 0) {
8426                return pkgs.get(0);
8427            }
8428        }
8429        return null;
8430    }
8431
8432    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
8433        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
8434                userId, andCode ? 1 : 0, packageName);
8435        if (mSystemReady) {
8436            msg.sendToTarget();
8437        } else {
8438            if (mPostSystemReadyMessages == null) {
8439                mPostSystemReadyMessages = new ArrayList<>();
8440            }
8441            mPostSystemReadyMessages.add(msg);
8442        }
8443    }
8444
8445    void startCleaningPackages() {
8446        // reader
8447        synchronized (mPackages) {
8448            if (!isExternalMediaAvailable()) {
8449                return;
8450            }
8451            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
8452                return;
8453            }
8454        }
8455        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
8456        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
8457        IActivityManager am = ActivityManagerNative.getDefault();
8458        if (am != null) {
8459            try {
8460                am.startService(null, intent, null, UserHandle.USER_OWNER);
8461            } catch (RemoteException e) {
8462            }
8463        }
8464    }
8465
8466    @Override
8467    public void installPackage(String originPath, IPackageInstallObserver2 observer,
8468            int installFlags, String installerPackageName, VerificationParams verificationParams,
8469            String packageAbiOverride) {
8470        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
8471                packageAbiOverride, UserHandle.getCallingUserId());
8472    }
8473
8474    @Override
8475    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
8476            int installFlags, String installerPackageName, VerificationParams verificationParams,
8477            String packageAbiOverride, int userId) {
8478        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
8479
8480        final int callingUid = Binder.getCallingUid();
8481        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
8482
8483        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8484            try {
8485                if (observer != null) {
8486                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
8487                }
8488            } catch (RemoteException re) {
8489            }
8490            return;
8491        }
8492
8493        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
8494            installFlags |= PackageManager.INSTALL_FROM_ADB;
8495
8496        } else {
8497            // Caller holds INSTALL_PACKAGES permission, so we're less strict
8498            // about installerPackageName.
8499
8500            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
8501            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
8502        }
8503
8504        UserHandle user;
8505        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
8506            user = UserHandle.ALL;
8507        } else {
8508            user = new UserHandle(userId);
8509        }
8510
8511        verificationParams.setInstallerUid(callingUid);
8512
8513        final File originFile = new File(originPath);
8514        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
8515
8516        final Message msg = mHandler.obtainMessage(INIT_COPY);
8517        msg.obj = new InstallParams(origin, observer, installFlags,
8518                installerPackageName, verificationParams, user, packageAbiOverride);
8519        mHandler.sendMessage(msg);
8520    }
8521
8522    void installStage(String packageName, File stagedDir, String stagedCid,
8523            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
8524            String installerPackageName, int installerUid, UserHandle user) {
8525        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
8526                params.referrerUri, installerUid, null);
8527
8528        final OriginInfo origin;
8529        if (stagedDir != null) {
8530            origin = OriginInfo.fromStagedFile(stagedDir);
8531        } else {
8532            origin = OriginInfo.fromStagedContainer(stagedCid);
8533        }
8534
8535        final Message msg = mHandler.obtainMessage(INIT_COPY);
8536        msg.obj = new InstallParams(origin, observer, params.installFlags,
8537                installerPackageName, verifParams, user, params.abiOverride);
8538        mHandler.sendMessage(msg);
8539    }
8540
8541    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8542        Bundle extras = new Bundle(1);
8543        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8544
8545        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8546                packageName, extras, null, null, new int[] {userId});
8547        try {
8548            IActivityManager am = ActivityManagerNative.getDefault();
8549            final boolean isSystem =
8550                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8551            if (isSystem && am.isUserRunning(userId, false)) {
8552                // The just-installed/enabled app is bundled on the system, so presumed
8553                // to be able to run automatically without needing an explicit launch.
8554                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8555                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8556                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8557                        .setPackage(packageName);
8558                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8559                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8560            }
8561        } catch (RemoteException e) {
8562            // shouldn't happen
8563            Slog.w(TAG, "Unable to bootstrap installed package", e);
8564        }
8565    }
8566
8567    @Override
8568    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8569            int userId) {
8570        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8571        PackageSetting pkgSetting;
8572        final int uid = Binder.getCallingUid();
8573        enforceCrossUserPermission(uid, userId, true, true,
8574                "setApplicationHiddenSetting for user " + userId);
8575
8576        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8577            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8578            return false;
8579        }
8580
8581        long callingId = Binder.clearCallingIdentity();
8582        try {
8583            boolean sendAdded = false;
8584            boolean sendRemoved = false;
8585            // writer
8586            synchronized (mPackages) {
8587                pkgSetting = mSettings.mPackages.get(packageName);
8588                if (pkgSetting == null) {
8589                    return false;
8590                }
8591                if (pkgSetting.getHidden(userId) != hidden) {
8592                    pkgSetting.setHidden(hidden, userId);
8593                    mSettings.writePackageRestrictionsLPr(userId);
8594                    if (hidden) {
8595                        sendRemoved = true;
8596                    } else {
8597                        sendAdded = true;
8598                    }
8599                }
8600            }
8601            if (sendAdded) {
8602                sendPackageAddedForUser(packageName, pkgSetting, userId);
8603                return true;
8604            }
8605            if (sendRemoved) {
8606                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8607                        "hiding pkg");
8608                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8609            }
8610        } finally {
8611            Binder.restoreCallingIdentity(callingId);
8612        }
8613        return false;
8614    }
8615
8616    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8617            int userId) {
8618        final PackageRemovedInfo info = new PackageRemovedInfo();
8619        info.removedPackage = packageName;
8620        info.removedUsers = new int[] {userId};
8621        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8622        info.sendBroadcast(false, false, false);
8623    }
8624
8625    /**
8626     * Returns true if application is not found or there was an error. Otherwise it returns
8627     * the hidden state of the package for the given user.
8628     */
8629    @Override
8630    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8631        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8632        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8633                false, "getApplicationHidden for user " + userId);
8634        PackageSetting pkgSetting;
8635        long callingId = Binder.clearCallingIdentity();
8636        try {
8637            // writer
8638            synchronized (mPackages) {
8639                pkgSetting = mSettings.mPackages.get(packageName);
8640                if (pkgSetting == null) {
8641                    return true;
8642                }
8643                return pkgSetting.getHidden(userId);
8644            }
8645        } finally {
8646            Binder.restoreCallingIdentity(callingId);
8647        }
8648    }
8649
8650    /**
8651     * @hide
8652     */
8653    @Override
8654    public int installExistingPackageAsUser(String packageName, int userId) {
8655        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8656                null);
8657        PackageSetting pkgSetting;
8658        final int uid = Binder.getCallingUid();
8659        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8660                + userId);
8661        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8662            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8663        }
8664
8665        long callingId = Binder.clearCallingIdentity();
8666        try {
8667            boolean sendAdded = false;
8668            Bundle extras = new Bundle(1);
8669
8670            // writer
8671            synchronized (mPackages) {
8672                pkgSetting = mSettings.mPackages.get(packageName);
8673                if (pkgSetting == null) {
8674                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8675                }
8676                if (!pkgSetting.getInstalled(userId)) {
8677                    pkgSetting.setInstalled(true, userId);
8678                    pkgSetting.setHidden(false, userId);
8679                    mSettings.writePackageRestrictionsLPr(userId);
8680                    sendAdded = true;
8681                }
8682            }
8683
8684            if (sendAdded) {
8685                sendPackageAddedForUser(packageName, pkgSetting, userId);
8686            }
8687        } finally {
8688            Binder.restoreCallingIdentity(callingId);
8689        }
8690
8691        return PackageManager.INSTALL_SUCCEEDED;
8692    }
8693
8694    boolean isUserRestricted(int userId, String restrictionKey) {
8695        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8696        if (restrictions.getBoolean(restrictionKey, false)) {
8697            Log.w(TAG, "User is restricted: " + restrictionKey);
8698            return true;
8699        }
8700        return false;
8701    }
8702
8703    @Override
8704    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8705        mContext.enforceCallingOrSelfPermission(
8706                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8707                "Only package verification agents can verify applications");
8708
8709        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8710        final PackageVerificationResponse response = new PackageVerificationResponse(
8711                verificationCode, Binder.getCallingUid());
8712        msg.arg1 = id;
8713        msg.obj = response;
8714        mHandler.sendMessage(msg);
8715    }
8716
8717    @Override
8718    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8719            long millisecondsToDelay) {
8720        mContext.enforceCallingOrSelfPermission(
8721                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8722                "Only package verification agents can extend verification timeouts");
8723
8724        final PackageVerificationState state = mPendingVerification.get(id);
8725        final PackageVerificationResponse response = new PackageVerificationResponse(
8726                verificationCodeAtTimeout, Binder.getCallingUid());
8727
8728        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8729            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8730        }
8731        if (millisecondsToDelay < 0) {
8732            millisecondsToDelay = 0;
8733        }
8734        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8735                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8736            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8737        }
8738
8739        if ((state != null) && !state.timeoutExtended()) {
8740            state.extendTimeout();
8741
8742            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8743            msg.arg1 = id;
8744            msg.obj = response;
8745            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8746        }
8747    }
8748
8749    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8750            int verificationCode, UserHandle user) {
8751        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8752        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8753        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8754        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8755        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8756
8757        mContext.sendBroadcastAsUser(intent, user,
8758                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8759    }
8760
8761    private ComponentName matchComponentForVerifier(String packageName,
8762            List<ResolveInfo> receivers) {
8763        ActivityInfo targetReceiver = null;
8764
8765        final int NR = receivers.size();
8766        for (int i = 0; i < NR; i++) {
8767            final ResolveInfo info = receivers.get(i);
8768            if (info.activityInfo == null) {
8769                continue;
8770            }
8771
8772            if (packageName.equals(info.activityInfo.packageName)) {
8773                targetReceiver = info.activityInfo;
8774                break;
8775            }
8776        }
8777
8778        if (targetReceiver == null) {
8779            return null;
8780        }
8781
8782        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8783    }
8784
8785    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8786            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8787        if (pkgInfo.verifiers.length == 0) {
8788            return null;
8789        }
8790
8791        final int N = pkgInfo.verifiers.length;
8792        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8793        for (int i = 0; i < N; i++) {
8794            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8795
8796            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8797                    receivers);
8798            if (comp == null) {
8799                continue;
8800            }
8801
8802            final int verifierUid = getUidForVerifier(verifierInfo);
8803            if (verifierUid == -1) {
8804                continue;
8805            }
8806
8807            if (DEBUG_VERIFY) {
8808                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8809                        + " with the correct signature");
8810            }
8811            sufficientVerifiers.add(comp);
8812            verificationState.addSufficientVerifier(verifierUid);
8813        }
8814
8815        return sufficientVerifiers;
8816    }
8817
8818    private int getUidForVerifier(VerifierInfo verifierInfo) {
8819        synchronized (mPackages) {
8820            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8821            if (pkg == null) {
8822                return -1;
8823            } else if (pkg.mSignatures.length != 1) {
8824                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8825                        + " has more than one signature; ignoring");
8826                return -1;
8827            }
8828
8829            /*
8830             * If the public key of the package's signature does not match
8831             * our expected public key, then this is a different package and
8832             * we should skip.
8833             */
8834
8835            final byte[] expectedPublicKey;
8836            try {
8837                final Signature verifierSig = pkg.mSignatures[0];
8838                final PublicKey publicKey = verifierSig.getPublicKey();
8839                expectedPublicKey = publicKey.getEncoded();
8840            } catch (CertificateException e) {
8841                return -1;
8842            }
8843
8844            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8845
8846            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8847                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8848                        + " does not have the expected public key; ignoring");
8849                return -1;
8850            }
8851
8852            return pkg.applicationInfo.uid;
8853        }
8854    }
8855
8856    @Override
8857    public void finishPackageInstall(int token) {
8858        enforceSystemOrRoot("Only the system is allowed to finish installs");
8859
8860        if (DEBUG_INSTALL) {
8861            Slog.v(TAG, "BM finishing package install for " + token);
8862        }
8863
8864        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8865        mHandler.sendMessage(msg);
8866    }
8867
8868    /**
8869     * Get the verification agent timeout.
8870     *
8871     * @return verification timeout in milliseconds
8872     */
8873    private long getVerificationTimeout() {
8874        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8875                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8876                DEFAULT_VERIFICATION_TIMEOUT);
8877    }
8878
8879    /**
8880     * Get the default verification agent response code.
8881     *
8882     * @return default verification response code
8883     */
8884    private int getDefaultVerificationResponse() {
8885        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8886                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8887                DEFAULT_VERIFICATION_RESPONSE);
8888    }
8889
8890    /**
8891     * Check whether or not package verification has been enabled.
8892     *
8893     * @return true if verification should be performed
8894     */
8895    private boolean isVerificationEnabled(int userId, int installFlags) {
8896        if (!DEFAULT_VERIFY_ENABLE) {
8897            return false;
8898        }
8899
8900        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8901
8902        // Check if installing from ADB
8903        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8904            // Do not run verification in a test harness environment
8905            if (ActivityManager.isRunningInTestHarness()) {
8906                return false;
8907            }
8908            if (ensureVerifyAppsEnabled) {
8909                return true;
8910            }
8911            // Check if the developer does not want package verification for ADB installs
8912            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8913                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8914                return false;
8915            }
8916        }
8917
8918        if (ensureVerifyAppsEnabled) {
8919            return true;
8920        }
8921
8922        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8923                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8924    }
8925
8926    @Override
8927    public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)
8928            throws RemoteException {
8929        mContext.enforceCallingOrSelfPermission(
8930                Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT,
8931                "Only intentfilter verification agents can verify applications");
8932
8933        final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED);
8934        final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse(
8935                Binder.getCallingUid(), verificationCode, failedDomains);
8936        msg.arg1 = id;
8937        msg.obj = response;
8938        mHandler.sendMessage(msg);
8939    }
8940
8941    @Override
8942    public int getIntentVerificationStatus(String packageName, int userId) {
8943        synchronized (mPackages) {
8944            return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId);
8945        }
8946    }
8947
8948    @Override
8949    public boolean updateIntentVerificationStatus(String packageName, int status, int userId) {
8950        boolean result = false;
8951        synchronized (mPackages) {
8952            result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId);
8953        }
8954        scheduleWritePackageRestrictionsLocked(userId);
8955        return result;
8956    }
8957
8958    @Override
8959    public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
8960        synchronized (mPackages) {
8961            return mSettings.getIntentFilterVerificationsLPr(packageName);
8962        }
8963    }
8964
8965    /**
8966     * Get the "allow unknown sources" setting.
8967     *
8968     * @return the current "allow unknown sources" setting
8969     */
8970    private int getUnknownSourcesSettings() {
8971        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8972                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8973                -1);
8974    }
8975
8976    @Override
8977    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8978        final int uid = Binder.getCallingUid();
8979        // writer
8980        synchronized (mPackages) {
8981            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8982            if (targetPackageSetting == null) {
8983                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8984            }
8985
8986            PackageSetting installerPackageSetting;
8987            if (installerPackageName != null) {
8988                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8989                if (installerPackageSetting == null) {
8990                    throw new IllegalArgumentException("Unknown installer package: "
8991                            + installerPackageName);
8992                }
8993            } else {
8994                installerPackageSetting = null;
8995            }
8996
8997            Signature[] callerSignature;
8998            Object obj = mSettings.getUserIdLPr(uid);
8999            if (obj != null) {
9000                if (obj instanceof SharedUserSetting) {
9001                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
9002                } else if (obj instanceof PackageSetting) {
9003                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
9004                } else {
9005                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
9006                }
9007            } else {
9008                throw new SecurityException("Unknown calling uid " + uid);
9009            }
9010
9011            // Verify: can't set installerPackageName to a package that is
9012            // not signed with the same cert as the caller.
9013            if (installerPackageSetting != null) {
9014                if (compareSignatures(callerSignature,
9015                        installerPackageSetting.signatures.mSignatures)
9016                        != PackageManager.SIGNATURE_MATCH) {
9017                    throw new SecurityException(
9018                            "Caller does not have same cert as new installer package "
9019                            + installerPackageName);
9020                }
9021            }
9022
9023            // Verify: if target already has an installer package, it must
9024            // be signed with the same cert as the caller.
9025            if (targetPackageSetting.installerPackageName != null) {
9026                PackageSetting setting = mSettings.mPackages.get(
9027                        targetPackageSetting.installerPackageName);
9028                // If the currently set package isn't valid, then it's always
9029                // okay to change it.
9030                if (setting != null) {
9031                    if (compareSignatures(callerSignature,
9032                            setting.signatures.mSignatures)
9033                            != PackageManager.SIGNATURE_MATCH) {
9034                        throw new SecurityException(
9035                                "Caller does not have same cert as old installer package "
9036                                + targetPackageSetting.installerPackageName);
9037                    }
9038                }
9039            }
9040
9041            // Okay!
9042            targetPackageSetting.installerPackageName = installerPackageName;
9043            scheduleWriteSettingsLocked();
9044        }
9045    }
9046
9047    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
9048        // Queue up an async operation since the package installation may take a little while.
9049        mHandler.post(new Runnable() {
9050            public void run() {
9051                mHandler.removeCallbacks(this);
9052                 // Result object to be returned
9053                PackageInstalledInfo res = new PackageInstalledInfo();
9054                res.returnCode = currentStatus;
9055                res.uid = -1;
9056                res.pkg = null;
9057                res.removedInfo = new PackageRemovedInfo();
9058                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9059                    args.doPreInstall(res.returnCode);
9060                    synchronized (mInstallLock) {
9061                        installPackageLI(args, res);
9062                    }
9063                    args.doPostInstall(res.returnCode, res.uid);
9064                }
9065
9066                // A restore should be performed at this point if (a) the install
9067                // succeeded, (b) the operation is not an update, and (c) the new
9068                // package has not opted out of backup participation.
9069                final boolean update = res.removedInfo.removedPackage != null;
9070                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
9071                boolean doRestore = !update
9072                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
9073
9074                // Set up the post-install work request bookkeeping.  This will be used
9075                // and cleaned up by the post-install event handling regardless of whether
9076                // there's a restore pass performed.  Token values are >= 1.
9077                int token;
9078                if (mNextInstallToken < 0) mNextInstallToken = 1;
9079                token = mNextInstallToken++;
9080
9081                PostInstallData data = new PostInstallData(args, res);
9082                mRunningInstalls.put(token, data);
9083                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
9084
9085                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
9086                    // Pass responsibility to the Backup Manager.  It will perform a
9087                    // restore if appropriate, then pass responsibility back to the
9088                    // Package Manager to run the post-install observer callbacks
9089                    // and broadcasts.
9090                    IBackupManager bm = IBackupManager.Stub.asInterface(
9091                            ServiceManager.getService(Context.BACKUP_SERVICE));
9092                    if (bm != null) {
9093                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
9094                                + " to BM for possible restore");
9095                        try {
9096                            if (bm.isBackupServiceActive(UserHandle.USER_OWNER)) {
9097                                bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
9098                            } else {
9099                                doRestore = false;
9100                            }
9101                        } catch (RemoteException e) {
9102                            // can't happen; the backup manager is local
9103                        } catch (Exception e) {
9104                            Slog.e(TAG, "Exception trying to enqueue restore", e);
9105                            doRestore = false;
9106                        }
9107                    } else {
9108                        Slog.e(TAG, "Backup Manager not found!");
9109                        doRestore = false;
9110                    }
9111                }
9112
9113                if (!doRestore) {
9114                    // No restore possible, or the Backup Manager was mysteriously not
9115                    // available -- just fire the post-install work request directly.
9116                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
9117                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
9118                    mHandler.sendMessage(msg);
9119                }
9120            }
9121        });
9122    }
9123
9124    private abstract class HandlerParams {
9125        private static final int MAX_RETRIES = 4;
9126
9127        /**
9128         * Number of times startCopy() has been attempted and had a non-fatal
9129         * error.
9130         */
9131        private int mRetries = 0;
9132
9133        /** User handle for the user requesting the information or installation. */
9134        private final UserHandle mUser;
9135
9136        HandlerParams(UserHandle user) {
9137            mUser = user;
9138        }
9139
9140        UserHandle getUser() {
9141            return mUser;
9142        }
9143
9144        final boolean startCopy() {
9145            boolean res;
9146            try {
9147                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
9148
9149                if (++mRetries > MAX_RETRIES) {
9150                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
9151                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
9152                    handleServiceError();
9153                    return false;
9154                } else {
9155                    handleStartCopy();
9156                    res = true;
9157                }
9158            } catch (RemoteException e) {
9159                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
9160                mHandler.sendEmptyMessage(MCS_RECONNECT);
9161                res = false;
9162            }
9163            handleReturnCode();
9164            return res;
9165        }
9166
9167        final void serviceError() {
9168            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
9169            handleServiceError();
9170            handleReturnCode();
9171        }
9172
9173        abstract void handleStartCopy() throws RemoteException;
9174        abstract void handleServiceError();
9175        abstract void handleReturnCode();
9176    }
9177
9178    class MeasureParams extends HandlerParams {
9179        private final PackageStats mStats;
9180        private boolean mSuccess;
9181
9182        private final IPackageStatsObserver mObserver;
9183
9184        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
9185            super(new UserHandle(stats.userHandle));
9186            mObserver = observer;
9187            mStats = stats;
9188        }
9189
9190        @Override
9191        public String toString() {
9192            return "MeasureParams{"
9193                + Integer.toHexString(System.identityHashCode(this))
9194                + " " + mStats.packageName + "}";
9195        }
9196
9197        @Override
9198        void handleStartCopy() throws RemoteException {
9199            synchronized (mInstallLock) {
9200                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
9201            }
9202
9203            if (mSuccess) {
9204                final boolean mounted;
9205                if (Environment.isExternalStorageEmulated()) {
9206                    mounted = true;
9207                } else {
9208                    final String status = Environment.getExternalStorageState();
9209                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
9210                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
9211                }
9212
9213                if (mounted) {
9214                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
9215
9216                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
9217                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
9218
9219                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
9220                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
9221
9222                    // Always subtract cache size, since it's a subdirectory
9223                    mStats.externalDataSize -= mStats.externalCacheSize;
9224
9225                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
9226                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
9227
9228                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
9229                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
9230                }
9231            }
9232        }
9233
9234        @Override
9235        void handleReturnCode() {
9236            if (mObserver != null) {
9237                try {
9238                    mObserver.onGetStatsCompleted(mStats, mSuccess);
9239                } catch (RemoteException e) {
9240                    Slog.i(TAG, "Observer no longer exists.");
9241                }
9242            }
9243        }
9244
9245        @Override
9246        void handleServiceError() {
9247            Slog.e(TAG, "Could not measure application " + mStats.packageName
9248                            + " external storage");
9249        }
9250    }
9251
9252    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
9253            throws RemoteException {
9254        long result = 0;
9255        for (File path : paths) {
9256            result += mcs.calculateDirectorySize(path.getAbsolutePath());
9257        }
9258        return result;
9259    }
9260
9261    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
9262        for (File path : paths) {
9263            try {
9264                mcs.clearDirectory(path.getAbsolutePath());
9265            } catch (RemoteException e) {
9266            }
9267        }
9268    }
9269
9270    static class OriginInfo {
9271        /**
9272         * Location where install is coming from, before it has been
9273         * copied/renamed into place. This could be a single monolithic APK
9274         * file, or a cluster directory. This location may be untrusted.
9275         */
9276        final File file;
9277        final String cid;
9278
9279        /**
9280         * Flag indicating that {@link #file} or {@link #cid} has already been
9281         * staged, meaning downstream users don't need to defensively copy the
9282         * contents.
9283         */
9284        final boolean staged;
9285
9286        /**
9287         * Flag indicating that {@link #file} or {@link #cid} is an already
9288         * installed app that is being moved.
9289         */
9290        final boolean existing;
9291
9292        final String resolvedPath;
9293        final File resolvedFile;
9294
9295        static OriginInfo fromNothing() {
9296            return new OriginInfo(null, null, false, false);
9297        }
9298
9299        static OriginInfo fromUntrustedFile(File file) {
9300            return new OriginInfo(file, null, false, false);
9301        }
9302
9303        static OriginInfo fromExistingFile(File file) {
9304            return new OriginInfo(file, null, false, true);
9305        }
9306
9307        static OriginInfo fromStagedFile(File file) {
9308            return new OriginInfo(file, null, true, false);
9309        }
9310
9311        static OriginInfo fromStagedContainer(String cid) {
9312            return new OriginInfo(null, cid, true, false);
9313        }
9314
9315        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
9316            this.file = file;
9317            this.cid = cid;
9318            this.staged = staged;
9319            this.existing = existing;
9320
9321            if (cid != null) {
9322                resolvedPath = PackageHelper.getSdDir(cid);
9323                resolvedFile = new File(resolvedPath);
9324            } else if (file != null) {
9325                resolvedPath = file.getAbsolutePath();
9326                resolvedFile = file;
9327            } else {
9328                resolvedPath = null;
9329                resolvedFile = null;
9330            }
9331        }
9332    }
9333
9334    class InstallParams extends HandlerParams {
9335        final OriginInfo origin;
9336        final IPackageInstallObserver2 observer;
9337        int installFlags;
9338        final String installerPackageName;
9339        final VerificationParams verificationParams;
9340        private InstallArgs mArgs;
9341        private int mRet;
9342        final String packageAbiOverride;
9343
9344        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9345                String installerPackageName, VerificationParams verificationParams, UserHandle user,
9346                String packageAbiOverride) {
9347            super(user);
9348            this.origin = origin;
9349            this.observer = observer;
9350            this.installFlags = installFlags;
9351            this.installerPackageName = installerPackageName;
9352            this.verificationParams = verificationParams;
9353            this.packageAbiOverride = packageAbiOverride;
9354        }
9355
9356        @Override
9357        public String toString() {
9358            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
9359                    + " file=" + origin.file + " cid=" + origin.cid + "}";
9360        }
9361
9362        public ManifestDigest getManifestDigest() {
9363            if (verificationParams == null) {
9364                return null;
9365            }
9366            return verificationParams.getManifestDigest();
9367        }
9368
9369        private int installLocationPolicy(PackageInfoLite pkgLite) {
9370            String packageName = pkgLite.packageName;
9371            int installLocation = pkgLite.installLocation;
9372            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9373            // reader
9374            synchronized (mPackages) {
9375                PackageParser.Package pkg = mPackages.get(packageName);
9376                if (pkg != null) {
9377                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
9378                        // Check for downgrading.
9379                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
9380                            try {
9381                                checkDowngrade(pkg, pkgLite);
9382                            } catch (PackageManagerException e) {
9383                                Slog.w(TAG, "Downgrade detected: " + e.getMessage());
9384                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
9385                            }
9386                        }
9387                        // Check for updated system application.
9388                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
9389                            if (onSd) {
9390                                Slog.w(TAG, "Cannot install update to system app on sdcard");
9391                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
9392                            }
9393                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9394                        } else {
9395                            if (onSd) {
9396                                // Install flag overrides everything.
9397                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9398                            }
9399                            // If current upgrade specifies particular preference
9400                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
9401                                // Application explicitly specified internal.
9402                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9403                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
9404                                // App explictly prefers external. Let policy decide
9405                            } else {
9406                                // Prefer previous location
9407                                if (isExternal(pkg)) {
9408                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9409                                }
9410                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
9411                            }
9412                        }
9413                    } else {
9414                        // Invalid install. Return error code
9415                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
9416                    }
9417                }
9418            }
9419            // All the special cases have been taken care of.
9420            // Return result based on recommended install location.
9421            if (onSd) {
9422                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
9423            }
9424            return pkgLite.recommendedInstallLocation;
9425        }
9426
9427        /*
9428         * Invoke remote method to get package information and install
9429         * location values. Override install location based on default
9430         * policy if needed and then create install arguments based
9431         * on the install location.
9432         */
9433        public void handleStartCopy() throws RemoteException {
9434            int ret = PackageManager.INSTALL_SUCCEEDED;
9435
9436            // If we're already staged, we've firmly committed to an install location
9437            if (origin.staged) {
9438                if (origin.file != null) {
9439                    installFlags |= PackageManager.INSTALL_INTERNAL;
9440                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9441                } else if (origin.cid != null) {
9442                    installFlags |= PackageManager.INSTALL_EXTERNAL;
9443                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
9444                } else {
9445                    throw new IllegalStateException("Invalid stage location");
9446                }
9447            }
9448
9449            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9450            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
9451
9452            PackageInfoLite pkgLite = null;
9453
9454            if (onInt && onSd) {
9455                // Check if both bits are set.
9456                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
9457                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9458            } else {
9459                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
9460                        packageAbiOverride);
9461
9462                /*
9463                 * If we have too little free space, try to free cache
9464                 * before giving up.
9465                 */
9466                if (!origin.staged && pkgLite.recommendedInstallLocation
9467                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9468                    // TODO: focus freeing disk space on the target device
9469                    final StorageManager storage = StorageManager.from(mContext);
9470                    final long lowThreshold = storage.getStorageLowBytes(
9471                            Environment.getDataDirectory());
9472
9473                    final long sizeBytes = mContainerService.calculateInstalledSize(
9474                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
9475
9476                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
9477                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
9478                                installFlags, packageAbiOverride);
9479                    }
9480
9481                    /*
9482                     * The cache free must have deleted the file we
9483                     * downloaded to install.
9484                     *
9485                     * TODO: fix the "freeCache" call to not delete
9486                     *       the file we care about.
9487                     */
9488                    if (pkgLite.recommendedInstallLocation
9489                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9490                        pkgLite.recommendedInstallLocation
9491                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
9492                    }
9493                }
9494            }
9495
9496            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9497                int loc = pkgLite.recommendedInstallLocation;
9498                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
9499                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
9500                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
9501                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9502                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
9503                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9504                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
9505                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
9506                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
9507                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
9508                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
9509                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
9510                } else {
9511                    // Override with defaults if needed.
9512                    loc = installLocationPolicy(pkgLite);
9513                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
9514                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
9515                    } else if (!onSd && !onInt) {
9516                        // Override install location with flags
9517                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
9518                            // Set the flag to install on external media.
9519                            installFlags |= PackageManager.INSTALL_EXTERNAL;
9520                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
9521                        } else {
9522                            // Make sure the flag for installing on external
9523                            // media is unset
9524                            installFlags |= PackageManager.INSTALL_INTERNAL;
9525                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
9526                        }
9527                    }
9528                }
9529            }
9530
9531            final InstallArgs args = createInstallArgs(this);
9532            mArgs = args;
9533
9534            if (ret == PackageManager.INSTALL_SUCCEEDED) {
9535                 /*
9536                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
9537                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
9538                 */
9539                int userIdentifier = getUser().getIdentifier();
9540                if (userIdentifier == UserHandle.USER_ALL
9541                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
9542                    userIdentifier = UserHandle.USER_OWNER;
9543                }
9544
9545                /*
9546                 * Determine if we have any installed package verifiers. If we
9547                 * do, then we'll defer to them to verify the packages.
9548                 */
9549                final int requiredUid = mRequiredVerifierPackage == null ? -1
9550                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
9551                if (!origin.existing && requiredUid != -1
9552                        && isVerificationEnabled(userIdentifier, installFlags)) {
9553                    final Intent verification = new Intent(
9554                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
9555                    verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
9556                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
9557                            PACKAGE_MIME_TYPE);
9558                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
9559
9560                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
9561                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
9562                            0 /* TODO: Which userId? */);
9563
9564                    if (DEBUG_VERIFY) {
9565                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
9566                                + verification.toString() + " with " + pkgLite.verifiers.length
9567                                + " optional verifiers");
9568                    }
9569
9570                    final int verificationId = mPendingVerificationToken++;
9571
9572                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9573
9574                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9575                            installerPackageName);
9576
9577                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9578                            installFlags);
9579
9580                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9581                            pkgLite.packageName);
9582
9583                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9584                            pkgLite.versionCode);
9585
9586                    if (verificationParams != null) {
9587                        if (verificationParams.getVerificationURI() != null) {
9588                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9589                                 verificationParams.getVerificationURI());
9590                        }
9591                        if (verificationParams.getOriginatingURI() != null) {
9592                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9593                                  verificationParams.getOriginatingURI());
9594                        }
9595                        if (verificationParams.getReferrer() != null) {
9596                            verification.putExtra(Intent.EXTRA_REFERRER,
9597                                  verificationParams.getReferrer());
9598                        }
9599                        if (verificationParams.getOriginatingUid() >= 0) {
9600                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9601                                  verificationParams.getOriginatingUid());
9602                        }
9603                        if (verificationParams.getInstallerUid() >= 0) {
9604                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9605                                  verificationParams.getInstallerUid());
9606                        }
9607                    }
9608
9609                    final PackageVerificationState verificationState = new PackageVerificationState(
9610                            requiredUid, args);
9611
9612                    mPendingVerification.append(verificationId, verificationState);
9613
9614                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9615                            receivers, verificationState);
9616
9617                    /*
9618                     * If any sufficient verifiers were listed in the package
9619                     * manifest, attempt to ask them.
9620                     */
9621                    if (sufficientVerifiers != null) {
9622                        final int N = sufficientVerifiers.size();
9623                        if (N == 0) {
9624                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9625                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9626                        } else {
9627                            for (int i = 0; i < N; i++) {
9628                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9629
9630                                final Intent sufficientIntent = new Intent(verification);
9631                                sufficientIntent.setComponent(verifierComponent);
9632
9633                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9634                            }
9635                        }
9636                    }
9637
9638                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9639                            mRequiredVerifierPackage, receivers);
9640                    if (ret == PackageManager.INSTALL_SUCCEEDED
9641                            && mRequiredVerifierPackage != null) {
9642                        /*
9643                         * Send the intent to the required verification agent,
9644                         * but only start the verification timeout after the
9645                         * target BroadcastReceivers have run.
9646                         */
9647                        verification.setComponent(requiredVerifierComponent);
9648                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9649                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9650                                new BroadcastReceiver() {
9651                                    @Override
9652                                    public void onReceive(Context context, Intent intent) {
9653                                        final Message msg = mHandler
9654                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9655                                        msg.arg1 = verificationId;
9656                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9657                                    }
9658                                }, null, 0, null, null);
9659
9660                        /*
9661                         * We don't want the copy to proceed until verification
9662                         * succeeds, so null out this field.
9663                         */
9664                        mArgs = null;
9665                    }
9666                } else {
9667                    /*
9668                     * No package verification is enabled, so immediately start
9669                     * the remote call to initiate copy using temporary file.
9670                     */
9671                    ret = args.copyApk(mContainerService, true);
9672                }
9673            }
9674
9675            mRet = ret;
9676        }
9677
9678        @Override
9679        void handleReturnCode() {
9680            // If mArgs is null, then MCS couldn't be reached. When it
9681            // reconnects, it will try again to install. At that point, this
9682            // will succeed.
9683            if (mArgs != null) {
9684                processPendingInstall(mArgs, mRet);
9685            }
9686        }
9687
9688        @Override
9689        void handleServiceError() {
9690            mArgs = createInstallArgs(this);
9691            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9692        }
9693
9694        public boolean isForwardLocked() {
9695            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9696        }
9697    }
9698
9699    /**
9700     * Used during creation of InstallArgs
9701     *
9702     * @param installFlags package installation flags
9703     * @return true if should be installed on external storage
9704     */
9705    private static boolean installOnSd(int installFlags) {
9706        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9707            return false;
9708        }
9709        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9710            return true;
9711        }
9712        return false;
9713    }
9714
9715    /**
9716     * Used during creation of InstallArgs
9717     *
9718     * @param installFlags package installation flags
9719     * @return true if should be installed as forward locked
9720     */
9721    private static boolean installForwardLocked(int installFlags) {
9722        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9723    }
9724
9725    private InstallArgs createInstallArgs(InstallParams params) {
9726        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9727            return new AsecInstallArgs(params);
9728        } else {
9729            return new FileInstallArgs(params);
9730        }
9731    }
9732
9733    /**
9734     * Create args that describe an existing installed package. Typically used
9735     * when cleaning up old installs, or used as a move source.
9736     */
9737    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9738            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9739        final boolean isInAsec;
9740        if (installOnSd(installFlags)) {
9741            /* Apps on SD card are always in ASEC containers. */
9742            isInAsec = true;
9743        } else if (installForwardLocked(installFlags)
9744                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9745            /*
9746             * Forward-locked apps are only in ASEC containers if they're the
9747             * new style
9748             */
9749            isInAsec = true;
9750        } else {
9751            isInAsec = false;
9752        }
9753
9754        if (isInAsec) {
9755            return new AsecInstallArgs(codePath, instructionSets,
9756                    installOnSd(installFlags), installForwardLocked(installFlags));
9757        } else {
9758            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9759                    instructionSets);
9760        }
9761    }
9762
9763    static abstract class InstallArgs {
9764        /** @see InstallParams#origin */
9765        final OriginInfo origin;
9766
9767        final IPackageInstallObserver2 observer;
9768        // Always refers to PackageManager flags only
9769        final int installFlags;
9770        final String installerPackageName;
9771        final ManifestDigest manifestDigest;
9772        final UserHandle user;
9773        final String abiOverride;
9774
9775        // The list of instruction sets supported by this app. This is currently
9776        // only used during the rmdex() phase to clean up resources. We can get rid of this
9777        // if we move dex files under the common app path.
9778        /* nullable */ String[] instructionSets;
9779
9780        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9781                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9782                String[] instructionSets, String abiOverride) {
9783            this.origin = origin;
9784            this.installFlags = installFlags;
9785            this.observer = observer;
9786            this.installerPackageName = installerPackageName;
9787            this.manifestDigest = manifestDigest;
9788            this.user = user;
9789            this.instructionSets = instructionSets;
9790            this.abiOverride = abiOverride;
9791        }
9792
9793        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9794        abstract int doPreInstall(int status);
9795
9796        /**
9797         * Rename package into final resting place. All paths on the given
9798         * scanned package should be updated to reflect the rename.
9799         */
9800        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9801        abstract int doPostInstall(int status, int uid);
9802
9803        /** @see PackageSettingBase#codePathString */
9804        abstract String getCodePath();
9805        /** @see PackageSettingBase#resourcePathString */
9806        abstract String getResourcePath();
9807        abstract String getLegacyNativeLibraryPath();
9808
9809        // Need installer lock especially for dex file removal.
9810        abstract void cleanUpResourcesLI();
9811        abstract boolean doPostDeleteLI(boolean delete);
9812        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9813
9814        /**
9815         * Called before the source arguments are copied. This is used mostly
9816         * for MoveParams when it needs to read the source file to put it in the
9817         * destination.
9818         */
9819        int doPreCopy() {
9820            return PackageManager.INSTALL_SUCCEEDED;
9821        }
9822
9823        /**
9824         * Called after the source arguments are copied. This is used mostly for
9825         * MoveParams when it needs to read the source file to put it in the
9826         * destination.
9827         *
9828         * @return
9829         */
9830        int doPostCopy(int uid) {
9831            return PackageManager.INSTALL_SUCCEEDED;
9832        }
9833
9834        protected boolean isFwdLocked() {
9835            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9836        }
9837
9838        protected boolean isExternal() {
9839            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9840        }
9841
9842        UserHandle getUser() {
9843            return user;
9844        }
9845    }
9846
9847    private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) {
9848        if (!allCodePaths.isEmpty()) {
9849            if (instructionSets == null) {
9850                throw new IllegalStateException("instructionSet == null");
9851            }
9852            String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9853            for (String codePath : allCodePaths) {
9854                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9855                    int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9856                    if (retCode < 0) {
9857                        Slog.w(TAG, "Couldn't remove dex file for package: "
9858                                + " at location " + codePath + ", retcode=" + retCode);
9859                        // we don't consider this to be a failure of the core package deletion
9860                    }
9861                }
9862            }
9863        }
9864    }
9865
9866    /**
9867     * Logic to handle installation of non-ASEC applications, including copying
9868     * and renaming logic.
9869     */
9870    class FileInstallArgs extends InstallArgs {
9871        private File codeFile;
9872        private File resourceFile;
9873        private File legacyNativeLibraryPath;
9874
9875        // Example topology:
9876        // /data/app/com.example/base.apk
9877        // /data/app/com.example/split_foo.apk
9878        // /data/app/com.example/lib/arm/libfoo.so
9879        // /data/app/com.example/lib/arm64/libfoo.so
9880        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9881
9882        /** New install */
9883        FileInstallArgs(InstallParams params) {
9884            super(params.origin, params.observer, params.installFlags,
9885                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9886                    null /* instruction sets */, params.packageAbiOverride);
9887            if (isFwdLocked()) {
9888                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9889            }
9890        }
9891
9892        /** Existing install */
9893        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9894                String[] instructionSets) {
9895            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9896            this.codeFile = (codePath != null) ? new File(codePath) : null;
9897            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9898            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9899                    new File(legacyNativeLibraryPath) : null;
9900        }
9901
9902        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9903            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9904                    isFwdLocked(), abiOverride);
9905
9906            final StorageManager storage = StorageManager.from(mContext);
9907            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9908        }
9909
9910        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9911            if (origin.staged) {
9912                Slog.d(TAG, origin.file + " already staged; skipping copy");
9913                codeFile = origin.file;
9914                resourceFile = origin.file;
9915                return PackageManager.INSTALL_SUCCEEDED;
9916            }
9917
9918            try {
9919                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9920                codeFile = tempDir;
9921                resourceFile = tempDir;
9922            } catch (IOException e) {
9923                Slog.w(TAG, "Failed to create copy file: " + e);
9924                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9925            }
9926
9927            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9928                @Override
9929                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9930                    if (!FileUtils.isValidExtFilename(name)) {
9931                        throw new IllegalArgumentException("Invalid filename: " + name);
9932                    }
9933                    try {
9934                        final File file = new File(codeFile, name);
9935                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9936                                O_RDWR | O_CREAT, 0644);
9937                        Os.chmod(file.getAbsolutePath(), 0644);
9938                        return new ParcelFileDescriptor(fd);
9939                    } catch (ErrnoException e) {
9940                        throw new RemoteException("Failed to open: " + e.getMessage());
9941                    }
9942                }
9943            };
9944
9945            int ret = PackageManager.INSTALL_SUCCEEDED;
9946            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9947            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9948                Slog.e(TAG, "Failed to copy package");
9949                return ret;
9950            }
9951
9952            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9953            NativeLibraryHelper.Handle handle = null;
9954            try {
9955                handle = NativeLibraryHelper.Handle.create(codeFile);
9956                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9957                        abiOverride);
9958            } catch (IOException e) {
9959                Slog.e(TAG, "Copying native libraries failed", e);
9960                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9961            } finally {
9962                IoUtils.closeQuietly(handle);
9963            }
9964
9965            return ret;
9966        }
9967
9968        int doPreInstall(int status) {
9969            if (status != PackageManager.INSTALL_SUCCEEDED) {
9970                cleanUp();
9971            }
9972            return status;
9973        }
9974
9975        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9976            if (status != PackageManager.INSTALL_SUCCEEDED) {
9977                cleanUp();
9978                return false;
9979            } else {
9980                final File beforeCodeFile = codeFile;
9981                final File afterCodeFile = getNextCodePath(pkg.packageName);
9982
9983                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9984                try {
9985                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9986                } catch (ErrnoException e) {
9987                    Slog.d(TAG, "Failed to rename", e);
9988                    return false;
9989                }
9990
9991                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9992                    Slog.d(TAG, "Failed to restorecon");
9993                    return false;
9994                }
9995
9996                // Reflect the rename internally
9997                codeFile = afterCodeFile;
9998                resourceFile = afterCodeFile;
9999
10000                // Reflect the rename in scanned details
10001                pkg.codePath = afterCodeFile.getAbsolutePath();
10002                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10003                        pkg.baseCodePath);
10004                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10005                        pkg.splitCodePaths);
10006
10007                // Reflect the rename in app info
10008                pkg.applicationInfo.setCodePath(pkg.codePath);
10009                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10010                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10011                pkg.applicationInfo.setResourcePath(pkg.codePath);
10012                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10013                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10014
10015                return true;
10016            }
10017        }
10018
10019        int doPostInstall(int status, int uid) {
10020            if (status != PackageManager.INSTALL_SUCCEEDED) {
10021                cleanUp();
10022            }
10023            return status;
10024        }
10025
10026        @Override
10027        String getCodePath() {
10028            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
10029        }
10030
10031        @Override
10032        String getResourcePath() {
10033            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
10034        }
10035
10036        @Override
10037        String getLegacyNativeLibraryPath() {
10038            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
10039        }
10040
10041        private boolean cleanUp() {
10042            if (codeFile == null || !codeFile.exists()) {
10043                return false;
10044            }
10045
10046            if (codeFile.isDirectory()) {
10047                mInstaller.rmPackageDir(codeFile.getAbsolutePath());
10048            } else {
10049                codeFile.delete();
10050            }
10051
10052            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
10053                resourceFile.delete();
10054            }
10055
10056            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
10057                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
10058                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
10059                }
10060                legacyNativeLibraryPath.delete();
10061            }
10062
10063            return true;
10064        }
10065
10066        void cleanUpResourcesLI() {
10067            // Try enumerating all code paths before deleting
10068            List<String> allCodePaths = Collections.EMPTY_LIST;
10069            if (codeFile != null && codeFile.exists()) {
10070                try {
10071                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10072                    allCodePaths = pkg.getAllCodePaths();
10073                } catch (PackageParserException e) {
10074                    // Ignored; we tried our best
10075                }
10076            }
10077
10078            cleanUp();
10079            removeDexFiles(allCodePaths, instructionSets);
10080        }
10081
10082        boolean doPostDeleteLI(boolean delete) {
10083            // XXX err, shouldn't we respect the delete flag?
10084            cleanUpResourcesLI();
10085            return true;
10086        }
10087    }
10088
10089    private boolean isAsecExternal(String cid) {
10090        final String asecPath = PackageHelper.getSdFilesystem(cid);
10091        return !asecPath.startsWith(mAsecInternalPath);
10092    }
10093
10094    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
10095            PackageManagerException {
10096        if (copyRet < 0) {
10097            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
10098                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
10099                throw new PackageManagerException(copyRet, message);
10100            }
10101        }
10102    }
10103
10104    /**
10105     * Extract the MountService "container ID" from the full code path of an
10106     * .apk.
10107     */
10108    static String cidFromCodePath(String fullCodePath) {
10109        int eidx = fullCodePath.lastIndexOf("/");
10110        String subStr1 = fullCodePath.substring(0, eidx);
10111        int sidx = subStr1.lastIndexOf("/");
10112        return subStr1.substring(sidx+1, eidx);
10113    }
10114
10115    /**
10116     * Logic to handle installation of ASEC applications, including copying and
10117     * renaming logic.
10118     */
10119    class AsecInstallArgs extends InstallArgs {
10120        static final String RES_FILE_NAME = "pkg.apk";
10121        static final String PUBLIC_RES_FILE_NAME = "res.zip";
10122
10123        String cid;
10124        String packagePath;
10125        String resourcePath;
10126        String legacyNativeLibraryDir;
10127
10128        /** New install */
10129        AsecInstallArgs(InstallParams params) {
10130            super(params.origin, params.observer, params.installFlags,
10131                    params.installerPackageName, params.getManifestDigest(),
10132                    params.getUser(), null /* instruction sets */,
10133                    params.packageAbiOverride);
10134        }
10135
10136        /** Existing install */
10137        AsecInstallArgs(String fullCodePath, String[] instructionSets,
10138                        boolean isExternal, boolean isForwardLocked) {
10139            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
10140                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
10141                    instructionSets, null);
10142            // Hackily pretend we're still looking at a full code path
10143            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
10144                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
10145            }
10146
10147            // Extract cid from fullCodePath
10148            int eidx = fullCodePath.lastIndexOf("/");
10149            String subStr1 = fullCodePath.substring(0, eidx);
10150            int sidx = subStr1.lastIndexOf("/");
10151            cid = subStr1.substring(sidx+1, eidx);
10152            setMountPath(subStr1);
10153        }
10154
10155        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
10156            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
10157                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
10158                    instructionSets, null);
10159            this.cid = cid;
10160            setMountPath(PackageHelper.getSdDir(cid));
10161        }
10162
10163        void createCopyFile() {
10164            cid = mInstallerService.allocateExternalStageCidLegacy();
10165        }
10166
10167        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
10168            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
10169                    abiOverride);
10170
10171            final File target;
10172            if (isExternal()) {
10173                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
10174            } else {
10175                target = Environment.getDataDirectory();
10176            }
10177
10178            final StorageManager storage = StorageManager.from(mContext);
10179            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
10180        }
10181
10182        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
10183            if (origin.staged) {
10184                Slog.d(TAG, origin.cid + " already staged; skipping copy");
10185                cid = origin.cid;
10186                setMountPath(PackageHelper.getSdDir(cid));
10187                return PackageManager.INSTALL_SUCCEEDED;
10188            }
10189
10190            if (temp) {
10191                createCopyFile();
10192            } else {
10193                /*
10194                 * Pre-emptively destroy the container since it's destroyed if
10195                 * copying fails due to it existing anyway.
10196                 */
10197                PackageHelper.destroySdDir(cid);
10198            }
10199
10200            final String newMountPath = imcs.copyPackageToContainer(
10201                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
10202                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
10203
10204            if (newMountPath != null) {
10205                setMountPath(newMountPath);
10206                return PackageManager.INSTALL_SUCCEEDED;
10207            } else {
10208                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10209            }
10210        }
10211
10212        @Override
10213        String getCodePath() {
10214            return packagePath;
10215        }
10216
10217        @Override
10218        String getResourcePath() {
10219            return resourcePath;
10220        }
10221
10222        @Override
10223        String getLegacyNativeLibraryPath() {
10224            return legacyNativeLibraryDir;
10225        }
10226
10227        int doPreInstall(int status) {
10228            if (status != PackageManager.INSTALL_SUCCEEDED) {
10229                // Destroy container
10230                PackageHelper.destroySdDir(cid);
10231            } else {
10232                boolean mounted = PackageHelper.isContainerMounted(cid);
10233                if (!mounted) {
10234                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
10235                            Process.SYSTEM_UID);
10236                    if (newMountPath != null) {
10237                        setMountPath(newMountPath);
10238                    } else {
10239                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10240                    }
10241                }
10242            }
10243            return status;
10244        }
10245
10246        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
10247            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
10248            String newMountPath = null;
10249            if (PackageHelper.isContainerMounted(cid)) {
10250                // Unmount the container
10251                if (!PackageHelper.unMountSdDir(cid)) {
10252                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
10253                    return false;
10254                }
10255            }
10256            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10257                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
10258                        " which might be stale. Will try to clean up.");
10259                // Clean up the stale container and proceed to recreate.
10260                if (!PackageHelper.destroySdDir(newCacheId)) {
10261                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
10262                    return false;
10263                }
10264                // Successfully cleaned up stale container. Try to rename again.
10265                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
10266                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
10267                            + " inspite of cleaning it up.");
10268                    return false;
10269                }
10270            }
10271            if (!PackageHelper.isContainerMounted(newCacheId)) {
10272                Slog.w(TAG, "Mounting container " + newCacheId);
10273                newMountPath = PackageHelper.mountSdDir(newCacheId,
10274                        getEncryptKey(), Process.SYSTEM_UID);
10275            } else {
10276                newMountPath = PackageHelper.getSdDir(newCacheId);
10277            }
10278            if (newMountPath == null) {
10279                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
10280                return false;
10281            }
10282            Log.i(TAG, "Succesfully renamed " + cid +
10283                    " to " + newCacheId +
10284                    " at new path: " + newMountPath);
10285            cid = newCacheId;
10286
10287            final File beforeCodeFile = new File(packagePath);
10288            setMountPath(newMountPath);
10289            final File afterCodeFile = new File(packagePath);
10290
10291            // Reflect the rename in scanned details
10292            pkg.codePath = afterCodeFile.getAbsolutePath();
10293            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10294                    pkg.baseCodePath);
10295            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
10296                    pkg.splitCodePaths);
10297
10298            // Reflect the rename in app info
10299            pkg.applicationInfo.setCodePath(pkg.codePath);
10300            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
10301            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
10302            pkg.applicationInfo.setResourcePath(pkg.codePath);
10303            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
10304            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
10305
10306            return true;
10307        }
10308
10309        private void setMountPath(String mountPath) {
10310            final File mountFile = new File(mountPath);
10311
10312            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
10313            if (monolithicFile.exists()) {
10314                packagePath = monolithicFile.getAbsolutePath();
10315                if (isFwdLocked()) {
10316                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
10317                } else {
10318                    resourcePath = packagePath;
10319                }
10320            } else {
10321                packagePath = mountFile.getAbsolutePath();
10322                resourcePath = packagePath;
10323            }
10324
10325            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
10326        }
10327
10328        int doPostInstall(int status, int uid) {
10329            if (status != PackageManager.INSTALL_SUCCEEDED) {
10330                cleanUp();
10331            } else {
10332                final int groupOwner;
10333                final String protectedFile;
10334                if (isFwdLocked()) {
10335                    groupOwner = UserHandle.getSharedAppGid(uid);
10336                    protectedFile = RES_FILE_NAME;
10337                } else {
10338                    groupOwner = -1;
10339                    protectedFile = null;
10340                }
10341
10342                if (uid < Process.FIRST_APPLICATION_UID
10343                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
10344                    Slog.e(TAG, "Failed to finalize " + cid);
10345                    PackageHelper.destroySdDir(cid);
10346                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10347                }
10348
10349                boolean mounted = PackageHelper.isContainerMounted(cid);
10350                if (!mounted) {
10351                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
10352                }
10353            }
10354            return status;
10355        }
10356
10357        private void cleanUp() {
10358            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
10359
10360            // Destroy secure container
10361            PackageHelper.destroySdDir(cid);
10362        }
10363
10364        private List<String> getAllCodePaths() {
10365            final File codeFile = new File(getCodePath());
10366            if (codeFile != null && codeFile.exists()) {
10367                try {
10368                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
10369                    return pkg.getAllCodePaths();
10370                } catch (PackageParserException e) {
10371                    // Ignored; we tried our best
10372                }
10373            }
10374            return Collections.EMPTY_LIST;
10375        }
10376
10377        void cleanUpResourcesLI() {
10378            // Enumerate all code paths before deleting
10379            cleanUpResourcesLI(getAllCodePaths());
10380        }
10381
10382        private void cleanUpResourcesLI(List<String> allCodePaths) {
10383            cleanUp();
10384            removeDexFiles(allCodePaths, instructionSets);
10385        }
10386
10387
10388
10389        String getPackageName() {
10390            return getAsecPackageName(cid);
10391        }
10392
10393        boolean doPostDeleteLI(boolean delete) {
10394            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
10395            final List<String> allCodePaths = getAllCodePaths();
10396            boolean mounted = PackageHelper.isContainerMounted(cid);
10397            if (mounted) {
10398                // Unmount first
10399                if (PackageHelper.unMountSdDir(cid)) {
10400                    mounted = false;
10401                }
10402            }
10403            if (!mounted && delete) {
10404                cleanUpResourcesLI(allCodePaths);
10405            }
10406            return !mounted;
10407        }
10408
10409        @Override
10410        int doPreCopy() {
10411            if (isFwdLocked()) {
10412                if (!PackageHelper.fixSdPermissions(cid,
10413                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
10414                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10415                }
10416            }
10417
10418            return PackageManager.INSTALL_SUCCEEDED;
10419        }
10420
10421        @Override
10422        int doPostCopy(int uid) {
10423            if (isFwdLocked()) {
10424                if (uid < Process.FIRST_APPLICATION_UID
10425                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
10426                                RES_FILE_NAME)) {
10427                    Slog.e(TAG, "Failed to finalize " + cid);
10428                    PackageHelper.destroySdDir(cid);
10429                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
10430                }
10431            }
10432
10433            return PackageManager.INSTALL_SUCCEEDED;
10434        }
10435    }
10436
10437    static String getAsecPackageName(String packageCid) {
10438        int idx = packageCid.lastIndexOf("-");
10439        if (idx == -1) {
10440            return packageCid;
10441        }
10442        return packageCid.substring(0, idx);
10443    }
10444
10445    // Utility method used to create code paths based on package name and available index.
10446    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
10447        String idxStr = "";
10448        int idx = 1;
10449        // Fall back to default value of idx=1 if prefix is not
10450        // part of oldCodePath
10451        if (oldCodePath != null) {
10452            String subStr = oldCodePath;
10453            // Drop the suffix right away
10454            if (suffix != null && subStr.endsWith(suffix)) {
10455                subStr = subStr.substring(0, subStr.length() - suffix.length());
10456            }
10457            // If oldCodePath already contains prefix find out the
10458            // ending index to either increment or decrement.
10459            int sidx = subStr.lastIndexOf(prefix);
10460            if (sidx != -1) {
10461                subStr = subStr.substring(sidx + prefix.length());
10462                if (subStr != null) {
10463                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
10464                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
10465                    }
10466                    try {
10467                        idx = Integer.parseInt(subStr);
10468                        if (idx <= 1) {
10469                            idx++;
10470                        } else {
10471                            idx--;
10472                        }
10473                    } catch(NumberFormatException e) {
10474                    }
10475                }
10476            }
10477        }
10478        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
10479        return prefix + idxStr;
10480    }
10481
10482    private File getNextCodePath(String packageName) {
10483        int suffix = 1;
10484        File result;
10485        do {
10486            result = new File(mAppInstallDir, packageName + "-" + suffix);
10487            suffix++;
10488        } while (result.exists());
10489        return result;
10490    }
10491
10492    // Utility method that returns the relative package path with respect
10493    // to the installation directory. Like say for /data/data/com.test-1.apk
10494    // string com.test-1 is returned.
10495    static String deriveCodePathName(String codePath) {
10496        if (codePath == null) {
10497            return null;
10498        }
10499        final File codeFile = new File(codePath);
10500        final String name = codeFile.getName();
10501        if (codeFile.isDirectory()) {
10502            return name;
10503        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
10504            final int lastDot = name.lastIndexOf('.');
10505            return name.substring(0, lastDot);
10506        } else {
10507            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
10508            return null;
10509        }
10510    }
10511
10512    class PackageInstalledInfo {
10513        String name;
10514        int uid;
10515        // The set of users that originally had this package installed.
10516        int[] origUsers;
10517        // The set of users that now have this package installed.
10518        int[] newUsers;
10519        PackageParser.Package pkg;
10520        int returnCode;
10521        String returnMsg;
10522        PackageRemovedInfo removedInfo;
10523
10524        public void setError(int code, String msg) {
10525            returnCode = code;
10526            returnMsg = msg;
10527            Slog.w(TAG, msg);
10528        }
10529
10530        public void setError(String msg, PackageParserException e) {
10531            returnCode = e.error;
10532            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10533            Slog.w(TAG, msg, e);
10534        }
10535
10536        public void setError(String msg, PackageManagerException e) {
10537            returnCode = e.error;
10538            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10539            Slog.w(TAG, msg, e);
10540        }
10541
10542        // In some error cases we want to convey more info back to the observer
10543        String origPackage;
10544        String origPermission;
10545    }
10546
10547    /*
10548     * Install a non-existing package.
10549     */
10550    private void installNewPackageLI(PackageParser.Package pkg,
10551            int parseFlags, int scanFlags, UserHandle user,
10552            String installerPackageName, PackageInstalledInfo res) {
10553        // Remember this for later, in case we need to rollback this install
10554        String pkgName = pkg.packageName;
10555
10556        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10557        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10558        synchronized(mPackages) {
10559            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10560                // A package with the same name is already installed, though
10561                // it has been renamed to an older name.  The package we
10562                // are trying to install should be installed as an update to
10563                // the existing one, but that has not been requested, so bail.
10564                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10565                        + " without first uninstalling package running as "
10566                        + mSettings.mRenamedPackages.get(pkgName));
10567                return;
10568            }
10569            if (mPackages.containsKey(pkgName)) {
10570                // Don't allow installation over an existing package with the same name.
10571                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10572                        + " without first uninstalling.");
10573                return;
10574            }
10575        }
10576
10577        try {
10578            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10579                    System.currentTimeMillis(), user);
10580
10581            updateSettingsLI(newPackage, installerPackageName, null, null, res, user);
10582            // delete the partially installed application. the data directory will have to be
10583            // restored if it was already existing
10584            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10585                // remove package from internal structures.  Note that we want deletePackageX to
10586                // delete the package data and cache directories that it created in
10587                // scanPackageLocked, unless those directories existed before we even tried to
10588                // install.
10589                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10590                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10591                                res.removedInfo, true);
10592            }
10593
10594        } catch (PackageManagerException e) {
10595            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10596        }
10597    }
10598
10599    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10600        // Upgrade keysets are being used.  Determine if new package has a superset of the
10601        // required keys.
10602        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10603        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10604        for (int i = 0; i < upgradeKeySets.length; i++) {
10605            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10606            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10607                return true;
10608            }
10609        }
10610        return false;
10611    }
10612
10613    private void replacePackageLI(PackageParser.Package pkg,
10614            int parseFlags, int scanFlags, UserHandle user,
10615            String installerPackageName, PackageInstalledInfo res) {
10616        PackageParser.Package oldPackage;
10617        String pkgName = pkg.packageName;
10618        int[] allUsers;
10619        boolean[] perUserInstalled;
10620
10621        // First find the old package info and check signatures
10622        synchronized(mPackages) {
10623            oldPackage = mPackages.get(pkgName);
10624            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10625            PackageSetting ps = mSettings.mPackages.get(pkgName);
10626            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10627                // default to original signature matching
10628                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10629                    != PackageManager.SIGNATURE_MATCH) {
10630                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10631                            "New package has a different signature: " + pkgName);
10632                    return;
10633                }
10634            } else {
10635                if(!checkUpgradeKeySetLP(ps, pkg)) {
10636                    res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
10637                            "New package not signed by keys specified by upgrade-keysets: "
10638                            + pkgName);
10639                    return;
10640                }
10641            }
10642
10643            // In case of rollback, remember per-user/profile install state
10644            allUsers = sUserManager.getUserIds();
10645            perUserInstalled = new boolean[allUsers.length];
10646            for (int i = 0; i < allUsers.length; i++) {
10647                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10648            }
10649        }
10650
10651        boolean sysPkg = (isSystemApp(oldPackage));
10652        if (sysPkg) {
10653            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10654                    user, allUsers, perUserInstalled, installerPackageName, res);
10655        } else {
10656            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10657                    user, allUsers, perUserInstalled, installerPackageName, res);
10658        }
10659    }
10660
10661    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10662            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10663            int[] allUsers, boolean[] perUserInstalled,
10664            String installerPackageName, PackageInstalledInfo res) {
10665        String pkgName = deletedPackage.packageName;
10666        boolean deletedPkg = true;
10667        boolean updatedSettings = false;
10668
10669        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10670                + deletedPackage);
10671        long origUpdateTime;
10672        if (pkg.mExtras != null) {
10673            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10674        } else {
10675            origUpdateTime = 0;
10676        }
10677
10678        // First delete the existing package while retaining the data directory
10679        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10680                res.removedInfo, true)) {
10681            // If the existing package wasn't successfully deleted
10682            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10683            deletedPkg = false;
10684        } else {
10685            // Successfully deleted the old package; proceed with replace.
10686
10687            // If deleted package lived in a container, give users a chance to
10688            // relinquish resources before killing.
10689            if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) {
10690                if (DEBUG_INSTALL) {
10691                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10692                }
10693                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10694                final ArrayList<String> pkgList = new ArrayList<String>(1);
10695                pkgList.add(deletedPackage.applicationInfo.packageName);
10696                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10697            }
10698
10699            deleteCodeCacheDirsLI(pkgName);
10700            try {
10701                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10702                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10703                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10704                        user);
10705                updatedSettings = true;
10706            } catch (PackageManagerException e) {
10707                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10708            }
10709        }
10710
10711        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10712            // remove package from internal structures.  Note that we want deletePackageX to
10713            // delete the package data and cache directories that it created in
10714            // scanPackageLocked, unless those directories existed before we even tried to
10715            // install.
10716            if(updatedSettings) {
10717                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10718                deletePackageLI(
10719                        pkgName, null, true, allUsers, perUserInstalled,
10720                        PackageManager.DELETE_KEEP_DATA,
10721                                res.removedInfo, true);
10722            }
10723            // Since we failed to install the new package we need to restore the old
10724            // package that we deleted.
10725            if (deletedPkg) {
10726                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10727                File restoreFile = new File(deletedPackage.codePath);
10728                // Parse old package
10729                boolean oldOnSd = isExternal(deletedPackage);
10730                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10731                        (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10732                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10733                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10734                try {
10735                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10736                } catch (PackageManagerException e) {
10737                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10738                            + e.getMessage());
10739                    return;
10740                }
10741                // Restore of old package succeeded. Update permissions.
10742                // writer
10743                synchronized (mPackages) {
10744                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10745                            UPDATE_PERMISSIONS_ALL);
10746                    // can downgrade to reader
10747                    mSettings.writeLPr();
10748                }
10749                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10750            }
10751        }
10752    }
10753
10754    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10755            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10756            int[] allUsers, boolean[] perUserInstalled,
10757            String installerPackageName, PackageInstalledInfo res) {
10758        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10759                + ", old=" + deletedPackage);
10760        boolean disabledSystem = false;
10761        boolean updatedSettings = false;
10762        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10763        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10764                != 0) {
10765            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10766        }
10767        String packageName = deletedPackage.packageName;
10768        if (packageName == null) {
10769            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10770                    "Attempt to delete null packageName.");
10771            return;
10772        }
10773        PackageParser.Package oldPkg;
10774        PackageSetting oldPkgSetting;
10775        // reader
10776        synchronized (mPackages) {
10777            oldPkg = mPackages.get(packageName);
10778            oldPkgSetting = mSettings.mPackages.get(packageName);
10779            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10780                    (oldPkgSetting == null)) {
10781                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10782                        "Couldn't find package:" + packageName + " information");
10783                return;
10784            }
10785        }
10786
10787        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10788
10789        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10790        res.removedInfo.removedPackage = packageName;
10791        // Remove existing system package
10792        removePackageLI(oldPkgSetting, true);
10793        // writer
10794        synchronized (mPackages) {
10795            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10796            if (!disabledSystem && deletedPackage != null) {
10797                // We didn't need to disable the .apk as a current system package,
10798                // which means we are replacing another update that is already
10799                // installed.  We need to make sure to delete the older one's .apk.
10800                res.removedInfo.args = createInstallArgsForExisting(0,
10801                        deletedPackage.applicationInfo.getCodePath(),
10802                        deletedPackage.applicationInfo.getResourcePath(),
10803                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10804                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10805            } else {
10806                res.removedInfo.args = null;
10807            }
10808        }
10809
10810        // Successfully disabled the old package. Now proceed with re-installation
10811        deleteCodeCacheDirsLI(packageName);
10812
10813        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10814        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10815
10816        PackageParser.Package newPackage = null;
10817        try {
10818            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10819            if (newPackage.mExtras != null) {
10820                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10821                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10822                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10823
10824                // is the update attempting to change shared user? that isn't going to work...
10825                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10826                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10827                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10828                            + " to " + newPkgSetting.sharedUser);
10829                    updatedSettings = true;
10830                }
10831            }
10832
10833            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10834                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res,
10835                        user);
10836                updatedSettings = true;
10837            }
10838
10839        } catch (PackageManagerException e) {
10840            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10841        }
10842
10843        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10844            // Re installation failed. Restore old information
10845            // Remove new pkg information
10846            if (newPackage != null) {
10847                removeInstalledPackageLI(newPackage, true);
10848            }
10849            // Add back the old system package
10850            try {
10851                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10852            } catch (PackageManagerException e) {
10853                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10854            }
10855            // Restore the old system information in Settings
10856            synchronized (mPackages) {
10857                if (disabledSystem) {
10858                    mSettings.enableSystemPackageLPw(packageName);
10859                }
10860                if (updatedSettings) {
10861                    mSettings.setInstallerPackageName(packageName,
10862                            oldPkgSetting.installerPackageName);
10863                }
10864                mSettings.writeLPr();
10865            }
10866        }
10867    }
10868
10869    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10870            int[] allUsers, boolean[] perUserInstalled,
10871            PackageInstalledInfo res, UserHandle user) {
10872        String pkgName = newPackage.packageName;
10873        synchronized (mPackages) {
10874            //write settings. the installStatus will be incomplete at this stage.
10875            //note that the new package setting would have already been
10876            //added to mPackages. It hasn't been persisted yet.
10877            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10878            mSettings.writeLPr();
10879        }
10880
10881        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10882
10883        synchronized (mPackages) {
10884            updatePermissionsLPw(newPackage.packageName, newPackage,
10885                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10886                            ? UPDATE_PERMISSIONS_ALL : 0));
10887            // For system-bundled packages, we assume that installing an upgraded version
10888            // of the package implies that the user actually wants to run that new code,
10889            // so we enable the package.
10890            PackageSetting ps = mSettings.mPackages.get(pkgName);
10891            if (ps != null) {
10892                if (isSystemApp(newPackage)) {
10893                    // NB: implicit assumption that system package upgrades apply to all users
10894                    if (DEBUG_INSTALL) {
10895                        Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10896                    }
10897                    if (res.origUsers != null) {
10898                        for (int userHandle : res.origUsers) {
10899                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10900                                    userHandle, installerPackageName);
10901                        }
10902                    }
10903                    // Also convey the prior install/uninstall state
10904                    if (allUsers != null && perUserInstalled != null) {
10905                        for (int i = 0; i < allUsers.length; i++) {
10906                            if (DEBUG_INSTALL) {
10907                                Slog.d(TAG, "    user " + allUsers[i]
10908                                        + " => " + perUserInstalled[i]);
10909                            }
10910                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10911                        }
10912                        // these install state changes will be persisted in the
10913                        // upcoming call to mSettings.writeLPr().
10914                    }
10915                }
10916                // It's implied that when a user requests installation, they want the app to be
10917                // installed and enabled.
10918                int userId = user.getIdentifier();
10919                if (userId != UserHandle.USER_ALL) {
10920                    ps.setInstalled(true, userId);
10921                    ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName);
10922                }
10923            }
10924            res.name = pkgName;
10925            res.uid = newPackage.applicationInfo.uid;
10926            res.pkg = newPackage;
10927            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10928            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10929            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10930            //to update install status
10931            mSettings.writeLPr();
10932        }
10933    }
10934
10935    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10936        final int installFlags = args.installFlags;
10937        String installerPackageName = args.installerPackageName;
10938        File tmpPackageFile = new File(args.getCodePath());
10939        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10940        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10941        boolean replace = false;
10942        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10943        // Result object to be returned
10944        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10945
10946        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10947        // Retrieve PackageSettings and parse package
10948        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10949                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10950                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10951        PackageParser pp = new PackageParser();
10952        pp.setSeparateProcesses(mSeparateProcesses);
10953        pp.setDisplayMetrics(mMetrics);
10954
10955        final PackageParser.Package pkg;
10956        try {
10957            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10958        } catch (PackageParserException e) {
10959            res.setError("Failed parse during installPackageLI", e);
10960            return;
10961        }
10962
10963        // Mark that we have an install time CPU ABI override.
10964        pkg.cpuAbiOverride = args.abiOverride;
10965
10966        String pkgName = res.name = pkg.packageName;
10967        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10968            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10969                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10970                return;
10971            }
10972        }
10973
10974        try {
10975            pp.collectCertificates(pkg, parseFlags);
10976            pp.collectManifestDigest(pkg);
10977        } catch (PackageParserException e) {
10978            res.setError("Failed collect during installPackageLI", e);
10979            return;
10980        }
10981
10982        /* If the installer passed in a manifest digest, compare it now. */
10983        if (args.manifestDigest != null) {
10984            if (DEBUG_INSTALL) {
10985                final String parsedManifest = pkg.manifestDigest == null ? "null"
10986                        : pkg.manifestDigest.toString();
10987                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10988                        + parsedManifest);
10989            }
10990
10991            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10992                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10993                return;
10994            }
10995        } else if (DEBUG_INSTALL) {
10996            final String parsedManifest = pkg.manifestDigest == null
10997                    ? "null" : pkg.manifestDigest.toString();
10998            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10999        }
11000
11001        // Get rid of all references to package scan path via parser.
11002        pp = null;
11003        String oldCodePath = null;
11004        boolean systemApp = false;
11005        synchronized (mPackages) {
11006            // Check if installing already existing package
11007            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
11008                String oldName = mSettings.mRenamedPackages.get(pkgName);
11009                if (pkg.mOriginalPackages != null
11010                        && pkg.mOriginalPackages.contains(oldName)
11011                        && mPackages.containsKey(oldName)) {
11012                    // This package is derived from an original package,
11013                    // and this device has been updating from that original
11014                    // name.  We must continue using the original name, so
11015                    // rename the new package here.
11016                    pkg.setPackageName(oldName);
11017                    pkgName = pkg.packageName;
11018                    replace = true;
11019                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
11020                            + oldName + " pkgName=" + pkgName);
11021                } else if (mPackages.containsKey(pkgName)) {
11022                    // This package, under its official name, already exists
11023                    // on the device; we should replace it.
11024                    replace = true;
11025                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
11026                }
11027            }
11028
11029            PackageSetting ps = mSettings.mPackages.get(pkgName);
11030            if (ps != null) {
11031                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
11032
11033                // Quick sanity check that we're signed correctly if updating;
11034                // we'll check this again later when scanning, but we want to
11035                // bail early here before tripping over redefined permissions.
11036                if (!ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
11037                    try {
11038                        verifySignaturesLP(ps, pkg);
11039                    } catch (PackageManagerException e) {
11040                        res.setError(e.error, e.getMessage());
11041                        return;
11042                    }
11043                } else {
11044                    if (!checkUpgradeKeySetLP(ps, pkg)) {
11045                        res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
11046                                + pkg.packageName + " upgrade keys do not match the "
11047                                + "previously installed version");
11048                        return;
11049                    }
11050                }
11051
11052                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
11053                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
11054                    systemApp = (ps.pkg.applicationInfo.flags &
11055                            ApplicationInfo.FLAG_SYSTEM) != 0;
11056                }
11057                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11058            }
11059
11060            // Check whether the newly-scanned package wants to define an already-defined perm
11061            int N = pkg.permissions.size();
11062            for (int i = N-1; i >= 0; i--) {
11063                PackageParser.Permission perm = pkg.permissions.get(i);
11064                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
11065                if (bp != null) {
11066                    // If the defining package is signed with our cert, it's okay.  This
11067                    // also includes the "updating the same package" case, of course.
11068                    // "updating same package" could also involve key-rotation.
11069                    final boolean sigsOk;
11070                    if (!bp.sourcePackage.equals(pkg.packageName)
11071                            || !(bp.packageSetting instanceof PackageSetting)
11072                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
11073                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
11074                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
11075                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
11076                    } else {
11077                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
11078                    }
11079                    if (!sigsOk) {
11080                        // If the owning package is the system itself, we log but allow
11081                        // install to proceed; we fail the install on all other permission
11082                        // redefinitions.
11083                        if (!bp.sourcePackage.equals("android")) {
11084                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
11085                                    + pkg.packageName + " attempting to redeclare permission "
11086                                    + perm.info.name + " already owned by " + bp.sourcePackage);
11087                            res.origPermission = perm.info.name;
11088                            res.origPackage = bp.sourcePackage;
11089                            return;
11090                        } else {
11091                            Slog.w(TAG, "Package " + pkg.packageName
11092                                    + " attempting to redeclare system permission "
11093                                    + perm.info.name + "; ignoring new declaration");
11094                            pkg.permissions.remove(i);
11095                        }
11096                    }
11097                }
11098            }
11099
11100        }
11101
11102        if (systemApp && onSd) {
11103            // Disable updates to system apps on sdcard
11104            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
11105                    "Cannot install updates to system apps on sdcard");
11106            return;
11107        }
11108
11109        // Run dexopt before old package gets removed, to minimize time when app is not available
11110        int result = mPackageDexOptimizer
11111                .performDexOpt(pkg, null /* instruction sets */, true /* forceDex */,
11112                        false /* defer */, false /* inclDependencies */);
11113        if (result == PackageDexOptimizer.DEX_OPT_FAILED) {
11114            res.setError(INSTALL_FAILED_DEXOPT, "Dexopt failed for " + pkg.codePath);
11115            return;
11116        }
11117
11118        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
11119            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
11120            return;
11121        }
11122
11123        startIntentFilterVerifications(args.user.getIdentifier(), pkg);
11124
11125        if (replace) {
11126            // Call replacePackageLI with SCAN_NO_DEX, since we already made dexopt
11127            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING | SCAN_NO_DEX, args.user,
11128                    installerPackageName, res);
11129        } else {
11130            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
11131                    args.user, installerPackageName, res);
11132        }
11133        synchronized (mPackages) {
11134            final PackageSetting ps = mSettings.mPackages.get(pkgName);
11135            if (ps != null) {
11136                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
11137            }
11138        }
11139    }
11140
11141    private void startIntentFilterVerifications(int userId, PackageParser.Package pkg) {
11142        if (mIntentFilterVerifierComponent == null) {
11143            Slog.d(TAG, "No IntentFilter verification will not be done as "
11144                    + "there is no IntentFilterVerifier available!");
11145            return;
11146        }
11147
11148        final int verifierUid = getPackageUid(
11149                mIntentFilterVerifierComponent.getPackageName(),
11150                (userId == UserHandle.USER_ALL) ? UserHandle.USER_OWNER : userId);
11151
11152        mHandler.removeMessages(START_INTENT_FILTER_VERIFICATIONS);
11153        final Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS);
11154        msg.obj = pkg;
11155        msg.arg1 = userId;
11156        msg.arg2 = verifierUid;
11157
11158        mHandler.sendMessage(msg);
11159    }
11160
11161    private void verifyIntentFiltersIfNeeded(int userId, int verifierUid,
11162                                             PackageParser.Package pkg) {
11163        int size = pkg.activities.size();
11164        if (size == 0) {
11165            Slog.d(TAG, "No activity, so no need to verify any IntentFilter!");
11166            return;
11167        }
11168
11169        Slog.d(TAG, "Checking for userId:" + userId + " if any IntentFilter from the " + size
11170                + " Activities needs verification ...");
11171
11172        final int verificationId = mIntentFilterVerificationToken++;
11173        int count = 0;
11174        synchronized (mPackages) {
11175            for (PackageParser.Activity a : pkg.activities) {
11176                for (ActivityIntentInfo filter : a.intents) {
11177                    boolean needFilterVerification = filter.needsVerification() &&
11178                            !filter.isVerified();
11179                    if (needFilterVerification && needNetworkVerificationLPr(filter)) {
11180                        Slog.d(TAG, "Verification needed for IntentFilter:" + filter.toString());
11181                        mIntentFilterVerifier.addOneIntentFilterVerification(
11182                                verifierUid, userId, verificationId, filter, pkg.packageName);
11183                        count++;
11184                    } else {
11185                        Slog.d(TAG, "No verification needed for IntentFilter:" + filter.toString());
11186                    }
11187                }
11188            }
11189        }
11190
11191        if (count > 0) {
11192            mIntentFilterVerifier.startVerifications(userId);
11193            Slog.d(TAG, "Started " + count + " IntentFilter verification"
11194                    + (count > 1 ? "s" : "") +  " for userId:" + userId + "!");
11195        } else {
11196            Slog.d(TAG, "No need to start any IntentFilter verification!");
11197        }
11198    }
11199
11200    private boolean needNetworkVerificationLPr(ActivityIntentInfo filter) {
11201        final ComponentName cn  = filter.activity.getComponentName();
11202        final String packageName = cn.getPackageName();
11203
11204        IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr(
11205                packageName);
11206        if (ivi == null) {
11207            return true;
11208        }
11209        int status = ivi.getStatus();
11210        switch (status) {
11211            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED:
11212            case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK:
11213                return true;
11214
11215            default:
11216                // Nothing to do
11217                return false;
11218        }
11219    }
11220
11221    private static boolean isMultiArch(PackageSetting ps) {
11222        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11223    }
11224
11225    private static boolean isMultiArch(ApplicationInfo info) {
11226        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
11227    }
11228
11229    private static boolean isExternal(PackageParser.Package pkg) {
11230        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11231    }
11232
11233    private static boolean isExternal(PackageSetting ps) {
11234        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11235    }
11236
11237    private static boolean isExternal(ApplicationInfo info) {
11238        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
11239    }
11240
11241    private static boolean isSystemApp(PackageParser.Package pkg) {
11242        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
11243    }
11244
11245    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
11246        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
11247    }
11248
11249    private static boolean isSystemApp(PackageSetting ps) {
11250        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
11251    }
11252
11253    private static boolean isUpdatedSystemApp(PackageSetting ps) {
11254        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
11255    }
11256
11257    private int packageFlagsToInstallFlags(PackageSetting ps) {
11258        int installFlags = 0;
11259        if (isExternal(ps)) {
11260            installFlags |= PackageManager.INSTALL_EXTERNAL;
11261        }
11262        if (ps.isForwardLocked()) {
11263            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
11264        }
11265        return installFlags;
11266    }
11267
11268    private void deleteTempPackageFiles() {
11269        final FilenameFilter filter = new FilenameFilter() {
11270            public boolean accept(File dir, String name) {
11271                return name.startsWith("vmdl") && name.endsWith(".tmp");
11272            }
11273        };
11274        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
11275            file.delete();
11276        }
11277    }
11278
11279    @Override
11280    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
11281            int flags) {
11282        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
11283                flags);
11284    }
11285
11286    @Override
11287    public void deletePackage(final String packageName,
11288            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
11289        mContext.enforceCallingOrSelfPermission(
11290                android.Manifest.permission.DELETE_PACKAGES, null);
11291        final int uid = Binder.getCallingUid();
11292        if (UserHandle.getUserId(uid) != userId) {
11293            mContext.enforceCallingPermission(
11294                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
11295                    "deletePackage for user " + userId);
11296        }
11297        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
11298            try {
11299                observer.onPackageDeleted(packageName,
11300                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
11301            } catch (RemoteException re) {
11302            }
11303            return;
11304        }
11305
11306        boolean uninstallBlocked = false;
11307        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
11308            int[] users = sUserManager.getUserIds();
11309            for (int i = 0; i < users.length; ++i) {
11310                if (getBlockUninstallForUser(packageName, users[i])) {
11311                    uninstallBlocked = true;
11312                    break;
11313                }
11314            }
11315        } else {
11316            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
11317        }
11318        if (uninstallBlocked) {
11319            try {
11320                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
11321                        null);
11322            } catch (RemoteException re) {
11323            }
11324            return;
11325        }
11326
11327        if (DEBUG_REMOVE) {
11328            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
11329        }
11330        // Queue up an async operation since the package deletion may take a little while.
11331        mHandler.post(new Runnable() {
11332            public void run() {
11333                mHandler.removeCallbacks(this);
11334                final int returnCode = deletePackageX(packageName, userId, flags);
11335                if (observer != null) {
11336                    try {
11337                        observer.onPackageDeleted(packageName, returnCode, null);
11338                    } catch (RemoteException e) {
11339                        Log.i(TAG, "Observer no longer exists.");
11340                    } //end catch
11341                } //end if
11342            } //end run
11343        });
11344    }
11345
11346    private boolean isPackageDeviceAdmin(String packageName, int userId) {
11347        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
11348                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
11349        try {
11350            if (dpm != null) {
11351                if (dpm.isDeviceOwner(packageName)) {
11352                    return true;
11353                }
11354                int[] users;
11355                if (userId == UserHandle.USER_ALL) {
11356                    users = sUserManager.getUserIds();
11357                } else {
11358                    users = new int[]{userId};
11359                }
11360                for (int i = 0; i < users.length; ++i) {
11361                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
11362                        return true;
11363                    }
11364                }
11365            }
11366        } catch (RemoteException e) {
11367        }
11368        return false;
11369    }
11370
11371    /**
11372     *  This method is an internal method that could be get invoked either
11373     *  to delete an installed package or to clean up a failed installation.
11374     *  After deleting an installed package, a broadcast is sent to notify any
11375     *  listeners that the package has been installed. For cleaning up a failed
11376     *  installation, the broadcast is not necessary since the package's
11377     *  installation wouldn't have sent the initial broadcast either
11378     *  The key steps in deleting a package are
11379     *  deleting the package information in internal structures like mPackages,
11380     *  deleting the packages base directories through installd
11381     *  updating mSettings to reflect current status
11382     *  persisting settings for later use
11383     *  sending a broadcast if necessary
11384     */
11385    private int deletePackageX(String packageName, int userId, int flags) {
11386        final PackageRemovedInfo info = new PackageRemovedInfo();
11387        final boolean res;
11388
11389        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
11390                ? UserHandle.ALL : new UserHandle(userId);
11391
11392        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
11393            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
11394            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
11395        }
11396
11397        boolean removedForAllUsers = false;
11398        boolean systemUpdate = false;
11399
11400        // for the uninstall-updates case and restricted profiles, remember the per-
11401        // userhandle installed state
11402        int[] allUsers;
11403        boolean[] perUserInstalled;
11404        synchronized (mPackages) {
11405            PackageSetting ps = mSettings.mPackages.get(packageName);
11406            allUsers = sUserManager.getUserIds();
11407            perUserInstalled = new boolean[allUsers.length];
11408            for (int i = 0; i < allUsers.length; i++) {
11409                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
11410            }
11411        }
11412
11413        synchronized (mInstallLock) {
11414            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
11415            res = deletePackageLI(packageName, removeForUser,
11416                    true, allUsers, perUserInstalled,
11417                    flags | REMOVE_CHATTY, info, true);
11418            systemUpdate = info.isRemovedPackageSystemUpdate;
11419            if (res && !systemUpdate && mPackages.get(packageName) == null) {
11420                removedForAllUsers = true;
11421            }
11422            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
11423                    + " removedForAllUsers=" + removedForAllUsers);
11424        }
11425
11426        if (res) {
11427            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
11428
11429            // If the removed package was a system update, the old system package
11430            // was re-enabled; we need to broadcast this information
11431            if (systemUpdate) {
11432                Bundle extras = new Bundle(1);
11433                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
11434                        ? info.removedAppId : info.uid);
11435                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11436
11437                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
11438                        extras, null, null, null);
11439                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
11440                        extras, null, null, null);
11441                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
11442                        null, packageName, null, null);
11443            }
11444        }
11445        // Force a gc here.
11446        Runtime.getRuntime().gc();
11447        // Delete the resources here after sending the broadcast to let
11448        // other processes clean up before deleting resources.
11449        if (info.args != null) {
11450            synchronized (mInstallLock) {
11451                info.args.doPostDeleteLI(true);
11452            }
11453        }
11454
11455        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
11456    }
11457
11458    static class PackageRemovedInfo {
11459        String removedPackage;
11460        int uid = -1;
11461        int removedAppId = -1;
11462        int[] removedUsers = null;
11463        boolean isRemovedPackageSystemUpdate = false;
11464        // Clean up resources deleted packages.
11465        InstallArgs args = null;
11466
11467        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
11468            Bundle extras = new Bundle(1);
11469            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
11470            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
11471            if (replacing) {
11472                extras.putBoolean(Intent.EXTRA_REPLACING, true);
11473            }
11474            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
11475            if (removedPackage != null) {
11476                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
11477                        extras, null, null, removedUsers);
11478                if (fullRemove && !replacing) {
11479                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
11480                            extras, null, null, removedUsers);
11481                }
11482            }
11483            if (removedAppId >= 0) {
11484                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
11485                        removedUsers);
11486            }
11487        }
11488    }
11489
11490    /*
11491     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
11492     * flag is not set, the data directory is removed as well.
11493     * make sure this flag is set for partially installed apps. If not its meaningless to
11494     * delete a partially installed application.
11495     */
11496    private void removePackageDataLI(PackageSetting ps,
11497            int[] allUserHandles, boolean[] perUserInstalled,
11498            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
11499        String packageName = ps.name;
11500        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
11501        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
11502        // Retrieve object to delete permissions for shared user later on
11503        final PackageSetting deletedPs;
11504        // reader
11505        synchronized (mPackages) {
11506            deletedPs = mSettings.mPackages.get(packageName);
11507            if (outInfo != null) {
11508                outInfo.removedPackage = packageName;
11509                outInfo.removedUsers = deletedPs != null
11510                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
11511                        : null;
11512            }
11513        }
11514        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11515            removeDataDirsLI(packageName);
11516            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
11517        }
11518        // writer
11519        synchronized (mPackages) {
11520            if (deletedPs != null) {
11521                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
11522                    if (outInfo != null) {
11523                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
11524                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
11525                    }
11526                    updatePermissionsLPw(deletedPs.name, null, 0);
11527                    if (deletedPs.sharedUser != null) {
11528                        // Remove permissions associated with package. Since runtime
11529                        // permissions are per user we have to kill the removed package
11530                        // or packages running under the shared user of the removed
11531                        // package if revoking the permissions requested only by the removed
11532                        // package is successful and this causes a change in gids.
11533                        for (int userId : UserManagerService.getInstance().getUserIds()) {
11534                            final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs,
11535                                    userId);
11536                            if (userIdToKill == UserHandle.USER_ALL
11537                                    || userIdToKill >= UserHandle.USER_OWNER) {
11538                                // If gids changed for this user, kill all affected packages.
11539                                mHandler.post(new Runnable() {
11540                                    @Override
11541                                    public void run() {
11542                                        // This has to happen with no lock held.
11543                                        killSettingPackagesForUser(deletedPs, userIdToKill,
11544                                                KILL_APP_REASON_GIDS_CHANGED);
11545                                    }
11546                                });
11547                            break;
11548                            }
11549                        }
11550                    }
11551                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
11552                    clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL);
11553                }
11554                // make sure to preserve per-user disabled state if this removal was just
11555                // a downgrade of a system app to the factory package
11556                if (allUserHandles != null && perUserInstalled != null) {
11557                    if (DEBUG_REMOVE) {
11558                        Slog.d(TAG, "Propagating install state across downgrade");
11559                    }
11560                    for (int i = 0; i < allUserHandles.length; i++) {
11561                        if (DEBUG_REMOVE) {
11562                            Slog.d(TAG, "    user " + allUserHandles[i]
11563                                    + " => " + perUserInstalled[i]);
11564                        }
11565                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11566                    }
11567                }
11568            }
11569            // can downgrade to reader
11570            if (writeSettings) {
11571                // Save settings now
11572                mSettings.writeLPr();
11573            }
11574        }
11575        if (outInfo != null) {
11576            // A user ID was deleted here. Go through all users and remove it
11577            // from KeyStore.
11578            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
11579        }
11580    }
11581
11582    static boolean locationIsPrivileged(File path) {
11583        try {
11584            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
11585                    .getCanonicalPath();
11586            return path.getCanonicalPath().startsWith(privilegedAppDir);
11587        } catch (IOException e) {
11588            Slog.e(TAG, "Unable to access code path " + path);
11589        }
11590        return false;
11591    }
11592
11593    /*
11594     * Tries to delete system package.
11595     */
11596    private boolean deleteSystemPackageLI(PackageSetting newPs,
11597            int[] allUserHandles, boolean[] perUserInstalled,
11598            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
11599        final boolean applyUserRestrictions
11600                = (allUserHandles != null) && (perUserInstalled != null);
11601        PackageSetting disabledPs = null;
11602        // Confirm if the system package has been updated
11603        // An updated system app can be deleted. This will also have to restore
11604        // the system pkg from system partition
11605        // reader
11606        synchronized (mPackages) {
11607            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
11608        }
11609        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
11610                + " disabledPs=" + disabledPs);
11611        if (disabledPs == null) {
11612            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
11613            return false;
11614        } else if (DEBUG_REMOVE) {
11615            Slog.d(TAG, "Deleting system pkg from data partition");
11616        }
11617        if (DEBUG_REMOVE) {
11618            if (applyUserRestrictions) {
11619                Slog.d(TAG, "Remembering install states:");
11620                for (int i = 0; i < allUserHandles.length; i++) {
11621                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
11622                }
11623            }
11624        }
11625        // Delete the updated package
11626        outInfo.isRemovedPackageSystemUpdate = true;
11627        if (disabledPs.versionCode < newPs.versionCode) {
11628            // Delete data for downgrades
11629            flags &= ~PackageManager.DELETE_KEEP_DATA;
11630        } else {
11631            // Preserve data by setting flag
11632            flags |= PackageManager.DELETE_KEEP_DATA;
11633        }
11634        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
11635                allUserHandles, perUserInstalled, outInfo, writeSettings);
11636        if (!ret) {
11637            return false;
11638        }
11639        // writer
11640        synchronized (mPackages) {
11641            // Reinstate the old system package
11642            mSettings.enableSystemPackageLPw(newPs.name);
11643            // Remove any native libraries from the upgraded package.
11644            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
11645        }
11646        // Install the system package
11647        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
11648        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
11649        if (locationIsPrivileged(disabledPs.codePath)) {
11650            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
11651        }
11652
11653        final PackageParser.Package newPkg;
11654        try {
11655            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
11656        } catch (PackageManagerException e) {
11657            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11658            return false;
11659        }
11660
11661        // writer
11662        synchronized (mPackages) {
11663            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11664            updatePermissionsLPw(newPkg.packageName, newPkg,
11665                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11666            if (applyUserRestrictions) {
11667                if (DEBUG_REMOVE) {
11668                    Slog.d(TAG, "Propagating install state across reinstall");
11669                }
11670                for (int i = 0; i < allUserHandles.length; i++) {
11671                    if (DEBUG_REMOVE) {
11672                        Slog.d(TAG, "    user " + allUserHandles[i]
11673                                + " => " + perUserInstalled[i]);
11674                    }
11675                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11676                }
11677                // Regardless of writeSettings we need to ensure that this restriction
11678                // state propagation is persisted
11679                mSettings.writeAllUsersPackageRestrictionsLPr();
11680            }
11681            // can downgrade to reader here
11682            if (writeSettings) {
11683                mSettings.writeLPr();
11684            }
11685        }
11686        return true;
11687    }
11688
11689    private boolean deleteInstalledPackageLI(PackageSetting ps,
11690            boolean deleteCodeAndResources, int flags,
11691            int[] allUserHandles, boolean[] perUserInstalled,
11692            PackageRemovedInfo outInfo, boolean writeSettings) {
11693        if (outInfo != null) {
11694            outInfo.uid = ps.appId;
11695        }
11696
11697        // Delete package data from internal structures and also remove data if flag is set
11698        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11699
11700        // Delete application code and resources
11701        if (deleteCodeAndResources && (outInfo != null)) {
11702            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11703                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11704                    getAppDexInstructionSets(ps));
11705            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11706        }
11707        return true;
11708    }
11709
11710    @Override
11711    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11712            int userId) {
11713        mContext.enforceCallingOrSelfPermission(
11714                android.Manifest.permission.DELETE_PACKAGES, null);
11715        synchronized (mPackages) {
11716            PackageSetting ps = mSettings.mPackages.get(packageName);
11717            if (ps == null) {
11718                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11719                return false;
11720            }
11721            if (!ps.getInstalled(userId)) {
11722                // Can't block uninstall for an app that is not installed or enabled.
11723                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11724                return false;
11725            }
11726            ps.setBlockUninstall(blockUninstall, userId);
11727            mSettings.writePackageRestrictionsLPr(userId);
11728        }
11729        return true;
11730    }
11731
11732    @Override
11733    public boolean getBlockUninstallForUser(String packageName, int userId) {
11734        synchronized (mPackages) {
11735            PackageSetting ps = mSettings.mPackages.get(packageName);
11736            if (ps == null) {
11737                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11738                return false;
11739            }
11740            return ps.getBlockUninstall(userId);
11741        }
11742    }
11743
11744    /*
11745     * This method handles package deletion in general
11746     */
11747    private boolean deletePackageLI(String packageName, UserHandle user,
11748            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11749            int flags, PackageRemovedInfo outInfo,
11750            boolean writeSettings) {
11751        if (packageName == null) {
11752            Slog.w(TAG, "Attempt to delete null packageName.");
11753            return false;
11754        }
11755        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11756        PackageSetting ps;
11757        boolean dataOnly = false;
11758        int removeUser = -1;
11759        int appId = -1;
11760        synchronized (mPackages) {
11761            ps = mSettings.mPackages.get(packageName);
11762            if (ps == null) {
11763                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11764                return false;
11765            }
11766            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11767                    && user.getIdentifier() != UserHandle.USER_ALL) {
11768                // The caller is asking that the package only be deleted for a single
11769                // user.  To do this, we just mark its uninstalled state and delete
11770                // its data.  If this is a system app, we only allow this to happen if
11771                // they have set the special DELETE_SYSTEM_APP which requests different
11772                // semantics than normal for uninstalling system apps.
11773                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11774                ps.setUserState(user.getIdentifier(),
11775                        COMPONENT_ENABLED_STATE_DEFAULT,
11776                        false, //installed
11777                        true,  //stopped
11778                        true,  //notLaunched
11779                        false, //hidden
11780                        null, null, null,
11781                        false, // blockUninstall
11782                        INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED);
11783                if (!isSystemApp(ps)) {
11784                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11785                        // Other user still have this package installed, so all
11786                        // we need to do is clear this user's data and save that
11787                        // it is uninstalled.
11788                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11789                        removeUser = user.getIdentifier();
11790                        appId = ps.appId;
11791                        mSettings.writePackageRestrictionsLPr(removeUser);
11792                    } else {
11793                        // We need to set it back to 'installed' so the uninstall
11794                        // broadcasts will be sent correctly.
11795                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11796                        ps.setInstalled(true, user.getIdentifier());
11797                    }
11798                } else {
11799                    // This is a system app, so we assume that the
11800                    // other users still have this package installed, so all
11801                    // we need to do is clear this user's data and save that
11802                    // it is uninstalled.
11803                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11804                    removeUser = user.getIdentifier();
11805                    appId = ps.appId;
11806                    mSettings.writePackageRestrictionsLPr(removeUser);
11807                }
11808            }
11809        }
11810
11811        if (removeUser >= 0) {
11812            // From above, we determined that we are deleting this only
11813            // for a single user.  Continue the work here.
11814            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11815            if (outInfo != null) {
11816                outInfo.removedPackage = packageName;
11817                outInfo.removedAppId = appId;
11818                outInfo.removedUsers = new int[] {removeUser};
11819            }
11820            mInstaller.clearUserData(packageName, removeUser);
11821            removeKeystoreDataIfNeeded(removeUser, appId);
11822            schedulePackageCleaning(packageName, removeUser, false);
11823            return true;
11824        }
11825
11826        if (dataOnly) {
11827            // Delete application data first
11828            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11829            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11830            return true;
11831        }
11832
11833        boolean ret = false;
11834        if (isSystemApp(ps)) {
11835            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11836            // When an updated system application is deleted we delete the existing resources as well and
11837            // fall back to existing code in system partition
11838            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11839                    flags, outInfo, writeSettings);
11840        } else {
11841            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11842            // Kill application pre-emptively especially for apps on sd.
11843            killApplication(packageName, ps.appId, "uninstall pkg");
11844            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11845                    allUserHandles, perUserInstalled,
11846                    outInfo, writeSettings);
11847        }
11848
11849        return ret;
11850    }
11851
11852    private final class ClearStorageConnection implements ServiceConnection {
11853        IMediaContainerService mContainerService;
11854
11855        @Override
11856        public void onServiceConnected(ComponentName name, IBinder service) {
11857            synchronized (this) {
11858                mContainerService = IMediaContainerService.Stub.asInterface(service);
11859                notifyAll();
11860            }
11861        }
11862
11863        @Override
11864        public void onServiceDisconnected(ComponentName name) {
11865        }
11866    }
11867
11868    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11869        final boolean mounted;
11870        if (Environment.isExternalStorageEmulated()) {
11871            mounted = true;
11872        } else {
11873            final String status = Environment.getExternalStorageState();
11874
11875            mounted = status.equals(Environment.MEDIA_MOUNTED)
11876                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11877        }
11878
11879        if (!mounted) {
11880            return;
11881        }
11882
11883        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11884        int[] users;
11885        if (userId == UserHandle.USER_ALL) {
11886            users = sUserManager.getUserIds();
11887        } else {
11888            users = new int[] { userId };
11889        }
11890        final ClearStorageConnection conn = new ClearStorageConnection();
11891        if (mContext.bindServiceAsUser(
11892                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11893            try {
11894                for (int curUser : users) {
11895                    long timeout = SystemClock.uptimeMillis() + 5000;
11896                    synchronized (conn) {
11897                        long now = SystemClock.uptimeMillis();
11898                        while (conn.mContainerService == null && now < timeout) {
11899                            try {
11900                                conn.wait(timeout - now);
11901                            } catch (InterruptedException e) {
11902                            }
11903                        }
11904                    }
11905                    if (conn.mContainerService == null) {
11906                        return;
11907                    }
11908
11909                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11910                    clearDirectory(conn.mContainerService,
11911                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11912                    if (allData) {
11913                        clearDirectory(conn.mContainerService,
11914                                userEnv.buildExternalStorageAppDataDirs(packageName));
11915                        clearDirectory(conn.mContainerService,
11916                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11917                    }
11918                }
11919            } finally {
11920                mContext.unbindService(conn);
11921            }
11922        }
11923    }
11924
11925    @Override
11926    public void clearApplicationUserData(final String packageName,
11927            final IPackageDataObserver observer, final int userId) {
11928        mContext.enforceCallingOrSelfPermission(
11929                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11930        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11931        // Queue up an async operation since the package deletion may take a little while.
11932        mHandler.post(new Runnable() {
11933            public void run() {
11934                mHandler.removeCallbacks(this);
11935                final boolean succeeded;
11936                synchronized (mInstallLock) {
11937                    succeeded = clearApplicationUserDataLI(packageName, userId);
11938                }
11939                clearExternalStorageDataSync(packageName, userId, true);
11940                if (succeeded) {
11941                    // invoke DeviceStorageMonitor's update method to clear any notifications
11942                    DeviceStorageMonitorInternal
11943                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11944                    if (dsm != null) {
11945                        dsm.checkMemory();
11946                    }
11947                }
11948                if(observer != null) {
11949                    try {
11950                        observer.onRemoveCompleted(packageName, succeeded);
11951                    } catch (RemoteException e) {
11952                        Log.i(TAG, "Observer no longer exists.");
11953                    }
11954                } //end if observer
11955            } //end run
11956        });
11957    }
11958
11959    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11960        if (packageName == null) {
11961            Slog.w(TAG, "Attempt to delete null packageName.");
11962            return false;
11963        }
11964
11965        // Try finding details about the requested package
11966        PackageParser.Package pkg;
11967        synchronized (mPackages) {
11968            pkg = mPackages.get(packageName);
11969            if (pkg == null) {
11970                final PackageSetting ps = mSettings.mPackages.get(packageName);
11971                if (ps != null) {
11972                    pkg = ps.pkg;
11973                }
11974            }
11975        }
11976
11977        if (pkg == null) {
11978            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11979        }
11980
11981        // Always delete data directories for package, even if we found no other
11982        // record of app. This helps users recover from UID mismatches without
11983        // resorting to a full data wipe.
11984        int retCode = mInstaller.clearUserData(packageName, userId);
11985        if (retCode < 0) {
11986            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11987            return false;
11988        }
11989
11990        if (pkg == null) {
11991            return false;
11992        }
11993
11994        if (pkg != null && pkg.applicationInfo != null) {
11995            final int appId = pkg.applicationInfo.uid;
11996            removeKeystoreDataIfNeeded(userId, appId);
11997        }
11998
11999        // Create a native library symlink only if we have native libraries
12000        // and if the native libraries are 32 bit libraries. We do not provide
12001        // this symlink for 64 bit libraries.
12002        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
12003                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
12004            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
12005            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
12006                Slog.w(TAG, "Failed linking native library dir");
12007                return false;
12008            }
12009        }
12010
12011        return true;
12012    }
12013
12014    /**
12015     * Remove entries from the keystore daemon. Will only remove it if the
12016     * {@code appId} is valid.
12017     */
12018    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
12019        if (appId < 0) {
12020            return;
12021        }
12022
12023        final KeyStore keyStore = KeyStore.getInstance();
12024        if (keyStore != null) {
12025            if (userId == UserHandle.USER_ALL) {
12026                for (final int individual : sUserManager.getUserIds()) {
12027                    keyStore.clearUid(UserHandle.getUid(individual, appId));
12028                }
12029            } else {
12030                keyStore.clearUid(UserHandle.getUid(userId, appId));
12031            }
12032        } else {
12033            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
12034        }
12035    }
12036
12037    @Override
12038    public void deleteApplicationCacheFiles(final String packageName,
12039            final IPackageDataObserver observer) {
12040        mContext.enforceCallingOrSelfPermission(
12041                android.Manifest.permission.DELETE_CACHE_FILES, null);
12042        // Queue up an async operation since the package deletion may take a little while.
12043        final int userId = UserHandle.getCallingUserId();
12044        mHandler.post(new Runnable() {
12045            public void run() {
12046                mHandler.removeCallbacks(this);
12047                final boolean succeded;
12048                synchronized (mInstallLock) {
12049                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
12050                }
12051                clearExternalStorageDataSync(packageName, userId, false);
12052                if(observer != null) {
12053                    try {
12054                        observer.onRemoveCompleted(packageName, succeded);
12055                    } catch (RemoteException e) {
12056                        Log.i(TAG, "Observer no longer exists.");
12057                    }
12058                } //end if observer
12059            } //end run
12060        });
12061    }
12062
12063    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
12064        if (packageName == null) {
12065            Slog.w(TAG, "Attempt to delete null packageName.");
12066            return false;
12067        }
12068        PackageParser.Package p;
12069        synchronized (mPackages) {
12070            p = mPackages.get(packageName);
12071        }
12072        if (p == null) {
12073            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12074            return false;
12075        }
12076        final ApplicationInfo applicationInfo = p.applicationInfo;
12077        if (applicationInfo == null) {
12078            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12079            return false;
12080        }
12081        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
12082        if (retCode < 0) {
12083            Slog.w(TAG, "Couldn't remove cache files for package: "
12084                       + packageName + " u" + userId);
12085            return false;
12086        }
12087        return true;
12088    }
12089
12090    @Override
12091    public void getPackageSizeInfo(final String packageName, int userHandle,
12092            final IPackageStatsObserver observer) {
12093        mContext.enforceCallingOrSelfPermission(
12094                android.Manifest.permission.GET_PACKAGE_SIZE, null);
12095        if (packageName == null) {
12096            throw new IllegalArgumentException("Attempt to get size of null packageName");
12097        }
12098
12099        PackageStats stats = new PackageStats(packageName, userHandle);
12100
12101        /*
12102         * Queue up an async operation since the package measurement may take a
12103         * little while.
12104         */
12105        Message msg = mHandler.obtainMessage(INIT_COPY);
12106        msg.obj = new MeasureParams(stats, observer);
12107        mHandler.sendMessage(msg);
12108    }
12109
12110    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
12111            PackageStats pStats) {
12112        if (packageName == null) {
12113            Slog.w(TAG, "Attempt to get size of null packageName.");
12114            return false;
12115        }
12116        PackageParser.Package p;
12117        boolean dataOnly = false;
12118        String libDirRoot = null;
12119        String asecPath = null;
12120        PackageSetting ps = null;
12121        synchronized (mPackages) {
12122            p = mPackages.get(packageName);
12123            ps = mSettings.mPackages.get(packageName);
12124            if(p == null) {
12125                dataOnly = true;
12126                if((ps == null) || (ps.pkg == null)) {
12127                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
12128                    return false;
12129                }
12130                p = ps.pkg;
12131            }
12132            if (ps != null) {
12133                libDirRoot = ps.legacyNativeLibraryPathString;
12134            }
12135            if (p != null && (isExternal(p) || p.isForwardLocked())) {
12136                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
12137                if (secureContainerId != null) {
12138                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
12139                }
12140            }
12141        }
12142        String publicSrcDir = null;
12143        if(!dataOnly) {
12144            final ApplicationInfo applicationInfo = p.applicationInfo;
12145            if (applicationInfo == null) {
12146                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
12147                return false;
12148            }
12149            if (p.isForwardLocked()) {
12150                publicSrcDir = applicationInfo.getBaseResourcePath();
12151            }
12152        }
12153        // TODO: extend to measure size of split APKs
12154        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
12155        // not just the first level.
12156        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
12157        // just the primary.
12158        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
12159        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
12160                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
12161        if (res < 0) {
12162            return false;
12163        }
12164
12165        // Fix-up for forward-locked applications in ASEC containers.
12166        if (!isExternal(p)) {
12167            pStats.codeSize += pStats.externalCodeSize;
12168            pStats.externalCodeSize = 0L;
12169        }
12170
12171        return true;
12172    }
12173
12174
12175    @Override
12176    public void addPackageToPreferred(String packageName) {
12177        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
12178    }
12179
12180    @Override
12181    public void removePackageFromPreferred(String packageName) {
12182        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
12183    }
12184
12185    @Override
12186    public List<PackageInfo> getPreferredPackages(int flags) {
12187        return new ArrayList<PackageInfo>();
12188    }
12189
12190    private int getUidTargetSdkVersionLockedLPr(int uid) {
12191        Object obj = mSettings.getUserIdLPr(uid);
12192        if (obj instanceof SharedUserSetting) {
12193            final SharedUserSetting sus = (SharedUserSetting) obj;
12194            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
12195            final Iterator<PackageSetting> it = sus.packages.iterator();
12196            while (it.hasNext()) {
12197                final PackageSetting ps = it.next();
12198                if (ps.pkg != null) {
12199                    int v = ps.pkg.applicationInfo.targetSdkVersion;
12200                    if (v < vers) vers = v;
12201                }
12202            }
12203            return vers;
12204        } else if (obj instanceof PackageSetting) {
12205            final PackageSetting ps = (PackageSetting) obj;
12206            if (ps.pkg != null) {
12207                return ps.pkg.applicationInfo.targetSdkVersion;
12208            }
12209        }
12210        return Build.VERSION_CODES.CUR_DEVELOPMENT;
12211    }
12212
12213    @Override
12214    public void addPreferredActivity(IntentFilter filter, int match,
12215            ComponentName[] set, ComponentName activity, int userId) {
12216        addPreferredActivityInternal(filter, match, set, activity, true, userId,
12217                "Adding preferred");
12218    }
12219
12220    private void addPreferredActivityInternal(IntentFilter filter, int match,
12221            ComponentName[] set, ComponentName activity, boolean always, int userId,
12222            String opname) {
12223        // writer
12224        int callingUid = Binder.getCallingUid();
12225        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
12226        if (filter.countActions() == 0) {
12227            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12228            return;
12229        }
12230        synchronized (mPackages) {
12231            if (mContext.checkCallingOrSelfPermission(
12232                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12233                    != PackageManager.PERMISSION_GRANTED) {
12234                if (getUidTargetSdkVersionLockedLPr(callingUid)
12235                        < Build.VERSION_CODES.FROYO) {
12236                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
12237                            + callingUid);
12238                    return;
12239                }
12240                mContext.enforceCallingOrSelfPermission(
12241                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12242            }
12243
12244            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
12245            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
12246                    + userId + ":");
12247            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12248            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
12249            scheduleWritePackageRestrictionsLocked(userId);
12250        }
12251    }
12252
12253    @Override
12254    public void replacePreferredActivity(IntentFilter filter, int match,
12255            ComponentName[] set, ComponentName activity, int userId) {
12256        if (filter.countActions() != 1) {
12257            throw new IllegalArgumentException(
12258                    "replacePreferredActivity expects filter to have only 1 action.");
12259        }
12260        if (filter.countDataAuthorities() != 0
12261                || filter.countDataPaths() != 0
12262                || filter.countDataSchemes() > 1
12263                || filter.countDataTypes() != 0) {
12264            throw new IllegalArgumentException(
12265                    "replacePreferredActivity expects filter to have no data authorities, " +
12266                    "paths, or types; and at most one scheme.");
12267        }
12268
12269        final int callingUid = Binder.getCallingUid();
12270        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
12271        synchronized (mPackages) {
12272            if (mContext.checkCallingOrSelfPermission(
12273                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12274                    != PackageManager.PERMISSION_GRANTED) {
12275                if (getUidTargetSdkVersionLockedLPr(callingUid)
12276                        < Build.VERSION_CODES.FROYO) {
12277                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
12278                            + Binder.getCallingUid());
12279                    return;
12280                }
12281                mContext.enforceCallingOrSelfPermission(
12282                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12283            }
12284
12285            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12286            if (pir != null) {
12287                // Get all of the existing entries that exactly match this filter.
12288                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
12289                if (existing != null && existing.size() == 1) {
12290                    PreferredActivity cur = existing.get(0);
12291                    if (DEBUG_PREFERRED) {
12292                        Slog.i(TAG, "Checking replace of preferred:");
12293                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12294                        if (!cur.mPref.mAlways) {
12295                            Slog.i(TAG, "  -- CUR; not mAlways!");
12296                        } else {
12297                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
12298                            Slog.i(TAG, "  -- CUR: mSet="
12299                                    + Arrays.toString(cur.mPref.mSetComponents));
12300                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
12301                            Slog.i(TAG, "  -- NEW: mMatch="
12302                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
12303                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
12304                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
12305                        }
12306                    }
12307                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
12308                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
12309                            && cur.mPref.sameSet(set)) {
12310                        // Setting the preferred activity to what it happens to be already
12311                        if (DEBUG_PREFERRED) {
12312                            Slog.i(TAG, "Replacing with same preferred activity "
12313                                    + cur.mPref.mShortComponent + " for user "
12314                                    + userId + ":");
12315                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12316                        }
12317                        return;
12318                    }
12319                }
12320
12321                if (existing != null) {
12322                    if (DEBUG_PREFERRED) {
12323                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
12324                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12325                    }
12326                    for (int i = 0; i < existing.size(); i++) {
12327                        PreferredActivity pa = existing.get(i);
12328                        if (DEBUG_PREFERRED) {
12329                            Slog.i(TAG, "Removing existing preferred activity "
12330                                    + pa.mPref.mComponent + ":");
12331                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
12332                        }
12333                        pir.removeFilter(pa);
12334                    }
12335                }
12336            }
12337            addPreferredActivityInternal(filter, match, set, activity, true, userId,
12338                    "Replacing preferred");
12339        }
12340    }
12341
12342    @Override
12343    public void clearPackagePreferredActivities(String packageName) {
12344        final int uid = Binder.getCallingUid();
12345        // writer
12346        synchronized (mPackages) {
12347            PackageParser.Package pkg = mPackages.get(packageName);
12348            if (pkg == null || pkg.applicationInfo.uid != uid) {
12349                if (mContext.checkCallingOrSelfPermission(
12350                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
12351                        != PackageManager.PERMISSION_GRANTED) {
12352                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
12353                            < Build.VERSION_CODES.FROYO) {
12354                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
12355                                + Binder.getCallingUid());
12356                        return;
12357                    }
12358                    mContext.enforceCallingOrSelfPermission(
12359                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12360                }
12361            }
12362
12363            int user = UserHandle.getCallingUserId();
12364            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
12365                scheduleWritePackageRestrictionsLocked(user);
12366            }
12367        }
12368    }
12369
12370    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12371    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
12372        ArrayList<PreferredActivity> removed = null;
12373        boolean changed = false;
12374        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12375            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
12376            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12377            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
12378                continue;
12379            }
12380            Iterator<PreferredActivity> it = pir.filterIterator();
12381            while (it.hasNext()) {
12382                PreferredActivity pa = it.next();
12383                // Mark entry for removal only if it matches the package name
12384                // and the entry is of type "always".
12385                if (packageName == null ||
12386                        (pa.mPref.mComponent.getPackageName().equals(packageName)
12387                                && pa.mPref.mAlways)) {
12388                    if (removed == null) {
12389                        removed = new ArrayList<PreferredActivity>();
12390                    }
12391                    removed.add(pa);
12392                }
12393            }
12394            if (removed != null) {
12395                for (int j=0; j<removed.size(); j++) {
12396                    PreferredActivity pa = removed.get(j);
12397                    pir.removeFilter(pa);
12398                }
12399                changed = true;
12400            }
12401        }
12402        return changed;
12403    }
12404
12405    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
12406    void clearIntentFilterVerificationsLPw(String packageName, int userId) {
12407        if (userId == UserHandle.USER_ALL) {
12408            mSettings.removeIntentFilterVerificationLPw(packageName, sUserManager.getUserIds());
12409            for (int oneUserId : sUserManager.getUserIds()) {
12410                scheduleWritePackageRestrictionsLocked(oneUserId);
12411            }
12412        } else {
12413            mSettings.removeIntentFilterVerificationLPw(packageName, userId);
12414            scheduleWritePackageRestrictionsLocked(userId);
12415        }
12416    }
12417
12418    @Override
12419    public void resetPreferredActivities(int userId) {
12420        /* TODO: Actually use userId. Why is it being passed in? */
12421        mContext.enforceCallingOrSelfPermission(
12422                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
12423        // writer
12424        synchronized (mPackages) {
12425            int user = UserHandle.getCallingUserId();
12426            clearPackagePreferredActivitiesLPw(null, user);
12427            mSettings.readDefaultPreferredAppsLPw(this, user);
12428            scheduleWritePackageRestrictionsLocked(user);
12429        }
12430    }
12431
12432    @Override
12433    public int getPreferredActivities(List<IntentFilter> outFilters,
12434            List<ComponentName> outActivities, String packageName) {
12435
12436        int num = 0;
12437        final int userId = UserHandle.getCallingUserId();
12438        // reader
12439        synchronized (mPackages) {
12440            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
12441            if (pir != null) {
12442                final Iterator<PreferredActivity> it = pir.filterIterator();
12443                while (it.hasNext()) {
12444                    final PreferredActivity pa = it.next();
12445                    if (packageName == null
12446                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
12447                                    && pa.mPref.mAlways)) {
12448                        if (outFilters != null) {
12449                            outFilters.add(new IntentFilter(pa));
12450                        }
12451                        if (outActivities != null) {
12452                            outActivities.add(pa.mPref.mComponent);
12453                        }
12454                    }
12455                }
12456            }
12457        }
12458
12459        return num;
12460    }
12461
12462    @Override
12463    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
12464            int userId) {
12465        int callingUid = Binder.getCallingUid();
12466        if (callingUid != Process.SYSTEM_UID) {
12467            throw new SecurityException(
12468                    "addPersistentPreferredActivity can only be run by the system");
12469        }
12470        if (filter.countActions() == 0) {
12471            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
12472            return;
12473        }
12474        synchronized (mPackages) {
12475            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
12476                    " :");
12477            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
12478            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
12479                    new PersistentPreferredActivity(filter, activity));
12480            scheduleWritePackageRestrictionsLocked(userId);
12481        }
12482    }
12483
12484    @Override
12485    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
12486        int callingUid = Binder.getCallingUid();
12487        if (callingUid != Process.SYSTEM_UID) {
12488            throw new SecurityException(
12489                    "clearPackagePersistentPreferredActivities can only be run by the system");
12490        }
12491        ArrayList<PersistentPreferredActivity> removed = null;
12492        boolean changed = false;
12493        synchronized (mPackages) {
12494            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
12495                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
12496                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
12497                        .valueAt(i);
12498                if (userId != thisUserId) {
12499                    continue;
12500                }
12501                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
12502                while (it.hasNext()) {
12503                    PersistentPreferredActivity ppa = it.next();
12504                    // Mark entry for removal only if it matches the package name.
12505                    if (ppa.mComponent.getPackageName().equals(packageName)) {
12506                        if (removed == null) {
12507                            removed = new ArrayList<PersistentPreferredActivity>();
12508                        }
12509                        removed.add(ppa);
12510                    }
12511                }
12512                if (removed != null) {
12513                    for (int j=0; j<removed.size(); j++) {
12514                        PersistentPreferredActivity ppa = removed.get(j);
12515                        ppir.removeFilter(ppa);
12516                    }
12517                    changed = true;
12518                }
12519            }
12520
12521            if (changed) {
12522                scheduleWritePackageRestrictionsLocked(userId);
12523            }
12524        }
12525    }
12526
12527    @Override
12528    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
12529            int sourceUserId, int targetUserId, int flags) {
12530        mContext.enforceCallingOrSelfPermission(
12531                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12532        int callingUid = Binder.getCallingUid();
12533        enforceOwnerRights(ownerPackage, callingUid);
12534        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12535        if (intentFilter.countActions() == 0) {
12536            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
12537            return;
12538        }
12539        synchronized (mPackages) {
12540            CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter,
12541                    ownerPackage, targetUserId, flags);
12542            CrossProfileIntentResolver resolver =
12543                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12544            ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter);
12545            // We have all those whose filter is equal. Now checking if the rest is equal as well.
12546            if (existing != null) {
12547                int size = existing.size();
12548                for (int i = 0; i < size; i++) {
12549                    if (newFilter.equalsIgnoreFilter(existing.get(i))) {
12550                        return;
12551                    }
12552                }
12553            }
12554            resolver.addFilter(newFilter);
12555            scheduleWritePackageRestrictionsLocked(sourceUserId);
12556        }
12557    }
12558
12559    @Override
12560    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) {
12561        mContext.enforceCallingOrSelfPermission(
12562                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
12563        int callingUid = Binder.getCallingUid();
12564        enforceOwnerRights(ownerPackage, callingUid);
12565        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
12566        synchronized (mPackages) {
12567            CrossProfileIntentResolver resolver =
12568                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
12569            ArraySet<CrossProfileIntentFilter> set =
12570                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
12571            for (CrossProfileIntentFilter filter : set) {
12572                if (filter.getOwnerPackage().equals(ownerPackage)) {
12573                    resolver.removeFilter(filter);
12574                }
12575            }
12576            scheduleWritePackageRestrictionsLocked(sourceUserId);
12577        }
12578    }
12579
12580    // Enforcing that callingUid is owning pkg on userId
12581    private void enforceOwnerRights(String pkg, int callingUid) {
12582        // The system owns everything.
12583        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
12584            return;
12585        }
12586        int callingUserId = UserHandle.getUserId(callingUid);
12587        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
12588        if (pi == null) {
12589            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
12590                    + callingUserId);
12591        }
12592        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
12593            throw new SecurityException("Calling uid " + callingUid
12594                    + " does not own package " + pkg);
12595        }
12596    }
12597
12598    @Override
12599    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
12600        Intent intent = new Intent(Intent.ACTION_MAIN);
12601        intent.addCategory(Intent.CATEGORY_HOME);
12602
12603        final int callingUserId = UserHandle.getCallingUserId();
12604        List<ResolveInfo> list = queryIntentActivities(intent, null,
12605                PackageManager.GET_META_DATA, callingUserId);
12606        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
12607                true, false, false, callingUserId);
12608
12609        allHomeCandidates.clear();
12610        if (list != null) {
12611            for (ResolveInfo ri : list) {
12612                allHomeCandidates.add(ri);
12613            }
12614        }
12615        return (preferred == null || preferred.activityInfo == null)
12616                ? null
12617                : new ComponentName(preferred.activityInfo.packageName,
12618                        preferred.activityInfo.name);
12619    }
12620
12621    @Override
12622    public void setApplicationEnabledSetting(String appPackageName,
12623            int newState, int flags, int userId, String callingPackage) {
12624        if (!sUserManager.exists(userId)) return;
12625        if (callingPackage == null) {
12626            callingPackage = Integer.toString(Binder.getCallingUid());
12627        }
12628        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
12629    }
12630
12631    @Override
12632    public void setComponentEnabledSetting(ComponentName componentName,
12633            int newState, int flags, int userId) {
12634        if (!sUserManager.exists(userId)) return;
12635        setEnabledSetting(componentName.getPackageName(),
12636                componentName.getClassName(), newState, flags, userId, null);
12637    }
12638
12639    private void setEnabledSetting(final String packageName, String className, int newState,
12640            final int flags, int userId, String callingPackage) {
12641        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
12642              || newState == COMPONENT_ENABLED_STATE_ENABLED
12643              || newState == COMPONENT_ENABLED_STATE_DISABLED
12644              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
12645              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
12646            throw new IllegalArgumentException("Invalid new component state: "
12647                    + newState);
12648        }
12649        PackageSetting pkgSetting;
12650        final int uid = Binder.getCallingUid();
12651        final int permission = mContext.checkCallingOrSelfPermission(
12652                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12653        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
12654        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12655        boolean sendNow = false;
12656        boolean isApp = (className == null);
12657        String componentName = isApp ? packageName : className;
12658        int packageUid = -1;
12659        ArrayList<String> components;
12660
12661        // writer
12662        synchronized (mPackages) {
12663            pkgSetting = mSettings.mPackages.get(packageName);
12664            if (pkgSetting == null) {
12665                if (className == null) {
12666                    throw new IllegalArgumentException(
12667                            "Unknown package: " + packageName);
12668                }
12669                throw new IllegalArgumentException(
12670                        "Unknown component: " + packageName
12671                        + "/" + className);
12672            }
12673            // Allow root and verify that userId is not being specified by a different user
12674            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12675                throw new SecurityException(
12676                        "Permission Denial: attempt to change component state from pid="
12677                        + Binder.getCallingPid()
12678                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12679            }
12680            if (className == null) {
12681                // We're dealing with an application/package level state change
12682                if (pkgSetting.getEnabled(userId) == newState) {
12683                    // Nothing to do
12684                    return;
12685                }
12686                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12687                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12688                    // Don't care about who enables an app.
12689                    callingPackage = null;
12690                }
12691                pkgSetting.setEnabled(newState, userId, callingPackage);
12692                // pkgSetting.pkg.mSetEnabled = newState;
12693            } else {
12694                // We're dealing with a component level state change
12695                // First, verify that this is a valid class name.
12696                PackageParser.Package pkg = pkgSetting.pkg;
12697                if (pkg == null || !pkg.hasComponentClassName(className)) {
12698                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12699                        throw new IllegalArgumentException("Component class " + className
12700                                + " does not exist in " + packageName);
12701                    } else {
12702                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12703                                + className + " does not exist in " + packageName);
12704                    }
12705                }
12706                switch (newState) {
12707                case COMPONENT_ENABLED_STATE_ENABLED:
12708                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12709                        return;
12710                    }
12711                    break;
12712                case COMPONENT_ENABLED_STATE_DISABLED:
12713                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12714                        return;
12715                    }
12716                    break;
12717                case COMPONENT_ENABLED_STATE_DEFAULT:
12718                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12719                        return;
12720                    }
12721                    break;
12722                default:
12723                    Slog.e(TAG, "Invalid new component state: " + newState);
12724                    return;
12725                }
12726            }
12727            scheduleWritePackageRestrictionsLocked(userId);
12728            components = mPendingBroadcasts.get(userId, packageName);
12729            final boolean newPackage = components == null;
12730            if (newPackage) {
12731                components = new ArrayList<String>();
12732            }
12733            if (!components.contains(componentName)) {
12734                components.add(componentName);
12735            }
12736            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12737                sendNow = true;
12738                // Purge entry from pending broadcast list if another one exists already
12739                // since we are sending one right away.
12740                mPendingBroadcasts.remove(userId, packageName);
12741            } else {
12742                if (newPackage) {
12743                    mPendingBroadcasts.put(userId, packageName, components);
12744                }
12745                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12746                    // Schedule a message
12747                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12748                }
12749            }
12750        }
12751
12752        long callingId = Binder.clearCallingIdentity();
12753        try {
12754            if (sendNow) {
12755                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12756                sendPackageChangedBroadcast(packageName,
12757                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12758            }
12759        } finally {
12760            Binder.restoreCallingIdentity(callingId);
12761        }
12762    }
12763
12764    private void sendPackageChangedBroadcast(String packageName,
12765            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12766        if (DEBUG_INSTALL)
12767            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12768                    + componentNames);
12769        Bundle extras = new Bundle(4);
12770        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12771        String nameList[] = new String[componentNames.size()];
12772        componentNames.toArray(nameList);
12773        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12774        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12775        extras.putInt(Intent.EXTRA_UID, packageUid);
12776        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12777                new int[] {UserHandle.getUserId(packageUid)});
12778    }
12779
12780    @Override
12781    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12782        if (!sUserManager.exists(userId)) return;
12783        final int uid = Binder.getCallingUid();
12784        final int permission = mContext.checkCallingOrSelfPermission(
12785                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12786        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12787        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12788        // writer
12789        synchronized (mPackages) {
12790            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12791                    uid, userId)) {
12792                scheduleWritePackageRestrictionsLocked(userId);
12793            }
12794        }
12795    }
12796
12797    @Override
12798    public String getInstallerPackageName(String packageName) {
12799        // reader
12800        synchronized (mPackages) {
12801            return mSettings.getInstallerPackageNameLPr(packageName);
12802        }
12803    }
12804
12805    @Override
12806    public int getApplicationEnabledSetting(String packageName, int userId) {
12807        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12808        int uid = Binder.getCallingUid();
12809        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12810        // reader
12811        synchronized (mPackages) {
12812            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12813        }
12814    }
12815
12816    @Override
12817    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12818        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12819        int uid = Binder.getCallingUid();
12820        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12821        // reader
12822        synchronized (mPackages) {
12823            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12824        }
12825    }
12826
12827    @Override
12828    public void enterSafeMode() {
12829        enforceSystemOrRoot("Only the system can request entering safe mode");
12830
12831        if (!mSystemReady) {
12832            mSafeMode = true;
12833        }
12834    }
12835
12836    @Override
12837    public void systemReady() {
12838        mSystemReady = true;
12839
12840        // Read the compatibilty setting when the system is ready.
12841        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12842                mContext.getContentResolver(),
12843                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12844        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12845        if (DEBUG_SETTINGS) {
12846            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12847        }
12848
12849        synchronized (mPackages) {
12850            // Verify that all of the preferred activity components actually
12851            // exist.  It is possible for applications to be updated and at
12852            // that point remove a previously declared activity component that
12853            // had been set as a preferred activity.  We try to clean this up
12854            // the next time we encounter that preferred activity, but it is
12855            // possible for the user flow to never be able to return to that
12856            // situation so here we do a sanity check to make sure we haven't
12857            // left any junk around.
12858            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12859            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12860                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12861                removed.clear();
12862                for (PreferredActivity pa : pir.filterSet()) {
12863                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12864                        removed.add(pa);
12865                    }
12866                }
12867                if (removed.size() > 0) {
12868                    for (int r=0; r<removed.size(); r++) {
12869                        PreferredActivity pa = removed.get(r);
12870                        Slog.w(TAG, "Removing dangling preferred activity: "
12871                                + pa.mPref.mComponent);
12872                        pir.removeFilter(pa);
12873                    }
12874                    mSettings.writePackageRestrictionsLPr(
12875                            mSettings.mPreferredActivities.keyAt(i));
12876                }
12877            }
12878        }
12879        sUserManager.systemReady();
12880
12881        // Kick off any messages waiting for system ready
12882        if (mPostSystemReadyMessages != null) {
12883            for (Message msg : mPostSystemReadyMessages) {
12884                msg.sendToTarget();
12885            }
12886            mPostSystemReadyMessages = null;
12887        }
12888
12889        // Watch for external volumes that come and go over time
12890        final StorageManager storage = mContext.getSystemService(StorageManager.class);
12891        storage.registerListener(mStorageListener);
12892    }
12893
12894    @Override
12895    public boolean isSafeMode() {
12896        return mSafeMode;
12897    }
12898
12899    @Override
12900    public boolean hasSystemUidErrors() {
12901        return mHasSystemUidErrors;
12902    }
12903
12904    static String arrayToString(int[] array) {
12905        StringBuffer buf = new StringBuffer(128);
12906        buf.append('[');
12907        if (array != null) {
12908            for (int i=0; i<array.length; i++) {
12909                if (i > 0) buf.append(", ");
12910                buf.append(array[i]);
12911            }
12912        }
12913        buf.append(']');
12914        return buf.toString();
12915    }
12916
12917    static class DumpState {
12918        public static final int DUMP_LIBS = 1 << 0;
12919        public static final int DUMP_FEATURES = 1 << 1;
12920        public static final int DUMP_RESOLVERS = 1 << 2;
12921        public static final int DUMP_PERMISSIONS = 1 << 3;
12922        public static final int DUMP_PACKAGES = 1 << 4;
12923        public static final int DUMP_SHARED_USERS = 1 << 5;
12924        public static final int DUMP_MESSAGES = 1 << 6;
12925        public static final int DUMP_PROVIDERS = 1 << 7;
12926        public static final int DUMP_VERIFIERS = 1 << 8;
12927        public static final int DUMP_PREFERRED = 1 << 9;
12928        public static final int DUMP_PREFERRED_XML = 1 << 10;
12929        public static final int DUMP_KEYSETS = 1 << 11;
12930        public static final int DUMP_VERSION = 1 << 12;
12931        public static final int DUMP_INSTALLS = 1 << 13;
12932        public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 14;
12933        public static final int DUMP_DOMAIN_PREFERRED = 1 << 15;
12934
12935        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12936
12937        private int mTypes;
12938
12939        private int mOptions;
12940
12941        private boolean mTitlePrinted;
12942
12943        private SharedUserSetting mSharedUser;
12944
12945        public boolean isDumping(int type) {
12946            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12947                return true;
12948            }
12949
12950            return (mTypes & type) != 0;
12951        }
12952
12953        public void setDump(int type) {
12954            mTypes |= type;
12955        }
12956
12957        public boolean isOptionEnabled(int option) {
12958            return (mOptions & option) != 0;
12959        }
12960
12961        public void setOptionEnabled(int option) {
12962            mOptions |= option;
12963        }
12964
12965        public boolean onTitlePrinted() {
12966            final boolean printed = mTitlePrinted;
12967            mTitlePrinted = true;
12968            return printed;
12969        }
12970
12971        public boolean getTitlePrinted() {
12972            return mTitlePrinted;
12973        }
12974
12975        public void setTitlePrinted(boolean enabled) {
12976            mTitlePrinted = enabled;
12977        }
12978
12979        public SharedUserSetting getSharedUser() {
12980            return mSharedUser;
12981        }
12982
12983        public void setSharedUser(SharedUserSetting user) {
12984            mSharedUser = user;
12985        }
12986    }
12987
12988    @Override
12989    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12990        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12991                != PackageManager.PERMISSION_GRANTED) {
12992            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12993                    + Binder.getCallingPid()
12994                    + ", uid=" + Binder.getCallingUid()
12995                    + " without permission "
12996                    + android.Manifest.permission.DUMP);
12997            return;
12998        }
12999
13000        DumpState dumpState = new DumpState();
13001        boolean fullPreferred = false;
13002        boolean checkin = false;
13003
13004        String packageName = null;
13005
13006        int opti = 0;
13007        while (opti < args.length) {
13008            String opt = args[opti];
13009            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
13010                break;
13011            }
13012            opti++;
13013
13014            if ("-a".equals(opt)) {
13015                // Right now we only know how to print all.
13016            } else if ("-h".equals(opt)) {
13017                pw.println("Package manager dump options:");
13018                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
13019                pw.println("    --checkin: dump for a checkin");
13020                pw.println("    -f: print details of intent filters");
13021                pw.println("    -h: print this help");
13022                pw.println("  cmd may be one of:");
13023                pw.println("    l[ibraries]: list known shared libraries");
13024                pw.println("    f[ibraries]: list device features");
13025                pw.println("    k[eysets]: print known keysets");
13026                pw.println("    r[esolvers]: dump intent resolvers");
13027                pw.println("    perm[issions]: dump permissions");
13028                pw.println("    pref[erred]: print preferred package settings");
13029                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
13030                pw.println("    prov[iders]: dump content providers");
13031                pw.println("    p[ackages]: dump installed packages");
13032                pw.println("    s[hared-users]: dump shared user IDs");
13033                pw.println("    m[essages]: print collected runtime messages");
13034                pw.println("    v[erifiers]: print package verifier info");
13035                pw.println("    version: print database version info");
13036                pw.println("    write: write current settings now");
13037                pw.println("    <package.name>: info about given package");
13038                pw.println("    installs: details about install sessions");
13039                pw.println("    d[omain-preferred-apps]: print domains preferred apps");
13040                pw.println("    i[ntent-filter-verifiers]|ifv: print intent filter verifier info");
13041                return;
13042            } else if ("--checkin".equals(opt)) {
13043                checkin = true;
13044            } else if ("-f".equals(opt)) {
13045                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13046            } else {
13047                pw.println("Unknown argument: " + opt + "; use -h for help");
13048            }
13049        }
13050
13051        // Is the caller requesting to dump a particular piece of data?
13052        if (opti < args.length) {
13053            String cmd = args[opti];
13054            opti++;
13055            // Is this a package name?
13056            if ("android".equals(cmd) || cmd.contains(".")) {
13057                packageName = cmd;
13058                // When dumping a single package, we always dump all of its
13059                // filter information since the amount of data will be reasonable.
13060                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
13061            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
13062                dumpState.setDump(DumpState.DUMP_LIBS);
13063            } else if ("f".equals(cmd) || "features".equals(cmd)) {
13064                dumpState.setDump(DumpState.DUMP_FEATURES);
13065            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
13066                dumpState.setDump(DumpState.DUMP_RESOLVERS);
13067            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
13068                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
13069            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
13070                dumpState.setDump(DumpState.DUMP_PREFERRED);
13071            } else if ("preferred-xml".equals(cmd)) {
13072                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
13073                if (opti < args.length && "--full".equals(args[opti])) {
13074                    fullPreferred = true;
13075                    opti++;
13076                }
13077            } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) {
13078                dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED);
13079            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
13080                dumpState.setDump(DumpState.DUMP_PACKAGES);
13081            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
13082                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
13083            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
13084                dumpState.setDump(DumpState.DUMP_PROVIDERS);
13085            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
13086                dumpState.setDump(DumpState.DUMP_MESSAGES);
13087            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
13088                dumpState.setDump(DumpState.DUMP_VERIFIERS);
13089            } else if ("i".equals(cmd) || "ifv".equals(cmd)
13090                    || "intent-filter-verifiers".equals(cmd)) {
13091                dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS);
13092            } else if ("version".equals(cmd)) {
13093                dumpState.setDump(DumpState.DUMP_VERSION);
13094            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
13095                dumpState.setDump(DumpState.DUMP_KEYSETS);
13096            } else if ("installs".equals(cmd)) {
13097                dumpState.setDump(DumpState.DUMP_INSTALLS);
13098            } else if ("write".equals(cmd)) {
13099                synchronized (mPackages) {
13100                    mSettings.writeLPr();
13101                    pw.println("Settings written.");
13102                    return;
13103                }
13104            }
13105        }
13106
13107        if (checkin) {
13108            pw.println("vers,1");
13109        }
13110
13111        // reader
13112        synchronized (mPackages) {
13113            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
13114                if (!checkin) {
13115                    if (dumpState.onTitlePrinted())
13116                        pw.println();
13117                    pw.println("Database versions:");
13118                    pw.print("  SDK Version:");
13119                    pw.print(" internal=");
13120                    pw.print(mSettings.mInternalSdkPlatform);
13121                    pw.print(" external=");
13122                    pw.println(mSettings.mExternalSdkPlatform);
13123                    pw.print("  DB Version:");
13124                    pw.print(" internal=");
13125                    pw.print(mSettings.mInternalDatabaseVersion);
13126                    pw.print(" external=");
13127                    pw.println(mSettings.mExternalDatabaseVersion);
13128                }
13129            }
13130
13131            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
13132                if (!checkin) {
13133                    if (dumpState.onTitlePrinted())
13134                        pw.println();
13135                    pw.println("Verifiers:");
13136                    pw.print("  Required: ");
13137                    pw.print(mRequiredVerifierPackage);
13138                    pw.print(" (uid=");
13139                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
13140                    pw.println(")");
13141                } else if (mRequiredVerifierPackage != null) {
13142                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
13143                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
13144                }
13145            }
13146
13147            if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) &&
13148                    packageName == null) {
13149                if (mIntentFilterVerifierComponent != null) {
13150                    String verifierPackageName = mIntentFilterVerifierComponent.getPackageName();
13151                    if (!checkin) {
13152                        if (dumpState.onTitlePrinted())
13153                            pw.println();
13154                        pw.println("Intent Filter Verifier:");
13155                        pw.print("  Using: ");
13156                        pw.print(verifierPackageName);
13157                        pw.print(" (uid=");
13158                        pw.print(getPackageUid(verifierPackageName, 0));
13159                        pw.println(")");
13160                    } else if (verifierPackageName != null) {
13161                        pw.print("ifv,"); pw.print(verifierPackageName);
13162                        pw.print(","); pw.println(getPackageUid(verifierPackageName, 0));
13163                    }
13164                } else {
13165                    pw.println();
13166                    pw.println("No Intent Filter Verifier available!");
13167                }
13168            }
13169
13170            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
13171                boolean printedHeader = false;
13172                final Iterator<String> it = mSharedLibraries.keySet().iterator();
13173                while (it.hasNext()) {
13174                    String name = it.next();
13175                    SharedLibraryEntry ent = mSharedLibraries.get(name);
13176                    if (!checkin) {
13177                        if (!printedHeader) {
13178                            if (dumpState.onTitlePrinted())
13179                                pw.println();
13180                            pw.println("Libraries:");
13181                            printedHeader = true;
13182                        }
13183                        pw.print("  ");
13184                    } else {
13185                        pw.print("lib,");
13186                    }
13187                    pw.print(name);
13188                    if (!checkin) {
13189                        pw.print(" -> ");
13190                    }
13191                    if (ent.path != null) {
13192                        if (!checkin) {
13193                            pw.print("(jar) ");
13194                            pw.print(ent.path);
13195                        } else {
13196                            pw.print(",jar,");
13197                            pw.print(ent.path);
13198                        }
13199                    } else {
13200                        if (!checkin) {
13201                            pw.print("(apk) ");
13202                            pw.print(ent.apk);
13203                        } else {
13204                            pw.print(",apk,");
13205                            pw.print(ent.apk);
13206                        }
13207                    }
13208                    pw.println();
13209                }
13210            }
13211
13212            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
13213                if (dumpState.onTitlePrinted())
13214                    pw.println();
13215                if (!checkin) {
13216                    pw.println("Features:");
13217                }
13218                Iterator<String> it = mAvailableFeatures.keySet().iterator();
13219                while (it.hasNext()) {
13220                    String name = it.next();
13221                    if (!checkin) {
13222                        pw.print("  ");
13223                    } else {
13224                        pw.print("feat,");
13225                    }
13226                    pw.println(name);
13227                }
13228            }
13229
13230            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
13231                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
13232                        : "Activity Resolver Table:", "  ", packageName,
13233                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13234                    dumpState.setTitlePrinted(true);
13235                }
13236                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
13237                        : "Receiver Resolver Table:", "  ", packageName,
13238                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13239                    dumpState.setTitlePrinted(true);
13240                }
13241                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
13242                        : "Service Resolver Table:", "  ", packageName,
13243                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13244                    dumpState.setTitlePrinted(true);
13245                }
13246                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
13247                        : "Provider Resolver Table:", "  ", packageName,
13248                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) {
13249                    dumpState.setTitlePrinted(true);
13250                }
13251            }
13252
13253            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
13254                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
13255                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
13256                    int user = mSettings.mPreferredActivities.keyAt(i);
13257                    if (pir.dump(pw,
13258                            dumpState.getTitlePrinted()
13259                                ? "\nPreferred Activities User " + user + ":"
13260                                : "Preferred Activities User " + user + ":", "  ",
13261                            packageName, true, false)) {
13262                        dumpState.setTitlePrinted(true);
13263                    }
13264                }
13265            }
13266
13267            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
13268                pw.flush();
13269                FileOutputStream fout = new FileOutputStream(fd);
13270                BufferedOutputStream str = new BufferedOutputStream(fout);
13271                XmlSerializer serializer = new FastXmlSerializer();
13272                try {
13273                    serializer.setOutput(str, "utf-8");
13274                    serializer.startDocument(null, true);
13275                    serializer.setFeature(
13276                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
13277                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
13278                    serializer.endDocument();
13279                    serializer.flush();
13280                } catch (IllegalArgumentException e) {
13281                    pw.println("Failed writing: " + e);
13282                } catch (IllegalStateException e) {
13283                    pw.println("Failed writing: " + e);
13284                } catch (IOException e) {
13285                    pw.println("Failed writing: " + e);
13286                }
13287            }
13288
13289            if (!checkin && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED)) {
13290                pw.println();
13291                int count = mSettings.mPackages.size();
13292                if (count == 0) {
13293                    pw.println("No domain preferred apps!");
13294                    pw.println();
13295                } else {
13296                    final String prefix = "  ";
13297                    Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values();
13298                    if (allPackageSettings.size() == 0) {
13299                        pw.println("No domain preferred apps!");
13300                        pw.println();
13301                    } else {
13302                        pw.println("Domain preferred apps status:");
13303                        pw.println();
13304                        count = 0;
13305                        for (PackageSetting ps : allPackageSettings) {
13306                            IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13307                            if (ivi == null || ivi.getPackageName() == null) continue;
13308                            pw.println(prefix + "Package Name: " + ivi.getPackageName());
13309                            pw.println(prefix + "Domains: " + ivi.getDomainsString());
13310                            pw.println(prefix + "Status: " + ivi.getStatusString());
13311                            pw.println();
13312                            count++;
13313                        }
13314                        if (count == 0) {
13315                            pw.println(prefix + "No domain preferred app status!");
13316                            pw.println();
13317                        }
13318                        for (int userId : sUserManager.getUserIds()) {
13319                            pw.println("Domain preferred apps for User " + userId + ":");
13320                            pw.println();
13321                            count = 0;
13322                            for (PackageSetting ps : allPackageSettings) {
13323                                IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo();
13324                                if (ivi == null || ivi.getPackageName() == null) {
13325                                    continue;
13326                                }
13327                                final int status = ps.getDomainVerificationStatusForUser(userId);
13328                                if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) {
13329                                    continue;
13330                                }
13331                                pw.println(prefix + "Package Name: " + ivi.getPackageName());
13332                                pw.println(prefix + "Domains: " + ivi.getDomainsString());
13333                                String statusStr = IntentFilterVerificationInfo.
13334                                        getStatusStringFromValue(status);
13335                                pw.println(prefix + "Status: " + statusStr);
13336                                pw.println();
13337                                count++;
13338                            }
13339                            if (count == 0) {
13340                                pw.println(prefix + "No domain preferred apps!");
13341                                pw.println();
13342                            }
13343                        }
13344                    }
13345                }
13346            }
13347
13348            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
13349                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
13350                if (packageName == null) {
13351                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
13352                        if (iperm == 0) {
13353                            if (dumpState.onTitlePrinted())
13354                                pw.println();
13355                            pw.println("AppOp Permissions:");
13356                        }
13357                        pw.print("  AppOp Permission ");
13358                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
13359                        pw.println(":");
13360                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
13361                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
13362                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
13363                        }
13364                    }
13365                }
13366            }
13367
13368            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
13369                boolean printedSomething = false;
13370                for (PackageParser.Provider p : mProviders.mProviders.values()) {
13371                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13372                        continue;
13373                    }
13374                    if (!printedSomething) {
13375                        if (dumpState.onTitlePrinted())
13376                            pw.println();
13377                        pw.println("Registered ContentProviders:");
13378                        printedSomething = true;
13379                    }
13380                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
13381                    pw.print("    "); pw.println(p.toString());
13382                }
13383                printedSomething = false;
13384                for (Map.Entry<String, PackageParser.Provider> entry :
13385                        mProvidersByAuthority.entrySet()) {
13386                    PackageParser.Provider p = entry.getValue();
13387                    if (packageName != null && !packageName.equals(p.info.packageName)) {
13388                        continue;
13389                    }
13390                    if (!printedSomething) {
13391                        if (dumpState.onTitlePrinted())
13392                            pw.println();
13393                        pw.println("ContentProvider Authorities:");
13394                        printedSomething = true;
13395                    }
13396                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
13397                    pw.print("    "); pw.println(p.toString());
13398                    if (p.info != null && p.info.applicationInfo != null) {
13399                        final String appInfo = p.info.applicationInfo.toString();
13400                        pw.print("      applicationInfo="); pw.println(appInfo);
13401                    }
13402                }
13403            }
13404
13405            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
13406                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
13407            }
13408
13409            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
13410                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
13411            }
13412
13413            if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
13414                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState, checkin);
13415            }
13416
13417            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
13418                // XXX should handle packageName != null by dumping only install data that
13419                // the given package is involved with.
13420                if (dumpState.onTitlePrinted()) pw.println();
13421                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
13422            }
13423
13424            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
13425                if (dumpState.onTitlePrinted()) pw.println();
13426                mSettings.dumpReadMessagesLPr(pw, dumpState);
13427
13428                pw.println();
13429                pw.println("Package warning messages:");
13430                BufferedReader in = null;
13431                String line = null;
13432                try {
13433                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13434                    while ((line = in.readLine()) != null) {
13435                        if (line.contains("ignored: updated version")) continue;
13436                        pw.println(line);
13437                    }
13438                } catch (IOException ignored) {
13439                } finally {
13440                    IoUtils.closeQuietly(in);
13441                }
13442            }
13443
13444            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
13445                BufferedReader in = null;
13446                String line = null;
13447                try {
13448                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
13449                    while ((line = in.readLine()) != null) {
13450                        if (line.contains("ignored: updated version")) continue;
13451                        pw.print("msg,");
13452                        pw.println(line);
13453                    }
13454                } catch (IOException ignored) {
13455                } finally {
13456                    IoUtils.closeQuietly(in);
13457                }
13458            }
13459        }
13460    }
13461
13462    // ------- apps on sdcard specific code -------
13463    static final boolean DEBUG_SD_INSTALL = false;
13464
13465    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
13466
13467    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
13468
13469    private boolean mMediaMounted = false;
13470
13471    static String getEncryptKey() {
13472        try {
13473            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
13474                    SD_ENCRYPTION_KEYSTORE_NAME);
13475            if (sdEncKey == null) {
13476                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
13477                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
13478                if (sdEncKey == null) {
13479                    Slog.e(TAG, "Failed to create encryption keys");
13480                    return null;
13481                }
13482            }
13483            return sdEncKey;
13484        } catch (NoSuchAlgorithmException nsae) {
13485            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
13486            return null;
13487        } catch (IOException ioe) {
13488            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
13489            return null;
13490        }
13491    }
13492
13493    /*
13494     * Update media status on PackageManager.
13495     */
13496    @Override
13497    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
13498        int callingUid = Binder.getCallingUid();
13499        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
13500            throw new SecurityException("Media status can only be updated by the system");
13501        }
13502        // reader; this apparently protects mMediaMounted, but should probably
13503        // be a different lock in that case.
13504        synchronized (mPackages) {
13505            Log.i(TAG, "Updating external media status from "
13506                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
13507                    + (mediaStatus ? "mounted" : "unmounted"));
13508            if (DEBUG_SD_INSTALL)
13509                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
13510                        + ", mMediaMounted=" + mMediaMounted);
13511            if (mediaStatus == mMediaMounted) {
13512                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
13513                        : 0, -1);
13514                mHandler.sendMessage(msg);
13515                return;
13516            }
13517            mMediaMounted = mediaStatus;
13518        }
13519        // Queue up an async operation since the package installation may take a
13520        // little while.
13521        mHandler.post(new Runnable() {
13522            public void run() {
13523                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
13524            }
13525        });
13526    }
13527
13528    /**
13529     * Called by MountService when the initial ASECs to scan are available.
13530     * Should block until all the ASEC containers are finished being scanned.
13531     */
13532    public void scanAvailableAsecs() {
13533        updateExternalMediaStatusInner(true, false, false);
13534        if (mShouldRestoreconData) {
13535            SELinuxMMAC.setRestoreconDone();
13536            mShouldRestoreconData = false;
13537        }
13538    }
13539
13540    /*
13541     * Collect information of applications on external media, map them against
13542     * existing containers and update information based on current mount status.
13543     * Please note that we always have to report status if reportStatus has been
13544     * set to true especially when unloading packages.
13545     */
13546    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
13547            boolean externalStorage) {
13548        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
13549        int[] uidArr = EmptyArray.INT;
13550
13551        final String[] list = PackageHelper.getSecureContainerList();
13552        if (ArrayUtils.isEmpty(list)) {
13553            Log.i(TAG, "No secure containers found");
13554        } else {
13555            // Process list of secure containers and categorize them
13556            // as active or stale based on their package internal state.
13557
13558            // reader
13559            synchronized (mPackages) {
13560                for (String cid : list) {
13561                    // Leave stages untouched for now; installer service owns them
13562                    if (PackageInstallerService.isStageName(cid)) continue;
13563
13564                    if (DEBUG_SD_INSTALL)
13565                        Log.i(TAG, "Processing container " + cid);
13566                    String pkgName = getAsecPackageName(cid);
13567                    if (pkgName == null) {
13568                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
13569                        continue;
13570                    }
13571                    if (DEBUG_SD_INSTALL)
13572                        Log.i(TAG, "Looking for pkg : " + pkgName);
13573
13574                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
13575                    if (ps == null) {
13576                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
13577                        continue;
13578                    }
13579
13580                    /*
13581                     * Skip packages that are not external if we're unmounting
13582                     * external storage.
13583                     */
13584                    if (externalStorage && !isMounted && !isExternal(ps)) {
13585                        continue;
13586                    }
13587
13588                    final AsecInstallArgs args = new AsecInstallArgs(cid,
13589                            getAppDexInstructionSets(ps), ps.isForwardLocked());
13590                    // The package status is changed only if the code path
13591                    // matches between settings and the container id.
13592                    if (ps.codePathString != null
13593                            && ps.codePathString.startsWith(args.getCodePath())) {
13594                        if (DEBUG_SD_INSTALL) {
13595                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
13596                                    + " at code path: " + ps.codePathString);
13597                        }
13598
13599                        // We do have a valid package installed on sdcard
13600                        processCids.put(args, ps.codePathString);
13601                        final int uid = ps.appId;
13602                        if (uid != -1) {
13603                            uidArr = ArrayUtils.appendInt(uidArr, uid);
13604                        }
13605                    } else {
13606                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
13607                                + ps.codePathString);
13608                    }
13609                }
13610            }
13611
13612            Arrays.sort(uidArr);
13613        }
13614
13615        // Process packages with valid entries.
13616        if (isMounted) {
13617            if (DEBUG_SD_INSTALL)
13618                Log.i(TAG, "Loading packages");
13619            loadMediaPackages(processCids, uidArr);
13620            startCleaningPackages();
13621            mInstallerService.onSecureContainersAvailable();
13622        } else {
13623            if (DEBUG_SD_INSTALL)
13624                Log.i(TAG, "Unloading packages");
13625            unloadMediaPackages(processCids, uidArr, reportStatus);
13626        }
13627    }
13628
13629    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
13630            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
13631        int size = pkgList.size();
13632        if (size > 0) {
13633            // Send broadcasts here
13634            Bundle extras = new Bundle();
13635            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
13636                    .toArray(new String[size]));
13637            if (uidArr != null) {
13638                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
13639            }
13640            if (replacing) {
13641                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
13642            }
13643            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
13644                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
13645            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
13646        }
13647    }
13648
13649   /*
13650     * Look at potentially valid container ids from processCids If package
13651     * information doesn't match the one on record or package scanning fails,
13652     * the cid is added to list of removeCids. We currently don't delete stale
13653     * containers.
13654     */
13655    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
13656        ArrayList<String> pkgList = new ArrayList<String>();
13657        Set<AsecInstallArgs> keys = processCids.keySet();
13658
13659        for (AsecInstallArgs args : keys) {
13660            String codePath = processCids.get(args);
13661            if (DEBUG_SD_INSTALL)
13662                Log.i(TAG, "Loading container : " + args.cid);
13663            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
13664            try {
13665                // Make sure there are no container errors first.
13666                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
13667                    Slog.e(TAG, "Failed to mount cid : " + args.cid
13668                            + " when installing from sdcard");
13669                    continue;
13670                }
13671                // Check code path here.
13672                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
13673                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
13674                            + " does not match one in settings " + codePath);
13675                    continue;
13676                }
13677                // Parse package
13678                int parseFlags = mDefParseFlags;
13679                if (args.isExternal()) {
13680                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
13681                }
13682                if (args.isFwdLocked()) {
13683                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
13684                }
13685
13686                synchronized (mInstallLock) {
13687                    PackageParser.Package pkg = null;
13688                    try {
13689                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
13690                    } catch (PackageManagerException e) {
13691                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
13692                    }
13693                    // Scan the package
13694                    if (pkg != null) {
13695                        /*
13696                         * TODO why is the lock being held? doPostInstall is
13697                         * called in other places without the lock. This needs
13698                         * to be straightened out.
13699                         */
13700                        // writer
13701                        synchronized (mPackages) {
13702                            retCode = PackageManager.INSTALL_SUCCEEDED;
13703                            pkgList.add(pkg.packageName);
13704                            // Post process args
13705                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
13706                                    pkg.applicationInfo.uid);
13707                        }
13708                    } else {
13709                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
13710                    }
13711                }
13712
13713            } finally {
13714                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
13715                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
13716                }
13717            }
13718        }
13719        // writer
13720        synchronized (mPackages) {
13721            // If the platform SDK has changed since the last time we booted,
13722            // we need to re-grant app permission to catch any new ones that
13723            // appear. This is really a hack, and means that apps can in some
13724            // cases get permissions that the user didn't initially explicitly
13725            // allow... it would be nice to have some better way to handle
13726            // this situation.
13727            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
13728            if (regrantPermissions)
13729                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
13730                        + mSdkVersion + "; regranting permissions for external storage");
13731            mSettings.mExternalSdkPlatform = mSdkVersion;
13732
13733            // Make sure group IDs have been assigned, and any permission
13734            // changes in other apps are accounted for
13735            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
13736                    | (regrantPermissions
13737                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
13738                            : 0));
13739
13740            mSettings.updateExternalDatabaseVersion();
13741
13742            // can downgrade to reader
13743            // Persist settings
13744            mSettings.writeLPr();
13745        }
13746        // Send a broadcast to let everyone know we are done processing
13747        if (pkgList.size() > 0) {
13748            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
13749        }
13750    }
13751
13752   /*
13753     * Utility method to unload a list of specified containers
13754     */
13755    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
13756        // Just unmount all valid containers.
13757        for (AsecInstallArgs arg : cidArgs) {
13758            synchronized (mInstallLock) {
13759                arg.doPostDeleteLI(false);
13760           }
13761       }
13762   }
13763
13764    /*
13765     * Unload packages mounted on external media. This involves deleting package
13766     * data from internal structures, sending broadcasts about diabled packages,
13767     * gc'ing to free up references, unmounting all secure containers
13768     * corresponding to packages on external media, and posting a
13769     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13770     * that we always have to post this message if status has been requested no
13771     * matter what.
13772     */
13773    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13774            final boolean reportStatus) {
13775        if (DEBUG_SD_INSTALL)
13776            Log.i(TAG, "unloading media packages");
13777        ArrayList<String> pkgList = new ArrayList<String>();
13778        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13779        final Set<AsecInstallArgs> keys = processCids.keySet();
13780        for (AsecInstallArgs args : keys) {
13781            String pkgName = args.getPackageName();
13782            if (DEBUG_SD_INSTALL)
13783                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13784            // Delete package internally
13785            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13786            synchronized (mInstallLock) {
13787                boolean res = deletePackageLI(pkgName, null, false, null, null,
13788                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13789                if (res) {
13790                    pkgList.add(pkgName);
13791                } else {
13792                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13793                    failedList.add(args);
13794                }
13795            }
13796        }
13797
13798        // reader
13799        synchronized (mPackages) {
13800            // We didn't update the settings after removing each package;
13801            // write them now for all packages.
13802            mSettings.writeLPr();
13803        }
13804
13805        // We have to absolutely send UPDATED_MEDIA_STATUS only
13806        // after confirming that all the receivers processed the ordered
13807        // broadcast when packages get disabled, force a gc to clean things up.
13808        // and unload all the containers.
13809        if (pkgList.size() > 0) {
13810            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13811                    new IIntentReceiver.Stub() {
13812                public void performReceive(Intent intent, int resultCode, String data,
13813                        Bundle extras, boolean ordered, boolean sticky,
13814                        int sendingUser) throws RemoteException {
13815                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13816                            reportStatus ? 1 : 0, 1, keys);
13817                    mHandler.sendMessage(msg);
13818                }
13819            });
13820        } else {
13821            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13822                    keys);
13823            mHandler.sendMessage(msg);
13824        }
13825    }
13826
13827    /** Binder call */
13828    @Override
13829    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13830            final int flags) {
13831        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13832        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13833        int returnCode = PackageManager.MOVE_SUCCEEDED;
13834        int currInstallFlags = 0;
13835        int newInstallFlags = 0;
13836
13837        File codeFile = null;
13838        String installerPackageName = null;
13839        String packageAbiOverride = null;
13840
13841        // reader
13842        synchronized (mPackages) {
13843            final PackageParser.Package pkg = mPackages.get(packageName);
13844            final PackageSetting ps = mSettings.mPackages.get(packageName);
13845            if (pkg == null || ps == null) {
13846                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13847            } else {
13848                // Disable moving fwd locked apps and system packages
13849                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13850                    Slog.w(TAG, "Cannot move system application");
13851                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13852                } else if (pkg.mOperationPending) {
13853                    Slog.w(TAG, "Attempt to move package which has pending operations");
13854                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13855                } else {
13856                    // Find install location first
13857                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13858                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13859                        Slog.w(TAG, "Ambigous flags specified for move location.");
13860                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13861                    } else {
13862                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13863                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13864                        currInstallFlags = isExternal(pkg)
13865                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13866
13867                        if (newInstallFlags == currInstallFlags) {
13868                            Slog.w(TAG, "No move required. Trying to move to same location");
13869                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13870                        } else {
13871                            if (pkg.isForwardLocked()) {
13872                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13873                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13874                            }
13875                        }
13876                    }
13877                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13878                        pkg.mOperationPending = true;
13879                    }
13880                }
13881
13882                codeFile = new File(pkg.codePath);
13883                installerPackageName = ps.installerPackageName;
13884                packageAbiOverride = ps.cpuAbiOverrideString;
13885            }
13886        }
13887
13888        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13889            try {
13890                observer.packageMoved(packageName, returnCode);
13891            } catch (RemoteException ignored) {
13892            }
13893            return;
13894        }
13895
13896        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13897            @Override
13898            public void onUserActionRequired(Intent intent) throws RemoteException {
13899                throw new IllegalStateException();
13900            }
13901
13902            @Override
13903            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13904                    Bundle extras) throws RemoteException {
13905                Slog.d(TAG, "Install result for move: "
13906                        + PackageManager.installStatusToString(returnCode, msg));
13907
13908                // We usually have a new package now after the install, but if
13909                // we failed we need to clear the pending flag on the original
13910                // package object.
13911                synchronized (mPackages) {
13912                    final PackageParser.Package pkg = mPackages.get(packageName);
13913                    if (pkg != null) {
13914                        pkg.mOperationPending = false;
13915                    }
13916                }
13917
13918                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13919                switch (status) {
13920                    case PackageInstaller.STATUS_SUCCESS:
13921                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13922                        break;
13923                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13924                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13925                        break;
13926                    default:
13927                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13928                        break;
13929                }
13930            }
13931        };
13932
13933        // Treat a move like reinstalling an existing app, which ensures that we
13934        // process everythign uniformly, like unpacking native libraries.
13935        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13936
13937        final Message msg = mHandler.obtainMessage(INIT_COPY);
13938        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13939        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13940                installerPackageName, null, user, packageAbiOverride);
13941        mHandler.sendMessage(msg);
13942    }
13943
13944    @Override
13945    public boolean setInstallLocation(int loc) {
13946        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13947                null);
13948        if (getInstallLocation() == loc) {
13949            return true;
13950        }
13951        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13952                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13953            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13954                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13955            return true;
13956        }
13957        return false;
13958   }
13959
13960    @Override
13961    public int getInstallLocation() {
13962        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13963                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13964                PackageHelper.APP_INSTALL_AUTO);
13965    }
13966
13967    /** Called by UserManagerService */
13968    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13969        mDirtyUsers.remove(userHandle);
13970        mSettings.removeUserLPw(userHandle);
13971        mPendingBroadcasts.remove(userHandle);
13972        if (mInstaller != null) {
13973            // Technically, we shouldn't be doing this with the package lock
13974            // held.  However, this is very rare, and there is already so much
13975            // other disk I/O going on, that we'll let it slide for now.
13976            mInstaller.removeUserDataDirs(userHandle);
13977        }
13978        mUserNeedsBadging.delete(userHandle);
13979        removeUnusedPackagesLILPw(userManager, userHandle);
13980    }
13981
13982    /**
13983     * We're removing userHandle and would like to remove any downloaded packages
13984     * that are no longer in use by any other user.
13985     * @param userHandle the user being removed
13986     */
13987    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13988        final boolean DEBUG_CLEAN_APKS = false;
13989        int [] users = userManager.getUserIdsLPr();
13990        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13991        while (psit.hasNext()) {
13992            PackageSetting ps = psit.next();
13993            if (ps.pkg == null) {
13994                continue;
13995            }
13996            final String packageName = ps.pkg.packageName;
13997            // Skip over if system app
13998            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13999                continue;
14000            }
14001            if (DEBUG_CLEAN_APKS) {
14002                Slog.i(TAG, "Checking package " + packageName);
14003            }
14004            boolean keep = false;
14005            for (int i = 0; i < users.length; i++) {
14006                if (users[i] != userHandle && ps.getInstalled(users[i])) {
14007                    keep = true;
14008                    if (DEBUG_CLEAN_APKS) {
14009                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
14010                                + users[i]);
14011                    }
14012                    break;
14013                }
14014            }
14015            if (!keep) {
14016                if (DEBUG_CLEAN_APKS) {
14017                    Slog.i(TAG, "  Removing package " + packageName);
14018                }
14019                mHandler.post(new Runnable() {
14020                    public void run() {
14021                        deletePackageX(packageName, userHandle, 0);
14022                    } //end run
14023                });
14024            }
14025        }
14026    }
14027
14028    /** Called by UserManagerService */
14029    void createNewUserLILPw(int userHandle, File path) {
14030        if (mInstaller != null) {
14031            mInstaller.createUserConfig(userHandle);
14032            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
14033        }
14034    }
14035
14036    void newUserCreatedLILPw(int userHandle) {
14037        // Adding a user requires updating runtime permissions for system apps.
14038        updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL);
14039    }
14040
14041    @Override
14042    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
14043        mContext.enforceCallingOrSelfPermission(
14044                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
14045                "Only package verification agents can read the verifier device identity");
14046
14047        synchronized (mPackages) {
14048            return mSettings.getVerifierDeviceIdentityLPw();
14049        }
14050    }
14051
14052    @Override
14053    public void setPermissionEnforced(String permission, boolean enforced) {
14054        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
14055        if (READ_EXTERNAL_STORAGE.equals(permission)) {
14056            synchronized (mPackages) {
14057                if (mSettings.mReadExternalStorageEnforced == null
14058                        || mSettings.mReadExternalStorageEnforced != enforced) {
14059                    mSettings.mReadExternalStorageEnforced = enforced;
14060                    mSettings.writeLPr();
14061                }
14062            }
14063            // kill any non-foreground processes so we restart them and
14064            // grant/revoke the GID.
14065            final IActivityManager am = ActivityManagerNative.getDefault();
14066            if (am != null) {
14067                final long token = Binder.clearCallingIdentity();
14068                try {
14069                    am.killProcessesBelowForeground("setPermissionEnforcement");
14070                } catch (RemoteException e) {
14071                } finally {
14072                    Binder.restoreCallingIdentity(token);
14073                }
14074            }
14075        } else {
14076            throw new IllegalArgumentException("No selective enforcement for " + permission);
14077        }
14078    }
14079
14080    @Override
14081    @Deprecated
14082    public boolean isPermissionEnforced(String permission) {
14083        return true;
14084    }
14085
14086    @Override
14087    public boolean isStorageLow() {
14088        final long token = Binder.clearCallingIdentity();
14089        try {
14090            final DeviceStorageMonitorInternal
14091                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
14092            if (dsm != null) {
14093                return dsm.isMemoryLow();
14094            } else {
14095                return false;
14096            }
14097        } finally {
14098            Binder.restoreCallingIdentity(token);
14099        }
14100    }
14101
14102    @Override
14103    public IPackageInstaller getPackageInstaller() {
14104        return mInstallerService;
14105    }
14106
14107    private boolean userNeedsBadging(int userId) {
14108        int index = mUserNeedsBadging.indexOfKey(userId);
14109        if (index < 0) {
14110            final UserInfo userInfo;
14111            final long token = Binder.clearCallingIdentity();
14112            try {
14113                userInfo = sUserManager.getUserInfo(userId);
14114            } finally {
14115                Binder.restoreCallingIdentity(token);
14116            }
14117            final boolean b;
14118            if (userInfo != null && userInfo.isManagedProfile()) {
14119                b = true;
14120            } else {
14121                b = false;
14122            }
14123            mUserNeedsBadging.put(userId, b);
14124            return b;
14125        }
14126        return mUserNeedsBadging.valueAt(index);
14127    }
14128
14129    @Override
14130    public KeySet getKeySetByAlias(String packageName, String alias) {
14131        if (packageName == null || alias == null) {
14132            return null;
14133        }
14134        synchronized(mPackages) {
14135            final PackageParser.Package pkg = mPackages.get(packageName);
14136            if (pkg == null) {
14137                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14138                throw new IllegalArgumentException("Unknown package: " + packageName);
14139            }
14140            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14141            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
14142        }
14143    }
14144
14145    @Override
14146    public KeySet getSigningKeySet(String packageName) {
14147        if (packageName == null) {
14148            return null;
14149        }
14150        synchronized(mPackages) {
14151            final PackageParser.Package pkg = mPackages.get(packageName);
14152            if (pkg == null) {
14153                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14154                throw new IllegalArgumentException("Unknown package: " + packageName);
14155            }
14156            if (pkg.applicationInfo.uid != Binder.getCallingUid()
14157                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
14158                throw new SecurityException("May not access signing KeySet of other apps.");
14159            }
14160            KeySetManagerService ksms = mSettings.mKeySetManagerService;
14161            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
14162        }
14163    }
14164
14165    @Override
14166    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
14167        if (packageName == null || ks == null) {
14168            return false;
14169        }
14170        synchronized(mPackages) {
14171            final PackageParser.Package pkg = mPackages.get(packageName);
14172            if (pkg == null) {
14173                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14174                throw new IllegalArgumentException("Unknown package: " + packageName);
14175            }
14176            IBinder ksh = ks.getToken();
14177            if (ksh instanceof KeySetHandle) {
14178                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14179                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
14180            }
14181            return false;
14182        }
14183    }
14184
14185    @Override
14186    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
14187        if (packageName == null || ks == null) {
14188            return false;
14189        }
14190        synchronized(mPackages) {
14191            final PackageParser.Package pkg = mPackages.get(packageName);
14192            if (pkg == null) {
14193                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
14194                throw new IllegalArgumentException("Unknown package: " + packageName);
14195            }
14196            IBinder ksh = ks.getToken();
14197            if (ksh instanceof KeySetHandle) {
14198                KeySetManagerService ksms = mSettings.mKeySetManagerService;
14199                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
14200            }
14201            return false;
14202        }
14203    }
14204
14205    public void getUsageStatsIfNoPackageUsageInfo() {
14206        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
14207            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
14208            if (usm == null) {
14209                throw new IllegalStateException("UsageStatsManager must be initialized");
14210            }
14211            long now = System.currentTimeMillis();
14212            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
14213            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
14214                String packageName = entry.getKey();
14215                PackageParser.Package pkg = mPackages.get(packageName);
14216                if (pkg == null) {
14217                    continue;
14218                }
14219                UsageStats usage = entry.getValue();
14220                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
14221                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
14222            }
14223        }
14224    }
14225
14226    /**
14227     * Check and throw if the given before/after packages would be considered a
14228     * downgrade.
14229     */
14230    private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after)
14231            throws PackageManagerException {
14232        if (after.versionCode < before.mVersionCode) {
14233            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14234                    "Update version code " + after.versionCode + " is older than current "
14235                    + before.mVersionCode);
14236        } else if (after.versionCode == before.mVersionCode) {
14237            if (after.baseRevisionCode < before.baseRevisionCode) {
14238                throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14239                        "Update base revision code " + after.baseRevisionCode
14240                        + " is older than current " + before.baseRevisionCode);
14241            }
14242
14243            if (!ArrayUtils.isEmpty(after.splitNames)) {
14244                for (int i = 0; i < after.splitNames.length; i++) {
14245                    final String splitName = after.splitNames[i];
14246                    final int j = ArrayUtils.indexOf(before.splitNames, splitName);
14247                    if (j != -1) {
14248                        if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) {
14249                            throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE,
14250                                    "Update split " + splitName + " revision code "
14251                                    + after.splitRevisionCodes[i] + " is older than current "
14252                                    + before.splitRevisionCodes[j]);
14253                        }
14254                    }
14255                }
14256            }
14257        }
14258    }
14259}
14260