PackageManagerService.java revision ec55ef0934b8e0d1bb705434947de817f7be57f1
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.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
28import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
29import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
30import static android.content.pm.PackageParser.isApkFile;
31import static android.os.Process.PACKAGE_INFO_GID;
32import static android.os.Process.SYSTEM_UID;
33import static android.system.OsConstants.O_CREAT;
34import static android.system.OsConstants.EEXIST;
35import static android.system.OsConstants.O_EXCL;
36import static android.system.OsConstants.O_RDWR;
37import static android.system.OsConstants.O_WRONLY;
38import static android.system.OsConstants.S_IRGRP;
39import static android.system.OsConstants.S_IROTH;
40import static android.system.OsConstants.S_IRWXU;
41import static android.system.OsConstants.S_IXGRP;
42import static android.system.OsConstants.S_IXOTH;
43import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
44import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
45import static com.android.internal.util.ArrayUtils.appendInt;
46import static com.android.internal.util.ArrayUtils.removeInt;
47
48import android.util.ArrayMap;
49
50import com.android.internal.R;
51import com.android.internal.app.IMediaContainerService;
52import com.android.internal.app.ResolverActivity;
53import com.android.internal.content.NativeLibraryHelper;
54import com.android.internal.content.PackageHelper;
55import com.android.internal.os.IParcelFileDescriptorFactory;
56import com.android.internal.util.ArrayUtils;
57import com.android.internal.util.FastPrintWriter;
58import com.android.internal.util.FastXmlSerializer;
59import com.android.internal.util.Preconditions;
60import com.android.internal.util.XmlUtils;
61import com.android.server.EventLogTags;
62import com.android.server.IntentResolver;
63import com.android.server.LocalServices;
64import com.android.server.ServiceThread;
65import com.android.server.SystemConfig;
66import com.android.server.Watchdog;
67import com.android.server.pm.Settings.DatabaseVersion;
68import com.android.server.storage.DeviceStorageMonitorInternal;
69
70import org.xmlpull.v1.XmlPullParser;
71import org.xmlpull.v1.XmlPullParserException;
72import org.xmlpull.v1.XmlSerializer;
73
74import android.app.ActivityManager;
75import android.app.ActivityManagerNative;
76import android.app.IActivityManager;
77import android.app.PackageInstallObserver;
78import android.app.admin.IDevicePolicyManager;
79import android.app.backup.IBackupManager;
80import android.content.BroadcastReceiver;
81import android.content.ComponentName;
82import android.content.Context;
83import android.content.IIntentReceiver;
84import android.content.Intent;
85import android.content.IntentFilter;
86import android.content.IntentSender;
87import android.content.IntentSender.SendIntentException;
88import android.content.ServiceConnection;
89import android.content.pm.ActivityInfo;
90import android.content.pm.ApplicationInfo;
91import android.content.pm.FeatureInfo;
92import android.content.pm.IPackageDataObserver;
93import android.content.pm.IPackageDeleteObserver;
94import android.content.pm.IPackageInstallObserver;
95import android.content.pm.IPackageInstallObserver2;
96import android.content.pm.IPackageInstaller;
97import android.content.pm.IPackageManager;
98import android.content.pm.IPackageMoveObserver;
99import android.content.pm.IPackageStatsObserver;
100import android.content.pm.InstrumentationInfo;
101import android.content.pm.ManifestDigest;
102import android.content.pm.PackageCleanItem;
103import android.content.pm.PackageInfo;
104import android.content.pm.PackageInfoLite;
105import android.content.pm.PackageInstallerParams;
106import android.content.pm.PackageManager;
107import android.content.pm.PackageParser.ActivityIntentInfo;
108import android.content.pm.PackageParser.PackageLite;
109import android.content.pm.PackageParser.PackageParserException;
110import android.content.pm.PackageParser;
111import android.content.pm.PackageStats;
112import android.content.pm.PackageUserState;
113import android.content.pm.ParceledListSlice;
114import android.content.pm.PermissionGroupInfo;
115import android.content.pm.PermissionInfo;
116import android.content.pm.ProviderInfo;
117import android.content.pm.ResolveInfo;
118import android.content.pm.ServiceInfo;
119import android.content.pm.Signature;
120import android.content.pm.UserInfo;
121import android.content.pm.VerificationParams;
122import android.content.pm.VerifierDeviceIdentity;
123import android.content.pm.VerifierInfo;
124import android.content.res.Resources;
125import android.hardware.display.DisplayManager;
126import android.net.Uri;
127import android.os.Binder;
128import android.os.Build;
129import android.os.Bundle;
130import android.os.Environment;
131import android.os.Environment.UserEnvironment;
132import android.os.FileObserver;
133import android.os.FileUtils;
134import android.os.Handler;
135import android.os.IBinder;
136import android.os.Looper;
137import android.os.Message;
138import android.os.Parcel;
139import android.os.ParcelFileDescriptor;
140import android.os.Process;
141import android.os.RemoteException;
142import android.os.SELinux;
143import android.os.ServiceManager;
144import android.os.SystemClock;
145import android.os.SystemProperties;
146import android.os.UserHandle;
147import android.os.UserManager;
148import android.security.KeyStore;
149import android.security.SystemKeyStore;
150import android.system.ErrnoException;
151import android.system.Os;
152import android.system.OsConstants;
153import android.system.StructStat;
154import android.text.TextUtils;
155import android.util.ArraySet;
156import android.util.AtomicFile;
157import android.util.DisplayMetrics;
158import android.util.EventLog;
159import android.util.Log;
160import android.util.LogPrinter;
161import android.util.PrintStreamPrinter;
162import android.util.Slog;
163import android.util.SparseArray;
164import android.util.SparseBooleanArray;
165import android.util.Xml;
166import android.view.Display;
167
168import java.io.BufferedInputStream;
169import java.io.BufferedOutputStream;
170import java.io.File;
171import java.io.FileDescriptor;
172import java.io.FileInputStream;
173import java.io.FileNotFoundException;
174import java.io.FileOutputStream;
175import java.io.FileReader;
176import java.io.FilenameFilter;
177import java.io.IOException;
178import java.io.InputStream;
179import java.io.PrintWriter;
180import java.nio.charset.StandardCharsets;
181import java.security.NoSuchAlgorithmException;
182import java.security.PublicKey;
183import java.security.cert.CertificateEncodingException;
184import java.security.cert.CertificateException;
185import java.text.SimpleDateFormat;
186import java.util.ArrayList;
187import java.util.Arrays;
188import java.util.Collection;
189import java.util.Collections;
190import java.util.Comparator;
191import java.util.Date;
192import java.util.HashMap;
193import java.util.HashSet;
194import java.util.Iterator;
195import java.util.List;
196import java.util.Map;
197import java.util.Random;
198import java.util.Set;
199import java.util.concurrent.atomic.AtomicBoolean;
200import java.util.concurrent.atomic.AtomicLong;
201
202import dalvik.system.DexFile;
203import dalvik.system.StaleDexCacheError;
204import dalvik.system.VMRuntime;
205
206import libcore.io.IoUtils;
207import libcore.io.Libcore;
208
209/**
210 * Keep track of all those .apks everywhere.
211 *
212 * This is very central to the platform's security; please run the unit
213 * tests whenever making modifications here:
214 *
215mmm frameworks/base/tests/AndroidTests
216adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
217adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
218 *
219 * {@hide}
220 */
221public class PackageManagerService extends IPackageManager.Stub {
222    static final String TAG = "PackageManager";
223    static final boolean DEBUG_SETTINGS = false;
224    static final boolean DEBUG_PREFERRED = false;
225    static final boolean DEBUG_UPGRADE = false;
226    private static final boolean DEBUG_INSTALL = false;
227    private static final boolean DEBUG_REMOVE = false;
228    private static final boolean DEBUG_BROADCASTS = false;
229    private static final boolean DEBUG_SHOW_INFO = false;
230    private static final boolean DEBUG_PACKAGE_INFO = false;
231    private static final boolean DEBUG_INTENT_MATCHING = false;
232    private static final boolean DEBUG_PACKAGE_SCANNING = false;
233    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
234    private static final boolean DEBUG_VERIFY = false;
235    private static final boolean DEBUG_DEXOPT = false;
236
237    private static final int RADIO_UID = Process.PHONE_UID;
238    private static final int LOG_UID = Process.LOG_UID;
239    private static final int NFC_UID = Process.NFC_UID;
240    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
241    private static final int SHELL_UID = Process.SHELL_UID;
242
243    // Cap the size of permission trees that 3rd party apps can define
244    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
245
246    private static final int REMOVE_EVENTS =
247        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
248    private static final int ADD_EVENTS =
249        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
250
251    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
252    // Suffix used during package installation when copying/moving
253    // package apks to install directory.
254    private static final String INSTALL_PACKAGE_SUFFIX = "-";
255
256    static final int SCAN_MONITOR = 1<<0;
257    static final int SCAN_NO_DEX = 1<<1;
258    static final int SCAN_FORCE_DEX = 1<<2;
259    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
260    static final int SCAN_NEW_INSTALL = 1<<4;
261    static final int SCAN_NO_PATHS = 1<<5;
262    static final int SCAN_UPDATE_TIME = 1<<6;
263    static final int SCAN_DEFER_DEX = 1<<7;
264    static final int SCAN_BOOTING = 1<<8;
265    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
266    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
267
268    static final int REMOVE_CHATTY = 1<<16;
269
270    /**
271     * Timeout (in milliseconds) after which the watchdog should declare that
272     * our handler thread is wedged.  The usual default for such things is one
273     * minute but we sometimes do very lengthy I/O operations on this thread,
274     * such as installing multi-gigabyte applications, so ours needs to be longer.
275     */
276    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
277
278    /**
279     * Whether verification is enabled by default.
280     */
281    private static final boolean DEFAULT_VERIFY_ENABLE = true;
282
283    /**
284     * The default maximum time to wait for the verification agent to return in
285     * milliseconds.
286     */
287    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
288
289    /**
290     * The default response for package verification timeout.
291     *
292     * This can be either PackageManager.VERIFICATION_ALLOW or
293     * PackageManager.VERIFICATION_REJECT.
294     */
295    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
296
297    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
298
299    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
300            DEFAULT_CONTAINER_PACKAGE,
301            "com.android.defcontainer.DefaultContainerService");
302
303    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
304
305    private static final String LIB_DIR_NAME = "lib";
306    private static final String LIB64_DIR_NAME = "lib64";
307
308    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
309
310    static final String mTempContainerPrefix = "smdl2tmp";
311
312    private static String sPreferredInstructionSet;
313
314    final ServiceThread mHandlerThread;
315
316    private static final String IDMAP_PREFIX = "/data/resource-cache/";
317    private static final String IDMAP_SUFFIX = "@idmap";
318
319    final PackageHandler mHandler;
320
321    final int mSdkVersion = Build.VERSION.SDK_INT;
322
323    final Context mContext;
324    final boolean mFactoryTest;
325    final boolean mOnlyCore;
326    final DisplayMetrics mMetrics;
327    final int mDefParseFlags;
328    final String[] mSeparateProcesses;
329
330    // This is where all application persistent data goes.
331    final File mAppDataDir;
332
333    // This is where all application persistent data goes for secondary users.
334    final File mUserAppDataDir;
335
336    /** The location for ASEC container files on internal storage. */
337    final String mAsecInternalPath;
338
339    // This is the object monitoring the framework dir.
340    final FileObserver mFrameworkInstallObserver;
341
342    // This is the object monitoring the system app dir.
343    final FileObserver mSystemInstallObserver;
344
345    // This is the object monitoring the privileged system app dir.
346    final FileObserver mPrivilegedInstallObserver;
347
348    // This is the object monitoring the vendor app dir.
349    final FileObserver mVendorInstallObserver;
350
351    // This is the object monitoring the vendor overlay package dir.
352    final FileObserver mVendorOverlayInstallObserver;
353
354    // This is the object monitoring the OEM app dir.
355    final FileObserver mOemInstallObserver;
356
357    // This is the object monitoring mAppInstallDir.
358    final FileObserver mAppInstallObserver;
359
360    // This is the object monitoring mDrmAppPrivateInstallDir.
361    final FileObserver mDrmAppInstallObserver;
362
363    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
364    // LOCK HELD.  Can be called with mInstallLock held.
365    final Installer mInstaller;
366
367    /** Directory where installed third-party apps stored */
368    final File mAppInstallDir;
369
370    /**
371     * Directory to which applications installed internally have native
372     * libraries copied.
373     */
374    private File mAppLibInstallDir;
375
376    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
377    // apps.
378    final File mDrmAppPrivateInstallDir;
379
380    // ----------------------------------------------------------------
381
382    // Lock for state used when installing and doing other long running
383    // operations.  Methods that must be called with this lock held have
384    // the suffix "LI".
385    final Object mInstallLock = new Object();
386
387    // These are the directories in the 3rd party applications installed dir
388    // that we have currently loaded packages from.  Keys are the application's
389    // installed zip file (absolute codePath), and values are Package.
390    final HashMap<String, PackageParser.Package> mAppDirs =
391            new HashMap<String, PackageParser.Package>();
392
393    // Information for the parser to write more useful error messages.
394    int mLastScanError;
395
396    // ----------------------------------------------------------------
397
398    // Keys are String (package name), values are Package.  This also serves
399    // as the lock for the global state.  Methods that must be called with
400    // this lock held have the prefix "LP".
401    final HashMap<String, PackageParser.Package> mPackages =
402            new HashMap<String, PackageParser.Package>();
403
404    // Tracks available target package names -> overlay package paths.
405    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
406        new HashMap<String, HashMap<String, PackageParser.Package>>();
407
408    final Settings mSettings;
409    boolean mRestoredSettings;
410
411    // System configuration read by SystemConfig.
412    final int[] mGlobalGids;
413    final SparseArray<HashSet<String>> mSystemPermissions;
414    final HashMap<String, FeatureInfo> mAvailableFeatures;
415
416    // If mac_permissions.xml was found for seinfo labeling.
417    boolean mFoundPolicyFile;
418
419    // If a recursive restorecon of /data/data/<pkg> is needed.
420    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
421
422    public static final class SharedLibraryEntry {
423        public final String path;
424        public final String apk;
425
426        SharedLibraryEntry(String _path, String _apk) {
427            path = _path;
428            apk = _apk;
429        }
430    }
431
432    // Currently known shared libraries.
433    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
434            new HashMap<String, SharedLibraryEntry>();
435
436    // All available activities, for your resolving pleasure.
437    final ActivityIntentResolver mActivities =
438            new ActivityIntentResolver();
439
440    // All available receivers, for your resolving pleasure.
441    final ActivityIntentResolver mReceivers =
442            new ActivityIntentResolver();
443
444    // All available services, for your resolving pleasure.
445    final ServiceIntentResolver mServices = new ServiceIntentResolver();
446
447    // All available providers, for your resolving pleasure.
448    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
449
450    // Mapping from provider base names (first directory in content URI codePath)
451    // to the provider information.
452    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
453            new HashMap<String, PackageParser.Provider>();
454
455    // Mapping from instrumentation class names to info about them.
456    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
457            new HashMap<ComponentName, PackageParser.Instrumentation>();
458
459    // Mapping from permission names to info about them.
460    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
461            new HashMap<String, PackageParser.PermissionGroup>();
462
463    // Packages whose data we have transfered into another package, thus
464    // should no longer exist.
465    final HashSet<String> mTransferedPackages = new HashSet<String>();
466
467    // Broadcast actions that are only available to the system.
468    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
469
470    /** List of packages waiting for verification. */
471    final SparseArray<PackageVerificationState> mPendingVerification
472            = new SparseArray<PackageVerificationState>();
473
474    final PackageInstallerService mInstallerService;
475
476    HashSet<PackageParser.Package> mDeferredDexOpt = null;
477
478    // Cache of users who need badging.
479    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
480
481    /** Token for keys in mPendingVerification. */
482    private int mPendingVerificationToken = 0;
483
484    boolean mSystemReady;
485    boolean mSafeMode;
486    boolean mHasSystemUidErrors;
487
488    ApplicationInfo mAndroidApplication;
489    final ActivityInfo mResolveActivity = new ActivityInfo();
490    final ResolveInfo mResolveInfo = new ResolveInfo();
491    ComponentName mResolveComponentName;
492    PackageParser.Package mPlatformPackage;
493    ComponentName mCustomResolverComponentName;
494
495    boolean mResolverReplaced = false;
496
497    // Set of pending broadcasts for aggregating enable/disable of components.
498    static class PendingPackageBroadcasts {
499        // for each user id, a map of <package name -> components within that package>
500        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
501
502        public PendingPackageBroadcasts() {
503            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
504        }
505
506        public ArrayList<String> get(int userId, String packageName) {
507            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
508            return packages.get(packageName);
509        }
510
511        public void put(int userId, String packageName, ArrayList<String> components) {
512            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
513            packages.put(packageName, components);
514        }
515
516        public void remove(int userId, String packageName) {
517            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
518            if (packages != null) {
519                packages.remove(packageName);
520            }
521        }
522
523        public void remove(int userId) {
524            mUidMap.remove(userId);
525        }
526
527        public int userIdCount() {
528            return mUidMap.size();
529        }
530
531        public int userIdAt(int n) {
532            return mUidMap.keyAt(n);
533        }
534
535        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
536            return mUidMap.get(userId);
537        }
538
539        public int size() {
540            // total number of pending broadcast entries across all userIds
541            int num = 0;
542            for (int i = 0; i< mUidMap.size(); i++) {
543                num += mUidMap.valueAt(i).size();
544            }
545            return num;
546        }
547
548        public void clear() {
549            mUidMap.clear();
550        }
551
552        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
553            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
554            if (map == null) {
555                map = new HashMap<String, ArrayList<String>>();
556                mUidMap.put(userId, map);
557            }
558            return map;
559        }
560    }
561    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
562
563    // Service Connection to remote media container service to copy
564    // package uri's from external media onto secure containers
565    // or internal storage.
566    private IMediaContainerService mContainerService = null;
567
568    static final int SEND_PENDING_BROADCAST = 1;
569    static final int MCS_BOUND = 3;
570    static final int END_COPY = 4;
571    static final int INIT_COPY = 5;
572    static final int MCS_UNBIND = 6;
573    static final int START_CLEANING_PACKAGE = 7;
574    static final int FIND_INSTALL_LOC = 8;
575    static final int POST_INSTALL = 9;
576    static final int MCS_RECONNECT = 10;
577    static final int MCS_GIVE_UP = 11;
578    static final int UPDATED_MEDIA_STATUS = 12;
579    static final int WRITE_SETTINGS = 13;
580    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
581    static final int PACKAGE_VERIFIED = 15;
582    static final int CHECK_PENDING_VERIFICATION = 16;
583
584    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
585
586    // Delay time in millisecs
587    static final int BROADCAST_DELAY = 10 * 1000;
588
589    static UserManagerService sUserManager;
590
591    // Stores a list of users whose package restrictions file needs to be updated
592    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
593
594    final private DefaultContainerConnection mDefContainerConn =
595            new DefaultContainerConnection();
596    class DefaultContainerConnection implements ServiceConnection {
597        public void onServiceConnected(ComponentName name, IBinder service) {
598            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
599            IMediaContainerService imcs =
600                IMediaContainerService.Stub.asInterface(service);
601            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
602        }
603
604        public void onServiceDisconnected(ComponentName name) {
605            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
606        }
607    };
608
609    // Recordkeeping of restore-after-install operations that are currently in flight
610    // between the Package Manager and the Backup Manager
611    class PostInstallData {
612        public InstallArgs args;
613        public PackageInstalledInfo res;
614
615        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
616            args = _a;
617            res = _r;
618        }
619    };
620    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
621    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
622
623    private final String mRequiredVerifierPackage;
624
625    private final PackageUsage mPackageUsage = new PackageUsage();
626
627    private class PackageUsage {
628        private static final int WRITE_INTERVAL
629            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
630
631        private final Object mFileLock = new Object();
632        private final AtomicLong mLastWritten = new AtomicLong(0);
633        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
634
635        private boolean mIsHistoricalPackageUsageAvailable = true;
636
637        boolean isHistoricalPackageUsageAvailable() {
638            return mIsHistoricalPackageUsageAvailable;
639        }
640
641        void write(boolean force) {
642            if (force) {
643                writeInternal();
644                return;
645            }
646            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
647                && !DEBUG_DEXOPT) {
648                return;
649            }
650            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
651                new Thread("PackageUsage_DiskWriter") {
652                    @Override
653                    public void run() {
654                        try {
655                            writeInternal();
656                        } finally {
657                            mBackgroundWriteRunning.set(false);
658                        }
659                    }
660                }.start();
661            }
662        }
663
664        private void writeInternal() {
665            synchronized (mPackages) {
666                synchronized (mFileLock) {
667                    AtomicFile file = getFile();
668                    FileOutputStream f = null;
669                    try {
670                        f = file.startWrite();
671                        BufferedOutputStream out = new BufferedOutputStream(f);
672                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
673                        StringBuilder sb = new StringBuilder();
674                        for (PackageParser.Package pkg : mPackages.values()) {
675                            if (pkg.mLastPackageUsageTimeInMills == 0) {
676                                continue;
677                            }
678                            sb.setLength(0);
679                            sb.append(pkg.packageName);
680                            sb.append(' ');
681                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
682                            sb.append('\n');
683                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
684                        }
685                        out.flush();
686                        file.finishWrite(f);
687                    } catch (IOException e) {
688                        if (f != null) {
689                            file.failWrite(f);
690                        }
691                        Log.e(TAG, "Failed to write package usage times", e);
692                    }
693                }
694            }
695            mLastWritten.set(SystemClock.elapsedRealtime());
696        }
697
698        void readLP() {
699            synchronized (mFileLock) {
700                AtomicFile file = getFile();
701                BufferedInputStream in = null;
702                try {
703                    in = new BufferedInputStream(file.openRead());
704                    StringBuffer sb = new StringBuffer();
705                    while (true) {
706                        String packageName = readToken(in, sb, ' ');
707                        if (packageName == null) {
708                            break;
709                        }
710                        String timeInMillisString = readToken(in, sb, '\n');
711                        if (timeInMillisString == null) {
712                            throw new IOException("Failed to find last usage time for package "
713                                                  + packageName);
714                        }
715                        PackageParser.Package pkg = mPackages.get(packageName);
716                        if (pkg == null) {
717                            continue;
718                        }
719                        long timeInMillis;
720                        try {
721                            timeInMillis = Long.parseLong(timeInMillisString.toString());
722                        } catch (NumberFormatException e) {
723                            throw new IOException("Failed to parse " + timeInMillisString
724                                                  + " as a long.", e);
725                        }
726                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
727                    }
728                } catch (FileNotFoundException expected) {
729                    mIsHistoricalPackageUsageAvailable = false;
730                } catch (IOException e) {
731                    Log.w(TAG, "Failed to read package usage times", e);
732                } finally {
733                    IoUtils.closeQuietly(in);
734                }
735            }
736            mLastWritten.set(SystemClock.elapsedRealtime());
737        }
738
739        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
740                throws IOException {
741            sb.setLength(0);
742            while (true) {
743                int ch = in.read();
744                if (ch == -1) {
745                    if (sb.length() == 0) {
746                        return null;
747                    }
748                    throw new IOException("Unexpected EOF");
749                }
750                if (ch == endOfToken) {
751                    return sb.toString();
752                }
753                sb.append((char)ch);
754            }
755        }
756
757        private AtomicFile getFile() {
758            File dataDir = Environment.getDataDirectory();
759            File systemDir = new File(dataDir, "system");
760            File fname = new File(systemDir, "package-usage.list");
761            return new AtomicFile(fname);
762        }
763    }
764
765    class PackageHandler extends Handler {
766        private boolean mBound = false;
767        final ArrayList<HandlerParams> mPendingInstalls =
768            new ArrayList<HandlerParams>();
769
770        private boolean connectToService() {
771            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
772                    " DefaultContainerService");
773            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
774            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
775            if (mContext.bindServiceAsUser(service, mDefContainerConn,
776                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
777                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
778                mBound = true;
779                return true;
780            }
781            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
782            return false;
783        }
784
785        private void disconnectService() {
786            mContainerService = null;
787            mBound = false;
788            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
789            mContext.unbindService(mDefContainerConn);
790            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
791        }
792
793        PackageHandler(Looper looper) {
794            super(looper);
795        }
796
797        public void handleMessage(Message msg) {
798            try {
799                doHandleMessage(msg);
800            } finally {
801                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
802            }
803        }
804
805        void doHandleMessage(Message msg) {
806            switch (msg.what) {
807                case INIT_COPY: {
808                    HandlerParams params = (HandlerParams) msg.obj;
809                    int idx = mPendingInstalls.size();
810                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
811                    // If a bind was already initiated we dont really
812                    // need to do anything. The pending install
813                    // will be processed later on.
814                    if (!mBound) {
815                        // If this is the only one pending we might
816                        // have to bind to the service again.
817                        if (!connectToService()) {
818                            Slog.e(TAG, "Failed to bind to media container service");
819                            params.serviceError();
820                            return;
821                        } else {
822                            // Once we bind to the service, the first
823                            // pending request will be processed.
824                            mPendingInstalls.add(idx, params);
825                        }
826                    } else {
827                        mPendingInstalls.add(idx, params);
828                        // Already bound to the service. Just make
829                        // sure we trigger off processing the first request.
830                        if (idx == 0) {
831                            mHandler.sendEmptyMessage(MCS_BOUND);
832                        }
833                    }
834                    break;
835                }
836                case MCS_BOUND: {
837                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
838                    if (msg.obj != null) {
839                        mContainerService = (IMediaContainerService) msg.obj;
840                    }
841                    if (mContainerService == null) {
842                        // Something seriously wrong. Bail out
843                        Slog.e(TAG, "Cannot bind to media container service");
844                        for (HandlerParams params : mPendingInstalls) {
845                            // Indicate service bind error
846                            params.serviceError();
847                        }
848                        mPendingInstalls.clear();
849                    } else if (mPendingInstalls.size() > 0) {
850                        HandlerParams params = mPendingInstalls.get(0);
851                        if (params != null) {
852                            if (params.startCopy()) {
853                                // We are done...  look for more work or to
854                                // go idle.
855                                if (DEBUG_SD_INSTALL) Log.i(TAG,
856                                        "Checking for more work or unbind...");
857                                // Delete pending install
858                                if (mPendingInstalls.size() > 0) {
859                                    mPendingInstalls.remove(0);
860                                }
861                                if (mPendingInstalls.size() == 0) {
862                                    if (mBound) {
863                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
864                                                "Posting delayed MCS_UNBIND");
865                                        removeMessages(MCS_UNBIND);
866                                        Message ubmsg = obtainMessage(MCS_UNBIND);
867                                        // Unbind after a little delay, to avoid
868                                        // continual thrashing.
869                                        sendMessageDelayed(ubmsg, 10000);
870                                    }
871                                } else {
872                                    // There are more pending requests in queue.
873                                    // Just post MCS_BOUND message to trigger processing
874                                    // of next pending install.
875                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
876                                            "Posting MCS_BOUND for next work");
877                                    mHandler.sendEmptyMessage(MCS_BOUND);
878                                }
879                            }
880                        }
881                    } else {
882                        // Should never happen ideally.
883                        Slog.w(TAG, "Empty queue");
884                    }
885                    break;
886                }
887                case MCS_RECONNECT: {
888                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
889                    if (mPendingInstalls.size() > 0) {
890                        if (mBound) {
891                            disconnectService();
892                        }
893                        if (!connectToService()) {
894                            Slog.e(TAG, "Failed to bind to media container service");
895                            for (HandlerParams params : mPendingInstalls) {
896                                // Indicate service bind error
897                                params.serviceError();
898                            }
899                            mPendingInstalls.clear();
900                        }
901                    }
902                    break;
903                }
904                case MCS_UNBIND: {
905                    // If there is no actual work left, then time to unbind.
906                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
907
908                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
909                        if (mBound) {
910                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
911
912                            disconnectService();
913                        }
914                    } else if (mPendingInstalls.size() > 0) {
915                        // There are more pending requests in queue.
916                        // Just post MCS_BOUND message to trigger processing
917                        // of next pending install.
918                        mHandler.sendEmptyMessage(MCS_BOUND);
919                    }
920
921                    break;
922                }
923                case MCS_GIVE_UP: {
924                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
925                    mPendingInstalls.remove(0);
926                    break;
927                }
928                case SEND_PENDING_BROADCAST: {
929                    String packages[];
930                    ArrayList<String> components[];
931                    int size = 0;
932                    int uids[];
933                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
934                    synchronized (mPackages) {
935                        if (mPendingBroadcasts == null) {
936                            return;
937                        }
938                        size = mPendingBroadcasts.size();
939                        if (size <= 0) {
940                            // Nothing to be done. Just return
941                            return;
942                        }
943                        packages = new String[size];
944                        components = new ArrayList[size];
945                        uids = new int[size];
946                        int i = 0;  // filling out the above arrays
947
948                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
949                            int packageUserId = mPendingBroadcasts.userIdAt(n);
950                            Iterator<Map.Entry<String, ArrayList<String>>> it
951                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
952                                            .entrySet().iterator();
953                            while (it.hasNext() && i < size) {
954                                Map.Entry<String, ArrayList<String>> ent = it.next();
955                                packages[i] = ent.getKey();
956                                components[i] = ent.getValue();
957                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
958                                uids[i] = (ps != null)
959                                        ? UserHandle.getUid(packageUserId, ps.appId)
960                                        : -1;
961                                i++;
962                            }
963                        }
964                        size = i;
965                        mPendingBroadcasts.clear();
966                    }
967                    // Send broadcasts
968                    for (int i = 0; i < size; i++) {
969                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
970                    }
971                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
972                    break;
973                }
974                case START_CLEANING_PACKAGE: {
975                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
976                    final String packageName = (String)msg.obj;
977                    final int userId = msg.arg1;
978                    final boolean andCode = msg.arg2 != 0;
979                    synchronized (mPackages) {
980                        if (userId == UserHandle.USER_ALL) {
981                            int[] users = sUserManager.getUserIds();
982                            for (int user : users) {
983                                mSettings.addPackageToCleanLPw(
984                                        new PackageCleanItem(user, packageName, andCode));
985                            }
986                        } else {
987                            mSettings.addPackageToCleanLPw(
988                                    new PackageCleanItem(userId, packageName, andCode));
989                        }
990                    }
991                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
992                    startCleaningPackages();
993                } break;
994                case POST_INSTALL: {
995                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
996                    PostInstallData data = mRunningInstalls.get(msg.arg1);
997                    mRunningInstalls.delete(msg.arg1);
998                    boolean deleteOld = false;
999
1000                    if (data != null) {
1001                        InstallArgs args = data.args;
1002                        PackageInstalledInfo res = data.res;
1003
1004                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1005                            res.removedInfo.sendBroadcast(false, true, false);
1006                            Bundle extras = new Bundle(1);
1007                            extras.putInt(Intent.EXTRA_UID, res.uid);
1008                            // Determine the set of users who are adding this
1009                            // package for the first time vs. those who are seeing
1010                            // an update.
1011                            int[] firstUsers;
1012                            int[] updateUsers = new int[0];
1013                            if (res.origUsers == null || res.origUsers.length == 0) {
1014                                firstUsers = res.newUsers;
1015                            } else {
1016                                firstUsers = new int[0];
1017                                for (int i=0; i<res.newUsers.length; i++) {
1018                                    int user = res.newUsers[i];
1019                                    boolean isNew = true;
1020                                    for (int j=0; j<res.origUsers.length; j++) {
1021                                        if (res.origUsers[j] == user) {
1022                                            isNew = false;
1023                                            break;
1024                                        }
1025                                    }
1026                                    if (isNew) {
1027                                        int[] newFirst = new int[firstUsers.length+1];
1028                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1029                                                firstUsers.length);
1030                                        newFirst[firstUsers.length] = user;
1031                                        firstUsers = newFirst;
1032                                    } else {
1033                                        int[] newUpdate = new int[updateUsers.length+1];
1034                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1035                                                updateUsers.length);
1036                                        newUpdate[updateUsers.length] = user;
1037                                        updateUsers = newUpdate;
1038                                    }
1039                                }
1040                            }
1041                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1042                                    res.pkg.applicationInfo.packageName,
1043                                    extras, null, null, firstUsers);
1044                            final boolean update = res.removedInfo.removedPackage != null;
1045                            if (update) {
1046                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1047                            }
1048                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1049                                    res.pkg.applicationInfo.packageName,
1050                                    extras, null, null, updateUsers);
1051                            if (update) {
1052                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1053                                        res.pkg.applicationInfo.packageName,
1054                                        extras, null, null, updateUsers);
1055                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1056                                        null, null,
1057                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1058
1059                                // treat asec-hosted packages like removable media on upgrade
1060                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1061                                    if (DEBUG_INSTALL) {
1062                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1063                                                + " is ASEC-hosted -> AVAILABLE");
1064                                    }
1065                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1066                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1067                                    pkgList.add(res.pkg.applicationInfo.packageName);
1068                                    sendResourcesChangedBroadcast(true, true,
1069                                            pkgList,uidArray, null);
1070                                }
1071                            }
1072                            if (res.removedInfo.args != null) {
1073                                // Remove the replaced package's older resources safely now
1074                                deleteOld = true;
1075                            }
1076
1077                            // Log current value of "unknown sources" setting
1078                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1079                                getUnknownSourcesSettings());
1080                        }
1081                        // Force a gc to clear up things
1082                        Runtime.getRuntime().gc();
1083                        // We delete after a gc for applications  on sdcard.
1084                        if (deleteOld) {
1085                            synchronized (mInstallLock) {
1086                                res.removedInfo.args.doPostDeleteLI(true);
1087                            }
1088                        }
1089                        if (args.observer != null) {
1090                            try {
1091                                Bundle extras = extrasForInstallResult(res);
1092                                args.observer.packageInstalled(res.name, extras, res.returnCode);
1093                            } catch (RemoteException e) {
1094                                Slog.i(TAG, "Observer no longer exists.");
1095                            }
1096                        }
1097                    } else {
1098                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1099                    }
1100                } break;
1101                case UPDATED_MEDIA_STATUS: {
1102                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1103                    boolean reportStatus = msg.arg1 == 1;
1104                    boolean doGc = msg.arg2 == 1;
1105                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1106                    if (doGc) {
1107                        // Force a gc to clear up stale containers.
1108                        Runtime.getRuntime().gc();
1109                    }
1110                    if (msg.obj != null) {
1111                        @SuppressWarnings("unchecked")
1112                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1113                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1114                        // Unload containers
1115                        unloadAllContainers(args);
1116                    }
1117                    if (reportStatus) {
1118                        try {
1119                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1120                            PackageHelper.getMountService().finishMediaUpdate();
1121                        } catch (RemoteException e) {
1122                            Log.e(TAG, "MountService not running?");
1123                        }
1124                    }
1125                } break;
1126                case WRITE_SETTINGS: {
1127                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1128                    synchronized (mPackages) {
1129                        removeMessages(WRITE_SETTINGS);
1130                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1131                        mSettings.writeLPr();
1132                        mDirtyUsers.clear();
1133                    }
1134                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1135                } break;
1136                case WRITE_PACKAGE_RESTRICTIONS: {
1137                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1138                    synchronized (mPackages) {
1139                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1140                        for (int userId : mDirtyUsers) {
1141                            mSettings.writePackageRestrictionsLPr(userId);
1142                        }
1143                        mDirtyUsers.clear();
1144                    }
1145                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1146                } break;
1147                case CHECK_PENDING_VERIFICATION: {
1148                    final int verificationId = msg.arg1;
1149                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1150
1151                    if ((state != null) && !state.timeoutExtended()) {
1152                        final InstallArgs args = state.getInstallArgs();
1153                        final Uri originUri = Uri.fromFile(args.originFile);
1154
1155                        Slog.i(TAG, "Verification timed out for " + originUri);
1156                        mPendingVerification.remove(verificationId);
1157
1158                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1159
1160                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1161                            Slog.i(TAG, "Continuing with installation of " + originUri);
1162                            state.setVerifierResponse(Binder.getCallingUid(),
1163                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1164                            broadcastPackageVerified(verificationId, originUri,
1165                                    PackageManager.VERIFICATION_ALLOW,
1166                                    state.getInstallArgs().getUser());
1167                            try {
1168                                ret = args.copyApk(mContainerService, true);
1169                            } catch (RemoteException e) {
1170                                Slog.e(TAG, "Could not contact the ContainerService");
1171                            }
1172                        } else {
1173                            broadcastPackageVerified(verificationId, originUri,
1174                                    PackageManager.VERIFICATION_REJECT,
1175                                    state.getInstallArgs().getUser());
1176                        }
1177
1178                        processPendingInstall(args, ret);
1179                        mHandler.sendEmptyMessage(MCS_UNBIND);
1180                    }
1181                    break;
1182                }
1183                case PACKAGE_VERIFIED: {
1184                    final int verificationId = msg.arg1;
1185
1186                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1187                    if (state == null) {
1188                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1189                        break;
1190                    }
1191
1192                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1193
1194                    state.setVerifierResponse(response.callerUid, response.code);
1195
1196                    if (state.isVerificationComplete()) {
1197                        mPendingVerification.remove(verificationId);
1198
1199                        final InstallArgs args = state.getInstallArgs();
1200                        final Uri originUri = Uri.fromFile(args.originFile);
1201
1202                        int ret;
1203                        if (state.isInstallAllowed()) {
1204                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1205                            broadcastPackageVerified(verificationId, originUri,
1206                                    response.code, state.getInstallArgs().getUser());
1207                            try {
1208                                ret = args.copyApk(mContainerService, true);
1209                            } catch (RemoteException e) {
1210                                Slog.e(TAG, "Could not contact the ContainerService");
1211                            }
1212                        } else {
1213                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1214                        }
1215
1216                        processPendingInstall(args, ret);
1217
1218                        mHandler.sendEmptyMessage(MCS_UNBIND);
1219                    }
1220
1221                    break;
1222                }
1223            }
1224        }
1225    }
1226
1227    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1228        Bundle extras = null;
1229        switch (res.returnCode) {
1230            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1231                extras = new Bundle();
1232                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1233                        res.origPermission);
1234                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1235                        res.origPackage);
1236                break;
1237            }
1238        }
1239        return extras;
1240    }
1241
1242    void scheduleWriteSettingsLocked() {
1243        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1244            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1245        }
1246    }
1247
1248    void scheduleWritePackageRestrictionsLocked(int userId) {
1249        if (!sUserManager.exists(userId)) return;
1250        mDirtyUsers.add(userId);
1251        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1252            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1253        }
1254    }
1255
1256    public static final PackageManagerService main(Context context, Installer installer,
1257            boolean factoryTest, boolean onlyCore) {
1258        PackageManagerService m = new PackageManagerService(context, installer,
1259                factoryTest, onlyCore);
1260        ServiceManager.addService("package", m);
1261        return m;
1262    }
1263
1264    static String[] splitString(String str, char sep) {
1265        int count = 1;
1266        int i = 0;
1267        while ((i=str.indexOf(sep, i)) >= 0) {
1268            count++;
1269            i++;
1270        }
1271
1272        String[] res = new String[count];
1273        i=0;
1274        count = 0;
1275        int lastI=0;
1276        while ((i=str.indexOf(sep, i)) >= 0) {
1277            res[count] = str.substring(lastI, i);
1278            count++;
1279            i++;
1280            lastI = i;
1281        }
1282        res[count] = str.substring(lastI, str.length());
1283        return res;
1284    }
1285
1286    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1287        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1288                Context.DISPLAY_SERVICE);
1289        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1290    }
1291
1292    public PackageManagerService(Context context, Installer installer,
1293            boolean factoryTest, boolean onlyCore) {
1294        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1295                SystemClock.uptimeMillis());
1296
1297        if (mSdkVersion <= 0) {
1298            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1299        }
1300
1301        mContext = context;
1302        mFactoryTest = factoryTest;
1303        mOnlyCore = onlyCore;
1304        mMetrics = new DisplayMetrics();
1305        mSettings = new Settings(context);
1306        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1307                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1308        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1309                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1310        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1313                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1314        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1315                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1316        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1317                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1318
1319        String separateProcesses = SystemProperties.get("debug.separate_processes");
1320        if (separateProcesses != null && separateProcesses.length() > 0) {
1321            if ("*".equals(separateProcesses)) {
1322                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1323                mSeparateProcesses = null;
1324                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1325            } else {
1326                mDefParseFlags = 0;
1327                mSeparateProcesses = separateProcesses.split(",");
1328                Slog.w(TAG, "Running with debug.separate_processes: "
1329                        + separateProcesses);
1330            }
1331        } else {
1332            mDefParseFlags = 0;
1333            mSeparateProcesses = null;
1334        }
1335
1336        mInstaller = installer;
1337
1338        getDefaultDisplayMetrics(context, mMetrics);
1339
1340        SystemConfig systemConfig = SystemConfig.getInstance();
1341        mGlobalGids = systemConfig.getGlobalGids();
1342        mSystemPermissions = systemConfig.getSystemPermissions();
1343        mAvailableFeatures = systemConfig.getAvailableFeatures();
1344
1345        synchronized (mInstallLock) {
1346        // writer
1347        synchronized (mPackages) {
1348            mHandlerThread = new ServiceThread(TAG,
1349                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1350            mHandlerThread.start();
1351            mHandler = new PackageHandler(mHandlerThread.getLooper());
1352            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1353
1354            File dataDir = Environment.getDataDirectory();
1355            mAppDataDir = new File(dataDir, "data");
1356            mAppInstallDir = new File(dataDir, "app");
1357            mAppLibInstallDir = new File(dataDir, "app-lib");
1358            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1359            mUserAppDataDir = new File(dataDir, "user");
1360            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1361
1362            sUserManager = new UserManagerService(context, this,
1363                    mInstallLock, mPackages);
1364
1365            // Propagate permission configuration in to package manager.
1366            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1367                    = systemConfig.getPermissions();
1368            for (int i=0; i<permConfig.size(); i++) {
1369                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1370                BasePermission bp = mSettings.mPermissions.get(perm.name);
1371                if (bp == null) {
1372                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1373                    mSettings.mPermissions.put(perm.name, bp);
1374                }
1375                if (perm.gids != null) {
1376                    bp.gids = appendInts(bp.gids, perm.gids);
1377                }
1378            }
1379
1380            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1381            for (int i=0; i<libConfig.size(); i++) {
1382                mSharedLibraries.put(libConfig.keyAt(i),
1383                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1384            }
1385
1386            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1387
1388            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1389                    mSdkVersion, mOnlyCore);
1390
1391            String customResolverActivity = Resources.getSystem().getString(
1392                    R.string.config_customResolverActivity);
1393            if (TextUtils.isEmpty(customResolverActivity)) {
1394                customResolverActivity = null;
1395            } else {
1396                mCustomResolverComponentName = ComponentName.unflattenFromString(
1397                        customResolverActivity);
1398            }
1399
1400            long startTime = SystemClock.uptimeMillis();
1401
1402            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1403                    startTime);
1404
1405            // Set flag to monitor and not change apk file paths when
1406            // scanning install directories.
1407            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1408
1409            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1410
1411            /**
1412             * Add everything in the in the boot class path to the
1413             * list of process files because dexopt will have been run
1414             * if necessary during zygote startup.
1415             */
1416            String bootClassPath = System.getProperty("java.boot.class.path");
1417            if (bootClassPath != null) {
1418                String[] paths = splitString(bootClassPath, ':');
1419                for (int i=0; i<paths.length; i++) {
1420                    alreadyDexOpted.add(paths[i]);
1421                }
1422            } else {
1423                Slog.w(TAG, "No BOOTCLASSPATH found!");
1424            }
1425
1426            boolean didDexOptLibraryOrTool = false;
1427
1428            final List<String> instructionSets = getAllInstructionSets();
1429
1430            /**
1431             * Ensure all external libraries have had dexopt run on them.
1432             */
1433            if (mSharedLibraries.size() > 0) {
1434                // NOTE: For now, we're compiling these system "shared libraries"
1435                // (and framework jars) into all available architectures. It's possible
1436                // to compile them only when we come across an app that uses them (there's
1437                // already logic for that in scanPackageLI) but that adds some complexity.
1438                for (String instructionSet : instructionSets) {
1439                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1440                        final String lib = libEntry.path;
1441                        if (lib == null) {
1442                            continue;
1443                        }
1444
1445                        try {
1446                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1447                                alreadyDexOpted.add(lib);
1448
1449                                // The list of "shared libraries" we have at this point is
1450                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1451                                didDexOptLibraryOrTool = true;
1452                            }
1453                        } catch (FileNotFoundException e) {
1454                            Slog.w(TAG, "Library not found: " + lib);
1455                        } catch (IOException e) {
1456                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1457                                    + e.getMessage());
1458                        }
1459                    }
1460                }
1461            }
1462
1463            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1464
1465            // Gross hack for now: we know this file doesn't contain any
1466            // code, so don't dexopt it to avoid the resulting log spew.
1467            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1468
1469            // Gross hack for now: we know this file is only part of
1470            // the boot class path for art, so don't dexopt it to
1471            // avoid the resulting log spew.
1472            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1473
1474            /**
1475             * And there are a number of commands implemented in Java, which
1476             * we currently need to do the dexopt on so that they can be
1477             * run from a non-root shell.
1478             */
1479            String[] frameworkFiles = frameworkDir.list();
1480            if (frameworkFiles != null) {
1481                // TODO: We could compile these only for the most preferred ABI. We should
1482                // first double check that the dex files for these commands are not referenced
1483                // by other system apps.
1484                for (String instructionSet : instructionSets) {
1485                    for (int i=0; i<frameworkFiles.length; i++) {
1486                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1487                        String path = libPath.getPath();
1488                        // Skip the file if we already did it.
1489                        if (alreadyDexOpted.contains(path)) {
1490                            continue;
1491                        }
1492                        // Skip the file if it is not a type we want to dexopt.
1493                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1494                            continue;
1495                        }
1496                        try {
1497                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1498                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1499                                didDexOptLibraryOrTool = true;
1500                            }
1501                        } catch (FileNotFoundException e) {
1502                            Slog.w(TAG, "Jar not found: " + path);
1503                        } catch (IOException e) {
1504                            Slog.w(TAG, "Exception reading jar: " + path, e);
1505                        }
1506                    }
1507                }
1508            }
1509
1510            if (didDexOptLibraryOrTool) {
1511                // If we dexopted a library or tool, then something on the system has
1512                // changed. Consider this significant, and wipe away all other
1513                // existing dexopt files to ensure we don't leave any dangling around.
1514                //
1515                // TODO: This should be revisited because it isn't as good an indicator
1516                // as it used to be. It used to include the boot classpath but at some point
1517                // DexFile.isDexOptNeeded started returning false for the boot
1518                // class path files in all cases. It is very possible in a
1519                // small maintenance release update that the library and tool
1520                // jars may be unchanged but APK could be removed resulting in
1521                // unused dalvik-cache files.
1522                for (String instructionSet : instructionSets) {
1523                    mInstaller.pruneDexCache(instructionSet);
1524                }
1525
1526                // Additionally, delete all dex files from the root directory
1527                // since there shouldn't be any there anyway, unless we're upgrading
1528                // from an older OS version or a build that contained the "old" style
1529                // flat scheme.
1530                mInstaller.pruneDexCache(".");
1531            }
1532
1533            // Collect vendor overlay packages.
1534            // (Do this before scanning any apps.)
1535            // For security and version matching reason, only consider
1536            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1537            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1538            mVendorOverlayInstallObserver = new AppDirObserver(
1539                    vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1540            mVendorOverlayInstallObserver.startWatching();
1541            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1542                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1543
1544            // Find base frameworks (resource packages without code).
1545            mFrameworkInstallObserver = new AppDirObserver(
1546                    frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1547            mFrameworkInstallObserver.startWatching();
1548            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1549                    | PackageParser.PARSE_IS_SYSTEM_DIR
1550                    | PackageParser.PARSE_IS_PRIVILEGED,
1551                    scanMode | SCAN_NO_DEX, 0);
1552
1553            // Collected privileged system packages.
1554            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1555            mPrivilegedInstallObserver = new AppDirObserver(
1556                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1557            mPrivilegedInstallObserver.startWatching();
1558            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1559                    | PackageParser.PARSE_IS_SYSTEM_DIR
1560                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1561
1562            // Collect ordinary system packages.
1563            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1564            mSystemInstallObserver = new AppDirObserver(
1565                    systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1566            mSystemInstallObserver.startWatching();
1567            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1568                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1569
1570            // Collect all vendor packages.
1571            File vendorAppDir = new File("/vendor/app");
1572            try {
1573                vendorAppDir = vendorAppDir.getCanonicalFile();
1574            } catch (IOException e) {
1575                // failed to look up canonical path, continue with original one
1576            }
1577            mVendorInstallObserver = new AppDirObserver(
1578                    vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1579            mVendorInstallObserver.startWatching();
1580            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1581                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1582
1583            // Collect all OEM packages.
1584            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1585            mOemInstallObserver = new AppDirObserver(
1586                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1587            mOemInstallObserver.startWatching();
1588            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1589                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1590
1591            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1592            mInstaller.moveFiles();
1593
1594            // Prune any system packages that no longer exist.
1595            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1596            if (!mOnlyCore) {
1597                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1598                while (psit.hasNext()) {
1599                    PackageSetting ps = psit.next();
1600
1601                    /*
1602                     * If this is not a system app, it can't be a
1603                     * disable system app.
1604                     */
1605                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1606                        continue;
1607                    }
1608
1609                    /*
1610                     * If the package is scanned, it's not erased.
1611                     */
1612                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1613                    if (scannedPkg != null) {
1614                        /*
1615                         * If the system app is both scanned and in the
1616                         * disabled packages list, then it must have been
1617                         * added via OTA. Remove it from the currently
1618                         * scanned package so the previously user-installed
1619                         * application can be scanned.
1620                         */
1621                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1622                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1623                                    + "; removing system app");
1624                            removePackageLI(ps, true);
1625                        }
1626
1627                        continue;
1628                    }
1629
1630                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1631                        psit.remove();
1632                        String msg = "System package " + ps.name
1633                                + " no longer exists; wiping its data";
1634                        reportSettingsProblem(Log.WARN, msg);
1635                        removeDataDirsLI(ps.name);
1636                    } else {
1637                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1638                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1639                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1640                        }
1641                    }
1642                }
1643            }
1644
1645            //look for any incomplete package installations
1646            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1647            //clean up list
1648            for(int i = 0; i < deletePkgsList.size(); i++) {
1649                //clean up here
1650                cleanupInstallFailedPackage(deletePkgsList.get(i));
1651            }
1652            //delete tmp files
1653            deleteTempPackageFiles();
1654
1655            // Remove any shared userIDs that have no associated packages
1656            mSettings.pruneSharedUsersLPw();
1657
1658            if (!mOnlyCore) {
1659                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1660                        SystemClock.uptimeMillis());
1661                mAppInstallObserver = new AppDirObserver(
1662                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1663                mAppInstallObserver.startWatching();
1664                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1665
1666                mDrmAppInstallObserver = new AppDirObserver(
1667                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1668                mDrmAppInstallObserver.startWatching();
1669                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1670                        scanMode, 0);
1671
1672                /**
1673                 * Remove disable package settings for any updated system
1674                 * apps that were removed via an OTA. If they're not a
1675                 * previously-updated app, remove them completely.
1676                 * Otherwise, just revoke their system-level permissions.
1677                 */
1678                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1679                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1680                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1681
1682                    String msg;
1683                    if (deletedPkg == null) {
1684                        msg = "Updated system package " + deletedAppName
1685                                + " no longer exists; wiping its data";
1686                        removeDataDirsLI(deletedAppName);
1687                    } else {
1688                        msg = "Updated system app + " + deletedAppName
1689                                + " no longer present; removing system privileges for "
1690                                + deletedAppName;
1691
1692                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1693
1694                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1695                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1696                    }
1697                    reportSettingsProblem(Log.WARN, msg);
1698                }
1699            } else {
1700                mAppInstallObserver = null;
1701                mDrmAppInstallObserver = null;
1702            }
1703
1704            // Now that we know all of the shared libraries, update all clients to have
1705            // the correct library paths.
1706            updateAllSharedLibrariesLPw();
1707
1708            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1709                // NOTE: We ignore potential failures here during a system scan (like
1710                // the rest of the commands above) because there's precious little we
1711                // can do about it. A settings error is reported, though.
1712                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1713                        false /* force dexopt */, false /* defer dexopt */);
1714            }
1715
1716            // Now that we know all the packages we are keeping,
1717            // read and update their last usage times.
1718            mPackageUsage.readLP();
1719
1720            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1721                    SystemClock.uptimeMillis());
1722            Slog.i(TAG, "Time to scan packages: "
1723                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1724                    + " seconds");
1725
1726            // If the platform SDK has changed since the last time we booted,
1727            // we need to re-grant app permission to catch any new ones that
1728            // appear.  This is really a hack, and means that apps can in some
1729            // cases get permissions that the user didn't initially explicitly
1730            // allow...  it would be nice to have some better way to handle
1731            // this situation.
1732            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1733                    != mSdkVersion;
1734            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1735                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1736                    + "; regranting permissions for internal storage");
1737            mSettings.mInternalSdkPlatform = mSdkVersion;
1738
1739            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1740                    | (regrantPermissions
1741                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1742                            : 0));
1743
1744            // If this is the first boot, and it is a normal boot, then
1745            // we need to initialize the default preferred apps.
1746            if (!mRestoredSettings && !onlyCore) {
1747                mSettings.readDefaultPreferredAppsLPw(this, 0);
1748            }
1749
1750            // All the changes are done during package scanning.
1751            mSettings.updateInternalDatabaseVersion();
1752
1753            // can downgrade to reader
1754            mSettings.writeLPr();
1755
1756            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1757                    SystemClock.uptimeMillis());
1758
1759
1760            mRequiredVerifierPackage = getRequiredVerifierLPr();
1761        } // synchronized (mPackages)
1762        } // synchronized (mInstallLock)
1763
1764        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1765
1766        // Now after opening every single application zip, make sure they
1767        // are all flushed.  Not really needed, but keeps things nice and
1768        // tidy.
1769        Runtime.getRuntime().gc();
1770    }
1771
1772    @Override
1773    public boolean isFirstBoot() {
1774        return !mRestoredSettings;
1775    }
1776
1777    @Override
1778    public boolean isOnlyCoreApps() {
1779        return mOnlyCore;
1780    }
1781
1782    private String getRequiredVerifierLPr() {
1783        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1784        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1785                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1786
1787        String requiredVerifier = null;
1788
1789        final int N = receivers.size();
1790        for (int i = 0; i < N; i++) {
1791            final ResolveInfo info = receivers.get(i);
1792
1793            if (info.activityInfo == null) {
1794                continue;
1795            }
1796
1797            final String packageName = info.activityInfo.packageName;
1798
1799            final PackageSetting ps = mSettings.mPackages.get(packageName);
1800            if (ps == null) {
1801                continue;
1802            }
1803
1804            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1805            if (!gp.grantedPermissions
1806                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1807                continue;
1808            }
1809
1810            if (requiredVerifier != null) {
1811                throw new RuntimeException("There can be only one required verifier");
1812            }
1813
1814            requiredVerifier = packageName;
1815        }
1816
1817        return requiredVerifier;
1818    }
1819
1820    @Override
1821    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1822            throws RemoteException {
1823        try {
1824            return super.onTransact(code, data, reply, flags);
1825        } catch (RuntimeException e) {
1826            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1827                Slog.wtf(TAG, "Package Manager Crash", e);
1828            }
1829            throw e;
1830        }
1831    }
1832
1833    void cleanupInstallFailedPackage(PackageSetting ps) {
1834        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1835        removeDataDirsLI(ps.name);
1836
1837        // TODO: try cleaning up codePath directory contents first, since it
1838        // might be a cluster
1839
1840        if (ps.codePath != null) {
1841            if (!ps.codePath.delete()) {
1842                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1843            }
1844        }
1845        if (ps.resourcePath != null) {
1846            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1847                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1848            }
1849        }
1850        mSettings.removePackageLPw(ps.name);
1851    }
1852
1853    static int[] appendInts(int[] cur, int[] add) {
1854        if (add == null) return cur;
1855        if (cur == null) return add;
1856        final int N = add.length;
1857        for (int i=0; i<N; i++) {
1858            cur = appendInt(cur, add[i]);
1859        }
1860        return cur;
1861    }
1862
1863    static int[] removeInts(int[] cur, int[] rem) {
1864        if (rem == null) return cur;
1865        if (cur == null) return cur;
1866        final int N = rem.length;
1867        for (int i=0; i<N; i++) {
1868            cur = removeInt(cur, rem[i]);
1869        }
1870        return cur;
1871    }
1872
1873    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1874        if (!sUserManager.exists(userId)) return null;
1875        final PackageSetting ps = (PackageSetting) p.mExtras;
1876        if (ps == null) {
1877            return null;
1878        }
1879        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1880        final PackageUserState state = ps.readUserState(userId);
1881        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1882                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1883                state, userId);
1884    }
1885
1886    @Override
1887    public boolean isPackageAvailable(String packageName, int userId) {
1888        if (!sUserManager.exists(userId)) return false;
1889        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1890        synchronized (mPackages) {
1891            PackageParser.Package p = mPackages.get(packageName);
1892            if (p != null) {
1893                final PackageSetting ps = (PackageSetting) p.mExtras;
1894                if (ps != null) {
1895                    final PackageUserState state = ps.readUserState(userId);
1896                    if (state != null) {
1897                        return PackageParser.isAvailable(state);
1898                    }
1899                }
1900            }
1901        }
1902        return false;
1903    }
1904
1905    @Override
1906    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1907        if (!sUserManager.exists(userId)) return null;
1908        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1909        // reader
1910        synchronized (mPackages) {
1911            PackageParser.Package p = mPackages.get(packageName);
1912            if (DEBUG_PACKAGE_INFO)
1913                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1914            if (p != null) {
1915                return generatePackageInfo(p, flags, userId);
1916            }
1917            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1918                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1919            }
1920        }
1921        return null;
1922    }
1923
1924    @Override
1925    public String[] currentToCanonicalPackageNames(String[] names) {
1926        String[] out = new String[names.length];
1927        // reader
1928        synchronized (mPackages) {
1929            for (int i=names.length-1; i>=0; i--) {
1930                PackageSetting ps = mSettings.mPackages.get(names[i]);
1931                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1932            }
1933        }
1934        return out;
1935    }
1936
1937    @Override
1938    public String[] canonicalToCurrentPackageNames(String[] names) {
1939        String[] out = new String[names.length];
1940        // reader
1941        synchronized (mPackages) {
1942            for (int i=names.length-1; i>=0; i--) {
1943                String cur = mSettings.mRenamedPackages.get(names[i]);
1944                out[i] = cur != null ? cur : names[i];
1945            }
1946        }
1947        return out;
1948    }
1949
1950    @Override
1951    public int getPackageUid(String packageName, int userId) {
1952        if (!sUserManager.exists(userId)) return -1;
1953        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1954        // reader
1955        synchronized (mPackages) {
1956            PackageParser.Package p = mPackages.get(packageName);
1957            if(p != null) {
1958                return UserHandle.getUid(userId, p.applicationInfo.uid);
1959            }
1960            PackageSetting ps = mSettings.mPackages.get(packageName);
1961            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1962                return -1;
1963            }
1964            p = ps.pkg;
1965            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1966        }
1967    }
1968
1969    @Override
1970    public int[] getPackageGids(String packageName) {
1971        // reader
1972        synchronized (mPackages) {
1973            PackageParser.Package p = mPackages.get(packageName);
1974            if (DEBUG_PACKAGE_INFO)
1975                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1976            if (p != null) {
1977                final PackageSetting ps = (PackageSetting)p.mExtras;
1978                return ps.getGids();
1979            }
1980        }
1981        // stupid thing to indicate an error.
1982        return new int[0];
1983    }
1984
1985    static final PermissionInfo generatePermissionInfo(
1986            BasePermission bp, int flags) {
1987        if (bp.perm != null) {
1988            return PackageParser.generatePermissionInfo(bp.perm, flags);
1989        }
1990        PermissionInfo pi = new PermissionInfo();
1991        pi.name = bp.name;
1992        pi.packageName = bp.sourcePackage;
1993        pi.nonLocalizedLabel = bp.name;
1994        pi.protectionLevel = bp.protectionLevel;
1995        return pi;
1996    }
1997
1998    @Override
1999    public PermissionInfo getPermissionInfo(String name, int flags) {
2000        // reader
2001        synchronized (mPackages) {
2002            final BasePermission p = mSettings.mPermissions.get(name);
2003            if (p != null) {
2004                return generatePermissionInfo(p, flags);
2005            }
2006            return null;
2007        }
2008    }
2009
2010    @Override
2011    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2012        // reader
2013        synchronized (mPackages) {
2014            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2015            for (BasePermission p : mSettings.mPermissions.values()) {
2016                if (group == null) {
2017                    if (p.perm == null || p.perm.info.group == null) {
2018                        out.add(generatePermissionInfo(p, flags));
2019                    }
2020                } else {
2021                    if (p.perm != null && group.equals(p.perm.info.group)) {
2022                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2023                    }
2024                }
2025            }
2026
2027            if (out.size() > 0) {
2028                return out;
2029            }
2030            return mPermissionGroups.containsKey(group) ? out : null;
2031        }
2032    }
2033
2034    @Override
2035    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2036        // reader
2037        synchronized (mPackages) {
2038            return PackageParser.generatePermissionGroupInfo(
2039                    mPermissionGroups.get(name), flags);
2040        }
2041    }
2042
2043    @Override
2044    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2045        // reader
2046        synchronized (mPackages) {
2047            final int N = mPermissionGroups.size();
2048            ArrayList<PermissionGroupInfo> out
2049                    = new ArrayList<PermissionGroupInfo>(N);
2050            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2051                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2052            }
2053            return out;
2054        }
2055    }
2056
2057    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2058            int userId) {
2059        if (!sUserManager.exists(userId)) return null;
2060        PackageSetting ps = mSettings.mPackages.get(packageName);
2061        if (ps != null) {
2062            if (ps.pkg == null) {
2063                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2064                        flags, userId);
2065                if (pInfo != null) {
2066                    return pInfo.applicationInfo;
2067                }
2068                return null;
2069            }
2070            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2071                    ps.readUserState(userId), userId);
2072        }
2073        return null;
2074    }
2075
2076    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2077            int userId) {
2078        if (!sUserManager.exists(userId)) return null;
2079        PackageSetting ps = mSettings.mPackages.get(packageName);
2080        if (ps != null) {
2081            PackageParser.Package pkg = ps.pkg;
2082            if (pkg == null) {
2083                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2084                    return null;
2085                }
2086                // Only data remains, so we aren't worried about code paths
2087                pkg = new PackageParser.Package(packageName);
2088                pkg.applicationInfo.packageName = packageName;
2089                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2090                pkg.applicationInfo.dataDir =
2091                        getDataPathForPackage(packageName, 0).getPath();
2092                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2093            }
2094            return generatePackageInfo(pkg, flags, userId);
2095        }
2096        return null;
2097    }
2098
2099    @Override
2100    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2101        if (!sUserManager.exists(userId)) return null;
2102        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2103        // writer
2104        synchronized (mPackages) {
2105            PackageParser.Package p = mPackages.get(packageName);
2106            if (DEBUG_PACKAGE_INFO) Log.v(
2107                    TAG, "getApplicationInfo " + packageName
2108                    + ": " + p);
2109            if (p != null) {
2110                PackageSetting ps = mSettings.mPackages.get(packageName);
2111                if (ps == null) return null;
2112                // Note: isEnabledLP() does not apply here - always return info
2113                return PackageParser.generateApplicationInfo(
2114                        p, flags, ps.readUserState(userId), userId);
2115            }
2116            if ("android".equals(packageName)||"system".equals(packageName)) {
2117                return mAndroidApplication;
2118            }
2119            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2120                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2121            }
2122        }
2123        return null;
2124    }
2125
2126
2127    @Override
2128    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2129        mContext.enforceCallingOrSelfPermission(
2130                android.Manifest.permission.CLEAR_APP_CACHE, null);
2131        // Queue up an async operation since clearing cache may take a little while.
2132        mHandler.post(new Runnable() {
2133            public void run() {
2134                mHandler.removeCallbacks(this);
2135                int retCode = -1;
2136                synchronized (mInstallLock) {
2137                    retCode = mInstaller.freeCache(freeStorageSize);
2138                    if (retCode < 0) {
2139                        Slog.w(TAG, "Couldn't clear application caches");
2140                    }
2141                }
2142                if (observer != null) {
2143                    try {
2144                        observer.onRemoveCompleted(null, (retCode >= 0));
2145                    } catch (RemoteException e) {
2146                        Slog.w(TAG, "RemoveException when invoking call back");
2147                    }
2148                }
2149            }
2150        });
2151    }
2152
2153    @Override
2154    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2155        mContext.enforceCallingOrSelfPermission(
2156                android.Manifest.permission.CLEAR_APP_CACHE, null);
2157        // Queue up an async operation since clearing cache may take a little while.
2158        mHandler.post(new Runnable() {
2159            public void run() {
2160                mHandler.removeCallbacks(this);
2161                int retCode = -1;
2162                synchronized (mInstallLock) {
2163                    retCode = mInstaller.freeCache(freeStorageSize);
2164                    if (retCode < 0) {
2165                        Slog.w(TAG, "Couldn't clear application caches");
2166                    }
2167                }
2168                if(pi != null) {
2169                    try {
2170                        // Callback via pending intent
2171                        int code = (retCode >= 0) ? 1 : 0;
2172                        pi.sendIntent(null, code, null,
2173                                null, null);
2174                    } catch (SendIntentException e1) {
2175                        Slog.i(TAG, "Failed to send pending intent");
2176                    }
2177                }
2178            }
2179        });
2180    }
2181
2182    void freeStorage(long freeStorageSize) throws IOException {
2183        synchronized (mInstallLock) {
2184            if (mInstaller.freeCache(freeStorageSize) < 0) {
2185                throw new IOException("Failed to free enough space");
2186            }
2187        }
2188    }
2189
2190    @Override
2191    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2192        if (!sUserManager.exists(userId)) return null;
2193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mActivities.mActivities.get(component);
2196
2197            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2198            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2199                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2200                if (ps == null) return null;
2201                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2202                        userId);
2203            }
2204            if (mResolveComponentName.equals(component)) {
2205                return mResolveActivity;
2206            }
2207        }
2208        return null;
2209    }
2210
2211    @Override
2212    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2213            String resolvedType) {
2214        synchronized (mPackages) {
2215            PackageParser.Activity a = mActivities.mActivities.get(component);
2216            if (a == null) {
2217                return false;
2218            }
2219            for (int i=0; i<a.intents.size(); i++) {
2220                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2221                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2222                    return true;
2223                }
2224            }
2225            return false;
2226        }
2227    }
2228
2229    @Override
2230    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2231        if (!sUserManager.exists(userId)) return null;
2232        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2233        synchronized (mPackages) {
2234            PackageParser.Activity a = mReceivers.mActivities.get(component);
2235            if (DEBUG_PACKAGE_INFO) Log.v(
2236                TAG, "getReceiverInfo " + component + ": " + a);
2237            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2238                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2239                if (ps == null) return null;
2240                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2241                        userId);
2242            }
2243        }
2244        return null;
2245    }
2246
2247    @Override
2248    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2249        if (!sUserManager.exists(userId)) return null;
2250        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2251        synchronized (mPackages) {
2252            PackageParser.Service s = mServices.mServices.get(component);
2253            if (DEBUG_PACKAGE_INFO) Log.v(
2254                TAG, "getServiceInfo " + component + ": " + s);
2255            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2256                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2257                if (ps == null) return null;
2258                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2259                        userId);
2260            }
2261        }
2262        return null;
2263    }
2264
2265    @Override
2266    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2267        if (!sUserManager.exists(userId)) return null;
2268        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2269        synchronized (mPackages) {
2270            PackageParser.Provider p = mProviders.mProviders.get(component);
2271            if (DEBUG_PACKAGE_INFO) Log.v(
2272                TAG, "getProviderInfo " + component + ": " + p);
2273            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2274                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2275                if (ps == null) return null;
2276                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2277                        userId);
2278            }
2279        }
2280        return null;
2281    }
2282
2283    @Override
2284    public String[] getSystemSharedLibraryNames() {
2285        Set<String> libSet;
2286        synchronized (mPackages) {
2287            libSet = mSharedLibraries.keySet();
2288            int size = libSet.size();
2289            if (size > 0) {
2290                String[] libs = new String[size];
2291                libSet.toArray(libs);
2292                return libs;
2293            }
2294        }
2295        return null;
2296    }
2297
2298    @Override
2299    public FeatureInfo[] getSystemAvailableFeatures() {
2300        Collection<FeatureInfo> featSet;
2301        synchronized (mPackages) {
2302            featSet = mAvailableFeatures.values();
2303            int size = featSet.size();
2304            if (size > 0) {
2305                FeatureInfo[] features = new FeatureInfo[size+1];
2306                featSet.toArray(features);
2307                FeatureInfo fi = new FeatureInfo();
2308                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2309                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2310                features[size] = fi;
2311                return features;
2312            }
2313        }
2314        return null;
2315    }
2316
2317    @Override
2318    public boolean hasSystemFeature(String name) {
2319        synchronized (mPackages) {
2320            return mAvailableFeatures.containsKey(name);
2321        }
2322    }
2323
2324    private void checkValidCaller(int uid, int userId) {
2325        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2326            return;
2327
2328        throw new SecurityException("Caller uid=" + uid
2329                + " is not privileged to communicate with user=" + userId);
2330    }
2331
2332    @Override
2333    public int checkPermission(String permName, String pkgName) {
2334        synchronized (mPackages) {
2335            PackageParser.Package p = mPackages.get(pkgName);
2336            if (p != null && p.mExtras != null) {
2337                PackageSetting ps = (PackageSetting)p.mExtras;
2338                if (ps.sharedUser != null) {
2339                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2340                        return PackageManager.PERMISSION_GRANTED;
2341                    }
2342                } else if (ps.grantedPermissions.contains(permName)) {
2343                    return PackageManager.PERMISSION_GRANTED;
2344                }
2345            }
2346        }
2347        return PackageManager.PERMISSION_DENIED;
2348    }
2349
2350    @Override
2351    public int checkUidPermission(String permName, int uid) {
2352        synchronized (mPackages) {
2353            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2354            if (obj != null) {
2355                GrantedPermissions gp = (GrantedPermissions)obj;
2356                if (gp.grantedPermissions.contains(permName)) {
2357                    return PackageManager.PERMISSION_GRANTED;
2358                }
2359            } else {
2360                HashSet<String> perms = mSystemPermissions.get(uid);
2361                if (perms != null && perms.contains(permName)) {
2362                    return PackageManager.PERMISSION_GRANTED;
2363                }
2364            }
2365        }
2366        return PackageManager.PERMISSION_DENIED;
2367    }
2368
2369    /**
2370     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2371     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2372     * @param message the message to log on security exception
2373     */
2374    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2375            String message) {
2376        if (userId < 0) {
2377            throw new IllegalArgumentException("Invalid userId " + userId);
2378        }
2379        if (userId == UserHandle.getUserId(callingUid)) return;
2380        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2381            if (requireFullPermission) {
2382                mContext.enforceCallingOrSelfPermission(
2383                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2384            } else {
2385                try {
2386                    mContext.enforceCallingOrSelfPermission(
2387                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2388                } catch (SecurityException se) {
2389                    mContext.enforceCallingOrSelfPermission(
2390                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2391                }
2392            }
2393        }
2394    }
2395
2396    private BasePermission findPermissionTreeLP(String permName) {
2397        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2398            if (permName.startsWith(bp.name) &&
2399                    permName.length() > bp.name.length() &&
2400                    permName.charAt(bp.name.length()) == '.') {
2401                return bp;
2402            }
2403        }
2404        return null;
2405    }
2406
2407    private BasePermission checkPermissionTreeLP(String permName) {
2408        if (permName != null) {
2409            BasePermission bp = findPermissionTreeLP(permName);
2410            if (bp != null) {
2411                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2412                    return bp;
2413                }
2414                throw new SecurityException("Calling uid "
2415                        + Binder.getCallingUid()
2416                        + " is not allowed to add to permission tree "
2417                        + bp.name + " owned by uid " + bp.uid);
2418            }
2419        }
2420        throw new SecurityException("No permission tree found for " + permName);
2421    }
2422
2423    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2424        if (s1 == null) {
2425            return s2 == null;
2426        }
2427        if (s2 == null) {
2428            return false;
2429        }
2430        if (s1.getClass() != s2.getClass()) {
2431            return false;
2432        }
2433        return s1.equals(s2);
2434    }
2435
2436    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2437        if (pi1.icon != pi2.icon) return false;
2438        if (pi1.logo != pi2.logo) return false;
2439        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2440        if (!compareStrings(pi1.name, pi2.name)) return false;
2441        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2442        // We'll take care of setting this one.
2443        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2444        // These are not currently stored in settings.
2445        //if (!compareStrings(pi1.group, pi2.group)) return false;
2446        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2447        //if (pi1.labelRes != pi2.labelRes) return false;
2448        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2449        return true;
2450    }
2451
2452    int permissionInfoFootprint(PermissionInfo info) {
2453        int size = info.name.length();
2454        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2455        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2456        return size;
2457    }
2458
2459    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2460        int size = 0;
2461        for (BasePermission perm : mSettings.mPermissions.values()) {
2462            if (perm.uid == tree.uid) {
2463                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2464            }
2465        }
2466        return size;
2467    }
2468
2469    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2470        // We calculate the max size of permissions defined by this uid and throw
2471        // if that plus the size of 'info' would exceed our stated maximum.
2472        if (tree.uid != Process.SYSTEM_UID) {
2473            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2474            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2475                throw new SecurityException("Permission tree size cap exceeded");
2476            }
2477        }
2478    }
2479
2480    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2481        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2482            throw new SecurityException("Label must be specified in permission");
2483        }
2484        BasePermission tree = checkPermissionTreeLP(info.name);
2485        BasePermission bp = mSettings.mPermissions.get(info.name);
2486        boolean added = bp == null;
2487        boolean changed = true;
2488        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2489        if (added) {
2490            enforcePermissionCapLocked(info, tree);
2491            bp = new BasePermission(info.name, tree.sourcePackage,
2492                    BasePermission.TYPE_DYNAMIC);
2493        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2494            throw new SecurityException(
2495                    "Not allowed to modify non-dynamic permission "
2496                    + info.name);
2497        } else {
2498            if (bp.protectionLevel == fixedLevel
2499                    && bp.perm.owner.equals(tree.perm.owner)
2500                    && bp.uid == tree.uid
2501                    && comparePermissionInfos(bp.perm.info, info)) {
2502                changed = false;
2503            }
2504        }
2505        bp.protectionLevel = fixedLevel;
2506        info = new PermissionInfo(info);
2507        info.protectionLevel = fixedLevel;
2508        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2509        bp.perm.info.packageName = tree.perm.info.packageName;
2510        bp.uid = tree.uid;
2511        if (added) {
2512            mSettings.mPermissions.put(info.name, bp);
2513        }
2514        if (changed) {
2515            if (!async) {
2516                mSettings.writeLPr();
2517            } else {
2518                scheduleWriteSettingsLocked();
2519            }
2520        }
2521        return added;
2522    }
2523
2524    @Override
2525    public boolean addPermission(PermissionInfo info) {
2526        synchronized (mPackages) {
2527            return addPermissionLocked(info, false);
2528        }
2529    }
2530
2531    @Override
2532    public boolean addPermissionAsync(PermissionInfo info) {
2533        synchronized (mPackages) {
2534            return addPermissionLocked(info, true);
2535        }
2536    }
2537
2538    @Override
2539    public void removePermission(String name) {
2540        synchronized (mPackages) {
2541            checkPermissionTreeLP(name);
2542            BasePermission bp = mSettings.mPermissions.get(name);
2543            if (bp != null) {
2544                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2545                    throw new SecurityException(
2546                            "Not allowed to modify non-dynamic permission "
2547                            + name);
2548                }
2549                mSettings.mPermissions.remove(name);
2550                mSettings.writeLPr();
2551            }
2552        }
2553    }
2554
2555    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2556        int index = pkg.requestedPermissions.indexOf(bp.name);
2557        if (index == -1) {
2558            throw new SecurityException("Package " + pkg.packageName
2559                    + " has not requested permission " + bp.name);
2560        }
2561        boolean isNormal =
2562                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2563                        == PermissionInfo.PROTECTION_NORMAL);
2564        boolean isDangerous =
2565                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2566                        == PermissionInfo.PROTECTION_DANGEROUS);
2567        boolean isDevelopment =
2568                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2569
2570        if (!isNormal && !isDangerous && !isDevelopment) {
2571            throw new SecurityException("Permission " + bp.name
2572                    + " is not a changeable permission type");
2573        }
2574
2575        if (isNormal || isDangerous) {
2576            if (pkg.requestedPermissionsRequired.get(index)) {
2577                throw new SecurityException("Can't change " + bp.name
2578                        + ". It is required by the application");
2579            }
2580        }
2581    }
2582
2583    @Override
2584    public void grantPermission(String packageName, String permissionName) {
2585        mContext.enforceCallingOrSelfPermission(
2586                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2587        synchronized (mPackages) {
2588            final PackageParser.Package pkg = mPackages.get(packageName);
2589            if (pkg == null) {
2590                throw new IllegalArgumentException("Unknown package: " + packageName);
2591            }
2592            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2593            if (bp == null) {
2594                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2595            }
2596
2597            checkGrantRevokePermissions(pkg, bp);
2598
2599            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2600            if (ps == null) {
2601                return;
2602            }
2603            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2604            if (gp.grantedPermissions.add(permissionName)) {
2605                if (ps.haveGids) {
2606                    gp.gids = appendInts(gp.gids, bp.gids);
2607                }
2608                mSettings.writeLPr();
2609            }
2610        }
2611    }
2612
2613    @Override
2614    public void revokePermission(String packageName, String permissionName) {
2615        int changedAppId = -1;
2616
2617        synchronized (mPackages) {
2618            final PackageParser.Package pkg = mPackages.get(packageName);
2619            if (pkg == null) {
2620                throw new IllegalArgumentException("Unknown package: " + packageName);
2621            }
2622            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2623                mContext.enforceCallingOrSelfPermission(
2624                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2625            }
2626            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2627            if (bp == null) {
2628                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2629            }
2630
2631            checkGrantRevokePermissions(pkg, bp);
2632
2633            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2634            if (ps == null) {
2635                return;
2636            }
2637            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2638            if (gp.grantedPermissions.remove(permissionName)) {
2639                gp.grantedPermissions.remove(permissionName);
2640                if (ps.haveGids) {
2641                    gp.gids = removeInts(gp.gids, bp.gids);
2642                }
2643                mSettings.writeLPr();
2644                changedAppId = ps.appId;
2645            }
2646        }
2647
2648        if (changedAppId >= 0) {
2649            // We changed the perm on someone, kill its processes.
2650            IActivityManager am = ActivityManagerNative.getDefault();
2651            if (am != null) {
2652                final int callingUserId = UserHandle.getCallingUserId();
2653                final long ident = Binder.clearCallingIdentity();
2654                try {
2655                    //XXX we should only revoke for the calling user's app permissions,
2656                    // but for now we impact all users.
2657                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2658                    //        "revoke " + permissionName);
2659                    int[] users = sUserManager.getUserIds();
2660                    for (int user : users) {
2661                        am.killUid(UserHandle.getUid(user, changedAppId),
2662                                "revoke " + permissionName);
2663                    }
2664                } catch (RemoteException e) {
2665                } finally {
2666                    Binder.restoreCallingIdentity(ident);
2667                }
2668            }
2669        }
2670    }
2671
2672    @Override
2673    public boolean isProtectedBroadcast(String actionName) {
2674        synchronized (mPackages) {
2675            return mProtectedBroadcasts.contains(actionName);
2676        }
2677    }
2678
2679    @Override
2680    public int checkSignatures(String pkg1, String pkg2) {
2681        synchronized (mPackages) {
2682            final PackageParser.Package p1 = mPackages.get(pkg1);
2683            final PackageParser.Package p2 = mPackages.get(pkg2);
2684            if (p1 == null || p1.mExtras == null
2685                    || p2 == null || p2.mExtras == null) {
2686                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2687            }
2688            return compareSignatures(p1.mSignatures, p2.mSignatures);
2689        }
2690    }
2691
2692    @Override
2693    public int checkUidSignatures(int uid1, int uid2) {
2694        // Map to base uids.
2695        uid1 = UserHandle.getAppId(uid1);
2696        uid2 = UserHandle.getAppId(uid2);
2697        // reader
2698        synchronized (mPackages) {
2699            Signature[] s1;
2700            Signature[] s2;
2701            Object obj = mSettings.getUserIdLPr(uid1);
2702            if (obj != null) {
2703                if (obj instanceof SharedUserSetting) {
2704                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2705                } else if (obj instanceof PackageSetting) {
2706                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2707                } else {
2708                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2709                }
2710            } else {
2711                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2712            }
2713            obj = mSettings.getUserIdLPr(uid2);
2714            if (obj != null) {
2715                if (obj instanceof SharedUserSetting) {
2716                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2717                } else if (obj instanceof PackageSetting) {
2718                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2719                } else {
2720                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2721                }
2722            } else {
2723                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2724            }
2725            return compareSignatures(s1, s2);
2726        }
2727    }
2728
2729    /**
2730     * Compares two sets of signatures. Returns:
2731     * <br />
2732     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2733     * <br />
2734     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2735     * <br />
2736     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2737     * <br />
2738     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2739     * <br />
2740     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2741     */
2742    static int compareSignatures(Signature[] s1, Signature[] s2) {
2743        if (s1 == null) {
2744            return s2 == null
2745                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2746                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2747        }
2748
2749        if (s2 == null) {
2750            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2751        }
2752
2753        if (s1.length != s2.length) {
2754            return PackageManager.SIGNATURE_NO_MATCH;
2755        }
2756
2757        // Since both signature sets are of size 1, we can compare without HashSets.
2758        if (s1.length == 1) {
2759            return s1[0].equals(s2[0]) ?
2760                    PackageManager.SIGNATURE_MATCH :
2761                    PackageManager.SIGNATURE_NO_MATCH;
2762        }
2763
2764        HashSet<Signature> set1 = new HashSet<Signature>();
2765        for (Signature sig : s1) {
2766            set1.add(sig);
2767        }
2768        HashSet<Signature> set2 = new HashSet<Signature>();
2769        for (Signature sig : s2) {
2770            set2.add(sig);
2771        }
2772        // Make sure s2 contains all signatures in s1.
2773        if (set1.equals(set2)) {
2774            return PackageManager.SIGNATURE_MATCH;
2775        }
2776        return PackageManager.SIGNATURE_NO_MATCH;
2777    }
2778
2779    /**
2780     * If the database version for this type of package (internal storage or
2781     * external storage) is less than the version where package signatures
2782     * were updated, return true.
2783     */
2784    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2785        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2786                DatabaseVersion.SIGNATURE_END_ENTITY))
2787                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2788                        DatabaseVersion.SIGNATURE_END_ENTITY));
2789    }
2790
2791    /**
2792     * Used for backward compatibility to make sure any packages with
2793     * certificate chains get upgraded to the new style. {@code existingSigs}
2794     * will be in the old format (since they were stored on disk from before the
2795     * system upgrade) and {@code scannedSigs} will be in the newer format.
2796     */
2797    private int compareSignaturesCompat(PackageSignatures existingSigs,
2798            PackageParser.Package scannedPkg) {
2799        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2800            return PackageManager.SIGNATURE_NO_MATCH;
2801        }
2802
2803        HashSet<Signature> existingSet = new HashSet<Signature>();
2804        for (Signature sig : existingSigs.mSignatures) {
2805            existingSet.add(sig);
2806        }
2807        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2808        for (Signature sig : scannedPkg.mSignatures) {
2809            try {
2810                Signature[] chainSignatures = sig.getChainSignatures();
2811                for (Signature chainSig : chainSignatures) {
2812                    scannedCompatSet.add(chainSig);
2813                }
2814            } catch (CertificateEncodingException e) {
2815                scannedCompatSet.add(sig);
2816            }
2817        }
2818        /*
2819         * Make sure the expanded scanned set contains all signatures in the
2820         * existing one.
2821         */
2822        if (scannedCompatSet.equals(existingSet)) {
2823            // Migrate the old signatures to the new scheme.
2824            existingSigs.assignSignatures(scannedPkg.mSignatures);
2825            // The new KeySets will be re-added later in the scanning process.
2826            mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName);
2827            return PackageManager.SIGNATURE_MATCH;
2828        }
2829        return PackageManager.SIGNATURE_NO_MATCH;
2830    }
2831
2832    @Override
2833    public String[] getPackagesForUid(int uid) {
2834        uid = UserHandle.getAppId(uid);
2835        // reader
2836        synchronized (mPackages) {
2837            Object obj = mSettings.getUserIdLPr(uid);
2838            if (obj instanceof SharedUserSetting) {
2839                final SharedUserSetting sus = (SharedUserSetting) obj;
2840                final int N = sus.packages.size();
2841                final String[] res = new String[N];
2842                final Iterator<PackageSetting> it = sus.packages.iterator();
2843                int i = 0;
2844                while (it.hasNext()) {
2845                    res[i++] = it.next().name;
2846                }
2847                return res;
2848            } else if (obj instanceof PackageSetting) {
2849                final PackageSetting ps = (PackageSetting) obj;
2850                return new String[] { ps.name };
2851            }
2852        }
2853        return null;
2854    }
2855
2856    @Override
2857    public String getNameForUid(int uid) {
2858        // reader
2859        synchronized (mPackages) {
2860            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2861            if (obj instanceof SharedUserSetting) {
2862                final SharedUserSetting sus = (SharedUserSetting) obj;
2863                return sus.name + ":" + sus.userId;
2864            } else if (obj instanceof PackageSetting) {
2865                final PackageSetting ps = (PackageSetting) obj;
2866                return ps.name;
2867            }
2868        }
2869        return null;
2870    }
2871
2872    @Override
2873    public int getUidForSharedUser(String sharedUserName) {
2874        if(sharedUserName == null) {
2875            return -1;
2876        }
2877        // reader
2878        synchronized (mPackages) {
2879            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2880            if (suid == null) {
2881                return -1;
2882            }
2883            return suid.userId;
2884        }
2885    }
2886
2887    @Override
2888    public int getFlagsForUid(int uid) {
2889        synchronized (mPackages) {
2890            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2891            if (obj instanceof SharedUserSetting) {
2892                final SharedUserSetting sus = (SharedUserSetting) obj;
2893                return sus.pkgFlags;
2894            } else if (obj instanceof PackageSetting) {
2895                final PackageSetting ps = (PackageSetting) obj;
2896                return ps.pkgFlags;
2897            }
2898        }
2899        return 0;
2900    }
2901
2902    @Override
2903    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2904            int flags, int userId) {
2905        if (!sUserManager.exists(userId)) return null;
2906        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2907        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2908        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2909    }
2910
2911    @Override
2912    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2913            IntentFilter filter, int match, ComponentName activity) {
2914        final int userId = UserHandle.getCallingUserId();
2915        if (DEBUG_PREFERRED) {
2916            Log.v(TAG, "setLastChosenActivity intent=" + intent
2917                + " resolvedType=" + resolvedType
2918                + " flags=" + flags
2919                + " filter=" + filter
2920                + " match=" + match
2921                + " activity=" + activity);
2922            filter.dump(new PrintStreamPrinter(System.out), "    ");
2923        }
2924        intent.setComponent(null);
2925        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2926        // Find any earlier preferred or last chosen entries and nuke them
2927        findPreferredActivity(intent, resolvedType,
2928                flags, query, 0, false, true, false, userId);
2929        // Add the new activity as the last chosen for this filter
2930        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2931    }
2932
2933    @Override
2934    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2935        final int userId = UserHandle.getCallingUserId();
2936        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2937        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2938        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2939                false, false, false, userId);
2940    }
2941
2942    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2943            int flags, List<ResolveInfo> query, int userId) {
2944        if (query != null) {
2945            final int N = query.size();
2946            if (N == 1) {
2947                return query.get(0);
2948            } else if (N > 1) {
2949                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2950                // If there is more than one activity with the same priority,
2951                // then let the user decide between them.
2952                ResolveInfo r0 = query.get(0);
2953                ResolveInfo r1 = query.get(1);
2954                if (DEBUG_INTENT_MATCHING || debug) {
2955                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2956                            + r1.activityInfo.name + "=" + r1.priority);
2957                }
2958                // If the first activity has a higher priority, or a different
2959                // default, then it is always desireable to pick it.
2960                if (r0.priority != r1.priority
2961                        || r0.preferredOrder != r1.preferredOrder
2962                        || r0.isDefault != r1.isDefault) {
2963                    return query.get(0);
2964                }
2965                // If we have saved a preference for a preferred activity for
2966                // this Intent, use that.
2967                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2968                        flags, query, r0.priority, true, false, debug, userId);
2969                if (ri != null) {
2970                    return ri;
2971                }
2972                if (userId != 0) {
2973                    ri = new ResolveInfo(mResolveInfo);
2974                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2975                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2976                            ri.activityInfo.applicationInfo);
2977                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2978                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2979                    return ri;
2980                }
2981                return mResolveInfo;
2982            }
2983        }
2984        return null;
2985    }
2986
2987    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2988            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2989        final int N = query.size();
2990        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2991                .get(userId);
2992        // Get the list of persistent preferred activities that handle the intent
2993        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2994        List<PersistentPreferredActivity> pprefs = ppir != null
2995                ? ppir.queryIntent(intent, resolvedType,
2996                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2997                : null;
2998        if (pprefs != null && pprefs.size() > 0) {
2999            final int M = pprefs.size();
3000            for (int i=0; i<M; i++) {
3001                final PersistentPreferredActivity ppa = pprefs.get(i);
3002                if (DEBUG_PREFERRED || debug) {
3003                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3004                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3005                            + "\n  component=" + ppa.mComponent);
3006                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3007                }
3008                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3009                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3010                if (DEBUG_PREFERRED || debug) {
3011                    Slog.v(TAG, "Found persistent preferred activity:");
3012                    if (ai != null) {
3013                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3014                    } else {
3015                        Slog.v(TAG, "  null");
3016                    }
3017                }
3018                if (ai == null) {
3019                    // This previously registered persistent preferred activity
3020                    // component is no longer known. Ignore it and do NOT remove it.
3021                    continue;
3022                }
3023                for (int j=0; j<N; j++) {
3024                    final ResolveInfo ri = query.get(j);
3025                    if (!ri.activityInfo.applicationInfo.packageName
3026                            .equals(ai.applicationInfo.packageName)) {
3027                        continue;
3028                    }
3029                    if (!ri.activityInfo.name.equals(ai.name)) {
3030                        continue;
3031                    }
3032                    //  Found a persistent preference that can handle the intent.
3033                    if (DEBUG_PREFERRED || debug) {
3034                        Slog.v(TAG, "Returning persistent preferred activity: " +
3035                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3036                    }
3037                    return ri;
3038                }
3039            }
3040        }
3041        return null;
3042    }
3043
3044    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3045            List<ResolveInfo> query, int priority, boolean always,
3046            boolean removeMatches, boolean debug, int userId) {
3047        if (!sUserManager.exists(userId)) return null;
3048        // writer
3049        synchronized (mPackages) {
3050            if (intent.getSelector() != null) {
3051                intent = intent.getSelector();
3052            }
3053            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3054
3055            // Try to find a matching persistent preferred activity.
3056            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3057                    debug, userId);
3058
3059            // If a persistent preferred activity matched, use it.
3060            if (pri != null) {
3061                return pri;
3062            }
3063
3064            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3065            // Get the list of preferred activities that handle the intent
3066            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3067            List<PreferredActivity> prefs = pir != null
3068                    ? pir.queryIntent(intent, resolvedType,
3069                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3070                    : null;
3071            if (prefs != null && prefs.size() > 0) {
3072                // First figure out how good the original match set is.
3073                // We will only allow preferred activities that came
3074                // from the same match quality.
3075                int match = 0;
3076
3077                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3078
3079                final int N = query.size();
3080                for (int j=0; j<N; j++) {
3081                    final ResolveInfo ri = query.get(j);
3082                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3083                            + ": 0x" + Integer.toHexString(match));
3084                    if (ri.match > match) {
3085                        match = ri.match;
3086                    }
3087                }
3088
3089                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3090                        + Integer.toHexString(match));
3091
3092                match &= IntentFilter.MATCH_CATEGORY_MASK;
3093                final int M = prefs.size();
3094                for (int i=0; i<M; i++) {
3095                    final PreferredActivity pa = prefs.get(i);
3096                    if (DEBUG_PREFERRED || debug) {
3097                        Slog.v(TAG, "Checking PreferredActivity ds="
3098                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3099                                + "\n  component=" + pa.mPref.mComponent);
3100                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3101                    }
3102                    if (pa.mPref.mMatch != match) {
3103                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3104                                + Integer.toHexString(pa.mPref.mMatch));
3105                        continue;
3106                    }
3107                    // If it's not an "always" type preferred activity and that's what we're
3108                    // looking for, skip it.
3109                    if (always && !pa.mPref.mAlways) {
3110                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3111                        continue;
3112                    }
3113                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3114                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3115                    if (DEBUG_PREFERRED || debug) {
3116                        Slog.v(TAG, "Found preferred activity:");
3117                        if (ai != null) {
3118                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3119                        } else {
3120                            Slog.v(TAG, "  null");
3121                        }
3122                    }
3123                    if (ai == null) {
3124                        // This previously registered preferred activity
3125                        // component is no longer known.  Most likely an update
3126                        // to the app was installed and in the new version this
3127                        // component no longer exists.  Clean it up by removing
3128                        // it from the preferred activities list, and skip it.
3129                        Slog.w(TAG, "Removing dangling preferred activity: "
3130                                + pa.mPref.mComponent);
3131                        pir.removeFilter(pa);
3132                        continue;
3133                    }
3134                    for (int j=0; j<N; j++) {
3135                        final ResolveInfo ri = query.get(j);
3136                        if (!ri.activityInfo.applicationInfo.packageName
3137                                .equals(ai.applicationInfo.packageName)) {
3138                            continue;
3139                        }
3140                        if (!ri.activityInfo.name.equals(ai.name)) {
3141                            continue;
3142                        }
3143
3144                        if (removeMatches) {
3145                            pir.removeFilter(pa);
3146                            if (DEBUG_PREFERRED) {
3147                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3148                            }
3149                            break;
3150                        }
3151
3152                        // Okay we found a previously set preferred or last chosen app.
3153                        // If the result set is different from when this
3154                        // was created, we need to clear it and re-ask the
3155                        // user their preference, if we're looking for an "always" type entry.
3156                        if (always && !pa.mPref.sameSet(query, priority)) {
3157                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3158                                    + intent + " type " + resolvedType);
3159                            if (DEBUG_PREFERRED) {
3160                                Slog.v(TAG, "Removing preferred activity since set changed "
3161                                        + pa.mPref.mComponent);
3162                            }
3163                            pir.removeFilter(pa);
3164                            // Re-add the filter as a "last chosen" entry (!always)
3165                            PreferredActivity lastChosen = new PreferredActivity(
3166                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3167                            pir.addFilter(lastChosen);
3168                            mSettings.writePackageRestrictionsLPr(userId);
3169                            return null;
3170                        }
3171
3172                        // Yay! Either the set matched or we're looking for the last chosen
3173                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3174                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3175                        mSettings.writePackageRestrictionsLPr(userId);
3176                        return ri;
3177                    }
3178                }
3179            }
3180            mSettings.writePackageRestrictionsLPr(userId);
3181        }
3182        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3183        return null;
3184    }
3185
3186    /*
3187     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3188     */
3189    @Override
3190    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3191            int targetUserId) {
3192        mContext.enforceCallingOrSelfPermission(
3193                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3194        List<CrossProfileIntentFilter> matches =
3195                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3196        if (matches != null) {
3197            int size = matches.size();
3198            for (int i = 0; i < size; i++) {
3199                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3200            }
3201        }
3202
3203        ArrayList<String> packageNames = null;
3204        SparseArray<ArrayList<String>> fromSource =
3205                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3206        if (fromSource != null) {
3207            packageNames = fromSource.get(targetUserId);
3208        }
3209        if (packageNames.contains(intent.getPackage())) {
3210            return true;
3211        }
3212        // We need the package name, so we try to resolve with the loosest flags possible
3213        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3214                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3215        int count = resolveInfos.size();
3216        for (int i = 0; i < count; i++) {
3217            ResolveInfo resolveInfo = resolveInfos.get(i);
3218            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3219                return true;
3220            }
3221        }
3222        return false;
3223    }
3224
3225    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3226            String resolvedType, int userId) {
3227        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3228        if (resolver != null) {
3229            return resolver.queryIntent(intent, resolvedType, false, userId);
3230        }
3231        return null;
3232    }
3233
3234    @Override
3235    public List<ResolveInfo> queryIntentActivities(Intent intent,
3236            String resolvedType, int flags, int userId) {
3237        if (!sUserManager.exists(userId)) return Collections.emptyList();
3238        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3239        ComponentName comp = intent.getComponent();
3240        if (comp == null) {
3241            if (intent.getSelector() != null) {
3242                intent = intent.getSelector();
3243                comp = intent.getComponent();
3244            }
3245        }
3246
3247        if (comp != null) {
3248            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3249            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3250            if (ai != null) {
3251                final ResolveInfo ri = new ResolveInfo();
3252                ri.activityInfo = ai;
3253                list.add(ri);
3254            }
3255            return list;
3256        }
3257
3258        // reader
3259        synchronized (mPackages) {
3260            final String pkgName = intent.getPackage();
3261            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3262            if (pkgName == null) {
3263                ResolveInfo resolveInfo = null;
3264                if (queryCrossProfile) {
3265                    // Check if the intent needs to be forwarded to another user for this package
3266                    ArrayList<ResolveInfo> crossProfileResult =
3267                            queryIntentActivitiesCrossProfilePackage(
3268                                    intent, resolvedType, flags, userId);
3269                    if (!crossProfileResult.isEmpty()) {
3270                        // Skip the current profile
3271                        return crossProfileResult;
3272                    }
3273                    List<CrossProfileIntentFilter> matchingFilters =
3274                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3275                    // Check for results that need to skip the current profile.
3276                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3277                            resolvedType, flags, userId);
3278                    if (resolveInfo != null) {
3279                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3280                        result.add(resolveInfo);
3281                        return result;
3282                    }
3283                    // Check for cross profile results.
3284                    resolveInfo = queryCrossProfileIntents(
3285                            matchingFilters, intent, resolvedType, flags, userId);
3286                }
3287                // Check for results in the current profile.
3288                List<ResolveInfo> result = mActivities.queryIntent(
3289                        intent, resolvedType, flags, userId);
3290                if (resolveInfo != null) {
3291                    result.add(resolveInfo);
3292                }
3293                return result;
3294            }
3295            final PackageParser.Package pkg = mPackages.get(pkgName);
3296            if (pkg != null) {
3297                if (queryCrossProfile) {
3298                    ArrayList<ResolveInfo> crossProfileResult =
3299                            queryIntentActivitiesCrossProfilePackage(
3300                                    intent, resolvedType, flags, userId, pkg, pkgName);
3301                    if (!crossProfileResult.isEmpty()) {
3302                        // Skip the current profile
3303                        return crossProfileResult;
3304                    }
3305                }
3306                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3307                        pkg.activities, userId);
3308            }
3309            return new ArrayList<ResolveInfo>();
3310        }
3311    }
3312
3313    private ResolveInfo querySkipCurrentProfileIntents(
3314            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3315            int flags, int sourceUserId) {
3316        if (matchingFilters != null) {
3317            int size = matchingFilters.size();
3318            for (int i = 0; i < size; i ++) {
3319                CrossProfileIntentFilter filter = matchingFilters.get(i);
3320                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3321                    // Checking if there are activities in the target user that can handle the
3322                    // intent.
3323                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3324                            flags, sourceUserId);
3325                    if (resolveInfo != null) {
3326                        return resolveInfo;
3327                    }
3328                }
3329            }
3330        }
3331        return null;
3332    }
3333
3334    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3335            Intent intent, String resolvedType, int flags, int userId) {
3336        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3337        SparseArray<ArrayList<String>> sourceForwardingInfo =
3338                mSettings.mCrossProfilePackageInfo.get(userId);
3339        if (sourceForwardingInfo != null) {
3340            int NI = sourceForwardingInfo.size();
3341            for (int i = 0; i < NI; i++) {
3342                int targetUserId = sourceForwardingInfo.keyAt(i);
3343                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3344                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3345                        intent, resolvedType, flags, targetUserId);
3346                int NJ = resolveInfos.size();
3347                for (int j = 0; j < NJ; j++) {
3348                    ResolveInfo resolveInfo = resolveInfos.get(j);
3349                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3350                        matchingResolveInfos.add(createForwardingResolveInfo(
3351                                resolveInfo.filter, userId, targetUserId));
3352                    }
3353                }
3354            }
3355        }
3356        return matchingResolveInfos;
3357    }
3358
3359    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3360            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3361            String packageName) {
3362        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3363        SparseArray<ArrayList<String>> sourceForwardingInfo =
3364                mSettings.mCrossProfilePackageInfo.get(userId);
3365        if (sourceForwardingInfo != null) {
3366            int NI = sourceForwardingInfo.size();
3367            for (int i = 0; i < NI; i++) {
3368                int targetUserId = sourceForwardingInfo.keyAt(i);
3369                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3370                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3371                            intent, resolvedType, flags, pkg.activities, targetUserId);
3372                    int NJ = resolveInfos.size();
3373                    for (int j = 0; j < NJ; j++) {
3374                        ResolveInfo resolveInfo = resolveInfos.get(j);
3375                        matchingResolveInfos.add(createForwardingResolveInfo(
3376                                resolveInfo.filter, userId, targetUserId));
3377                    }
3378                }
3379            }
3380        }
3381        return matchingResolveInfos;
3382    }
3383
3384    // Return matching ResolveInfo if any for skip current profile intent filters.
3385    private ResolveInfo queryCrossProfileIntents(
3386            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3387            int flags, int sourceUserId) {
3388        if (matchingFilters != null) {
3389            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3390            // match the same intent. For performance reasons, it is better not to
3391            // run queryIntent twice for the same userId
3392            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3393            int size = matchingFilters.size();
3394            for (int i = 0; i < size; i++) {
3395                CrossProfileIntentFilter filter = matchingFilters.get(i);
3396                int targetUserId = filter.getTargetUserId();
3397                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3398                        && !alreadyTriedUserIds.get(targetUserId)) {
3399                    // Checking if there are activities in the target user that can handle the
3400                    // intent.
3401                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3402                            flags, sourceUserId);
3403                    if (resolveInfo != null) return resolveInfo;
3404                    alreadyTriedUserIds.put(targetUserId, true);
3405                }
3406            }
3407        }
3408        return null;
3409    }
3410
3411    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3412            String resolvedType, int flags, int sourceUserId) {
3413        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3414                resolvedType, flags, filter.getTargetUserId());
3415        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3416            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3417        }
3418        return null;
3419    }
3420
3421    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3422            int sourceUserId, int targetUserId) {
3423        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3424        String className;
3425        if (targetUserId == UserHandle.USER_OWNER) {
3426            className = FORWARD_INTENT_TO_USER_OWNER;
3427        } else {
3428            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3429        }
3430        ComponentName forwardingActivityComponentName = new ComponentName(
3431                mAndroidApplication.packageName, className);
3432        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3433                sourceUserId);
3434        if (targetUserId == UserHandle.USER_OWNER) {
3435            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3436            forwardingResolveInfo.noResourceId = true;
3437        }
3438        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3439        forwardingResolveInfo.priority = 0;
3440        forwardingResolveInfo.preferredOrder = 0;
3441        forwardingResolveInfo.match = 0;
3442        forwardingResolveInfo.isDefault = true;
3443        forwardingResolveInfo.filter = filter;
3444        forwardingResolveInfo.targetUserId = targetUserId;
3445        return forwardingResolveInfo;
3446    }
3447
3448    @Override
3449    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3450            Intent[] specifics, String[] specificTypes, Intent intent,
3451            String resolvedType, int flags, int userId) {
3452        if (!sUserManager.exists(userId)) return Collections.emptyList();
3453        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3454                "query intent activity options");
3455        final String resultsAction = intent.getAction();
3456
3457        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3458                | PackageManager.GET_RESOLVED_FILTER, userId);
3459
3460        if (DEBUG_INTENT_MATCHING) {
3461            Log.v(TAG, "Query " + intent + ": " + results);
3462        }
3463
3464        int specificsPos = 0;
3465        int N;
3466
3467        // todo: note that the algorithm used here is O(N^2).  This
3468        // isn't a problem in our current environment, but if we start running
3469        // into situations where we have more than 5 or 10 matches then this
3470        // should probably be changed to something smarter...
3471
3472        // First we go through and resolve each of the specific items
3473        // that were supplied, taking care of removing any corresponding
3474        // duplicate items in the generic resolve list.
3475        if (specifics != null) {
3476            for (int i=0; i<specifics.length; i++) {
3477                final Intent sintent = specifics[i];
3478                if (sintent == null) {
3479                    continue;
3480                }
3481
3482                if (DEBUG_INTENT_MATCHING) {
3483                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3484                }
3485
3486                String action = sintent.getAction();
3487                if (resultsAction != null && resultsAction.equals(action)) {
3488                    // If this action was explicitly requested, then don't
3489                    // remove things that have it.
3490                    action = null;
3491                }
3492
3493                ResolveInfo ri = null;
3494                ActivityInfo ai = null;
3495
3496                ComponentName comp = sintent.getComponent();
3497                if (comp == null) {
3498                    ri = resolveIntent(
3499                        sintent,
3500                        specificTypes != null ? specificTypes[i] : null,
3501                            flags, userId);
3502                    if (ri == null) {
3503                        continue;
3504                    }
3505                    if (ri == mResolveInfo) {
3506                        // ACK!  Must do something better with this.
3507                    }
3508                    ai = ri.activityInfo;
3509                    comp = new ComponentName(ai.applicationInfo.packageName,
3510                            ai.name);
3511                } else {
3512                    ai = getActivityInfo(comp, flags, userId);
3513                    if (ai == null) {
3514                        continue;
3515                    }
3516                }
3517
3518                // Look for any generic query activities that are duplicates
3519                // of this specific one, and remove them from the results.
3520                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3521                N = results.size();
3522                int j;
3523                for (j=specificsPos; j<N; j++) {
3524                    ResolveInfo sri = results.get(j);
3525                    if ((sri.activityInfo.name.equals(comp.getClassName())
3526                            && sri.activityInfo.applicationInfo.packageName.equals(
3527                                    comp.getPackageName()))
3528                        || (action != null && sri.filter.matchAction(action))) {
3529                        results.remove(j);
3530                        if (DEBUG_INTENT_MATCHING) Log.v(
3531                            TAG, "Removing duplicate item from " + j
3532                            + " due to specific " + specificsPos);
3533                        if (ri == null) {
3534                            ri = sri;
3535                        }
3536                        j--;
3537                        N--;
3538                    }
3539                }
3540
3541                // Add this specific item to its proper place.
3542                if (ri == null) {
3543                    ri = new ResolveInfo();
3544                    ri.activityInfo = ai;
3545                }
3546                results.add(specificsPos, ri);
3547                ri.specificIndex = i;
3548                specificsPos++;
3549            }
3550        }
3551
3552        // Now we go through the remaining generic results and remove any
3553        // duplicate actions that are found here.
3554        N = results.size();
3555        for (int i=specificsPos; i<N-1; i++) {
3556            final ResolveInfo rii = results.get(i);
3557            if (rii.filter == null) {
3558                continue;
3559            }
3560
3561            // Iterate over all of the actions of this result's intent
3562            // filter...  typically this should be just one.
3563            final Iterator<String> it = rii.filter.actionsIterator();
3564            if (it == null) {
3565                continue;
3566            }
3567            while (it.hasNext()) {
3568                final String action = it.next();
3569                if (resultsAction != null && resultsAction.equals(action)) {
3570                    // If this action was explicitly requested, then don't
3571                    // remove things that have it.
3572                    continue;
3573                }
3574                for (int j=i+1; j<N; j++) {
3575                    final ResolveInfo rij = results.get(j);
3576                    if (rij.filter != null && rij.filter.hasAction(action)) {
3577                        results.remove(j);
3578                        if (DEBUG_INTENT_MATCHING) Log.v(
3579                            TAG, "Removing duplicate item from " + j
3580                            + " due to action " + action + " at " + i);
3581                        j--;
3582                        N--;
3583                    }
3584                }
3585            }
3586
3587            // If the caller didn't request filter information, drop it now
3588            // so we don't have to marshall/unmarshall it.
3589            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3590                rii.filter = null;
3591            }
3592        }
3593
3594        // Filter out the caller activity if so requested.
3595        if (caller != null) {
3596            N = results.size();
3597            for (int i=0; i<N; i++) {
3598                ActivityInfo ainfo = results.get(i).activityInfo;
3599                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3600                        && caller.getClassName().equals(ainfo.name)) {
3601                    results.remove(i);
3602                    break;
3603                }
3604            }
3605        }
3606
3607        // If the caller didn't request filter information,
3608        // drop them now so we don't have to
3609        // marshall/unmarshall it.
3610        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3611            N = results.size();
3612            for (int i=0; i<N; i++) {
3613                results.get(i).filter = null;
3614            }
3615        }
3616
3617        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3618        return results;
3619    }
3620
3621    @Override
3622    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3623            int userId) {
3624        if (!sUserManager.exists(userId)) return Collections.emptyList();
3625        ComponentName comp = intent.getComponent();
3626        if (comp == null) {
3627            if (intent.getSelector() != null) {
3628                intent = intent.getSelector();
3629                comp = intent.getComponent();
3630            }
3631        }
3632        if (comp != null) {
3633            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3634            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3635            if (ai != null) {
3636                ResolveInfo ri = new ResolveInfo();
3637                ri.activityInfo = ai;
3638                list.add(ri);
3639            }
3640            return list;
3641        }
3642
3643        // reader
3644        synchronized (mPackages) {
3645            String pkgName = intent.getPackage();
3646            if (pkgName == null) {
3647                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3648            }
3649            final PackageParser.Package pkg = mPackages.get(pkgName);
3650            if (pkg != null) {
3651                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3652                        userId);
3653            }
3654            return null;
3655        }
3656    }
3657
3658    @Override
3659    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3660        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3661        if (!sUserManager.exists(userId)) return null;
3662        if (query != null) {
3663            if (query.size() >= 1) {
3664                // If there is more than one service with the same priority,
3665                // just arbitrarily pick the first one.
3666                return query.get(0);
3667            }
3668        }
3669        return null;
3670    }
3671
3672    @Override
3673    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3674            int userId) {
3675        if (!sUserManager.exists(userId)) return Collections.emptyList();
3676        ComponentName comp = intent.getComponent();
3677        if (comp == null) {
3678            if (intent.getSelector() != null) {
3679                intent = intent.getSelector();
3680                comp = intent.getComponent();
3681            }
3682        }
3683        if (comp != null) {
3684            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3685            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3686            if (si != null) {
3687                final ResolveInfo ri = new ResolveInfo();
3688                ri.serviceInfo = si;
3689                list.add(ri);
3690            }
3691            return list;
3692        }
3693
3694        // reader
3695        synchronized (mPackages) {
3696            String pkgName = intent.getPackage();
3697            if (pkgName == null) {
3698                return mServices.queryIntent(intent, resolvedType, flags, userId);
3699            }
3700            final PackageParser.Package pkg = mPackages.get(pkgName);
3701            if (pkg != null) {
3702                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3703                        userId);
3704            }
3705            return null;
3706        }
3707    }
3708
3709    @Override
3710    public List<ResolveInfo> queryIntentContentProviders(
3711            Intent intent, String resolvedType, int flags, int userId) {
3712        if (!sUserManager.exists(userId)) return Collections.emptyList();
3713        ComponentName comp = intent.getComponent();
3714        if (comp == null) {
3715            if (intent.getSelector() != null) {
3716                intent = intent.getSelector();
3717                comp = intent.getComponent();
3718            }
3719        }
3720        if (comp != null) {
3721            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3722            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3723            if (pi != null) {
3724                final ResolveInfo ri = new ResolveInfo();
3725                ri.providerInfo = pi;
3726                list.add(ri);
3727            }
3728            return list;
3729        }
3730
3731        // reader
3732        synchronized (mPackages) {
3733            String pkgName = intent.getPackage();
3734            if (pkgName == null) {
3735                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3736            }
3737            final PackageParser.Package pkg = mPackages.get(pkgName);
3738            if (pkg != null) {
3739                return mProviders.queryIntentForPackage(
3740                        intent, resolvedType, flags, pkg.providers, userId);
3741            }
3742            return null;
3743        }
3744    }
3745
3746    @Override
3747    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3748        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3749
3750        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3751
3752        // writer
3753        synchronized (mPackages) {
3754            ArrayList<PackageInfo> list;
3755            if (listUninstalled) {
3756                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3757                for (PackageSetting ps : mSettings.mPackages.values()) {
3758                    PackageInfo pi;
3759                    if (ps.pkg != null) {
3760                        pi = generatePackageInfo(ps.pkg, flags, userId);
3761                    } else {
3762                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3763                    }
3764                    if (pi != null) {
3765                        list.add(pi);
3766                    }
3767                }
3768            } else {
3769                list = new ArrayList<PackageInfo>(mPackages.size());
3770                for (PackageParser.Package p : mPackages.values()) {
3771                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3772                    if (pi != null) {
3773                        list.add(pi);
3774                    }
3775                }
3776            }
3777
3778            return new ParceledListSlice<PackageInfo>(list);
3779        }
3780    }
3781
3782    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3783            String[] permissions, boolean[] tmp, int flags, int userId) {
3784        int numMatch = 0;
3785        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3786        for (int i=0; i<permissions.length; i++) {
3787            if (gp.grantedPermissions.contains(permissions[i])) {
3788                tmp[i] = true;
3789                numMatch++;
3790            } else {
3791                tmp[i] = false;
3792            }
3793        }
3794        if (numMatch == 0) {
3795            return;
3796        }
3797        PackageInfo pi;
3798        if (ps.pkg != null) {
3799            pi = generatePackageInfo(ps.pkg, flags, userId);
3800        } else {
3801            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3802        }
3803        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3804            if (numMatch == permissions.length) {
3805                pi.requestedPermissions = permissions;
3806            } else {
3807                pi.requestedPermissions = new String[numMatch];
3808                numMatch = 0;
3809                for (int i=0; i<permissions.length; i++) {
3810                    if (tmp[i]) {
3811                        pi.requestedPermissions[numMatch] = permissions[i];
3812                        numMatch++;
3813                    }
3814                }
3815            }
3816        }
3817        list.add(pi);
3818    }
3819
3820    @Override
3821    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3822            String[] permissions, int flags, int userId) {
3823        if (!sUserManager.exists(userId)) return null;
3824        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3825
3826        // writer
3827        synchronized (mPackages) {
3828            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3829            boolean[] tmpBools = new boolean[permissions.length];
3830            if (listUninstalled) {
3831                for (PackageSetting ps : mSettings.mPackages.values()) {
3832                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3833                }
3834            } else {
3835                for (PackageParser.Package pkg : mPackages.values()) {
3836                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3837                    if (ps != null) {
3838                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3839                                userId);
3840                    }
3841                }
3842            }
3843
3844            return new ParceledListSlice<PackageInfo>(list);
3845        }
3846    }
3847
3848    @Override
3849    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3850        if (!sUserManager.exists(userId)) return null;
3851        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3852
3853        // writer
3854        synchronized (mPackages) {
3855            ArrayList<ApplicationInfo> list;
3856            if (listUninstalled) {
3857                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3858                for (PackageSetting ps : mSettings.mPackages.values()) {
3859                    ApplicationInfo ai;
3860                    if (ps.pkg != null) {
3861                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3862                                ps.readUserState(userId), userId);
3863                    } else {
3864                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3865                    }
3866                    if (ai != null) {
3867                        list.add(ai);
3868                    }
3869                }
3870            } else {
3871                list = new ArrayList<ApplicationInfo>(mPackages.size());
3872                for (PackageParser.Package p : mPackages.values()) {
3873                    if (p.mExtras != null) {
3874                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3875                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3876                        if (ai != null) {
3877                            list.add(ai);
3878                        }
3879                    }
3880                }
3881            }
3882
3883            return new ParceledListSlice<ApplicationInfo>(list);
3884        }
3885    }
3886
3887    public List<ApplicationInfo> getPersistentApplications(int flags) {
3888        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3889
3890        // reader
3891        synchronized (mPackages) {
3892            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3893            final int userId = UserHandle.getCallingUserId();
3894            while (i.hasNext()) {
3895                final PackageParser.Package p = i.next();
3896                if (p.applicationInfo != null
3897                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3898                        && (!mSafeMode || isSystemApp(p))) {
3899                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3900                    if (ps != null) {
3901                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3902                                ps.readUserState(userId), userId);
3903                        if (ai != null) {
3904                            finalList.add(ai);
3905                        }
3906                    }
3907                }
3908            }
3909        }
3910
3911        return finalList;
3912    }
3913
3914    @Override
3915    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3916        if (!sUserManager.exists(userId)) return null;
3917        // reader
3918        synchronized (mPackages) {
3919            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3920            PackageSetting ps = provider != null
3921                    ? mSettings.mPackages.get(provider.owner.packageName)
3922                    : null;
3923            return ps != null
3924                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3925                    && (!mSafeMode || (provider.info.applicationInfo.flags
3926                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3927                    ? PackageParser.generateProviderInfo(provider, flags,
3928                            ps.readUserState(userId), userId)
3929                    : null;
3930        }
3931    }
3932
3933    /**
3934     * @deprecated
3935     */
3936    @Deprecated
3937    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3938        // reader
3939        synchronized (mPackages) {
3940            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3941                    .entrySet().iterator();
3942            final int userId = UserHandle.getCallingUserId();
3943            while (i.hasNext()) {
3944                Map.Entry<String, PackageParser.Provider> entry = i.next();
3945                PackageParser.Provider p = entry.getValue();
3946                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3947
3948                if (ps != null && p.syncable
3949                        && (!mSafeMode || (p.info.applicationInfo.flags
3950                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3951                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3952                            ps.readUserState(userId), userId);
3953                    if (info != null) {
3954                        outNames.add(entry.getKey());
3955                        outInfo.add(info);
3956                    }
3957                }
3958            }
3959        }
3960    }
3961
3962    @Override
3963    public List<ProviderInfo> queryContentProviders(String processName,
3964            int uid, int flags) {
3965        ArrayList<ProviderInfo> finalList = null;
3966        // reader
3967        synchronized (mPackages) {
3968            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3969            final int userId = processName != null ?
3970                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3971            while (i.hasNext()) {
3972                final PackageParser.Provider p = i.next();
3973                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3974                if (ps != null && p.info.authority != null
3975                        && (processName == null
3976                                || (p.info.processName.equals(processName)
3977                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3978                        && mSettings.isEnabledLPr(p.info, flags, userId)
3979                        && (!mSafeMode
3980                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3981                    if (finalList == null) {
3982                        finalList = new ArrayList<ProviderInfo>(3);
3983                    }
3984                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3985                            ps.readUserState(userId), userId);
3986                    if (info != null) {
3987                        finalList.add(info);
3988                    }
3989                }
3990            }
3991        }
3992
3993        if (finalList != null) {
3994            Collections.sort(finalList, mProviderInitOrderSorter);
3995        }
3996
3997        return finalList;
3998    }
3999
4000    @Override
4001    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4002            int flags) {
4003        // reader
4004        synchronized (mPackages) {
4005            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4006            return PackageParser.generateInstrumentationInfo(i, flags);
4007        }
4008    }
4009
4010    @Override
4011    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4012            int flags) {
4013        ArrayList<InstrumentationInfo> finalList =
4014            new ArrayList<InstrumentationInfo>();
4015
4016        // reader
4017        synchronized (mPackages) {
4018            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4019            while (i.hasNext()) {
4020                final PackageParser.Instrumentation p = i.next();
4021                if (targetPackage == null
4022                        || targetPackage.equals(p.info.targetPackage)) {
4023                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4024                            flags);
4025                    if (ii != null) {
4026                        finalList.add(ii);
4027                    }
4028                }
4029            }
4030        }
4031
4032        return finalList;
4033    }
4034
4035    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4036        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4037        if (overlays == null) {
4038            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4039            return;
4040        }
4041        for (PackageParser.Package opkg : overlays.values()) {
4042            // Not much to do if idmap fails: we already logged the error
4043            // and we certainly don't want to abort installation of pkg simply
4044            // because an overlay didn't fit properly. For these reasons,
4045            // ignore the return value of createIdmapForPackagePairLI.
4046            createIdmapForPackagePairLI(pkg, opkg);
4047        }
4048    }
4049
4050    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4051            PackageParser.Package opkg) {
4052        if (!opkg.mTrustedOverlay) {
4053            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4054                    opkg.baseCodePath + ": overlay not trusted");
4055            return false;
4056        }
4057        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4058        if (overlaySet == null) {
4059            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4060                    opkg.baseCodePath + " but target package has no known overlays");
4061            return false;
4062        }
4063        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4064        // TODO: generate idmap for split APKs
4065        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4066            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4067                    + opkg.baseCodePath);
4068            return false;
4069        }
4070        PackageParser.Package[] overlayArray =
4071            overlaySet.values().toArray(new PackageParser.Package[0]);
4072        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4073            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4074                return p1.mOverlayPriority - p2.mOverlayPriority;
4075            }
4076        };
4077        Arrays.sort(overlayArray, cmp);
4078
4079        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4080        int i = 0;
4081        for (PackageParser.Package p : overlayArray) {
4082            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4083        }
4084        return true;
4085    }
4086
4087    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4088        final File[] files = dir.listFiles();
4089        if (ArrayUtils.isEmpty(files)) {
4090            Log.d(TAG, "No files in app dir " + dir);
4091            return;
4092        }
4093
4094        if (DEBUG_PACKAGE_SCANNING) {
4095            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4096                    + " flags=0x" + Integer.toHexString(flags));
4097        }
4098
4099        for (File file : files) {
4100            final boolean isPackage = isApkFile(file) || file.isDirectory();
4101            if (!isPackage) {
4102                // Ignore entries which are not apk's
4103                continue;
4104            }
4105            PackageParser.Package pkg = scanPackageLI(file,
4106                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4107            // Don't mess around with apps in system partition.
4108            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4109                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4110                // Delete the apk
4111                Slog.w(TAG, "Cleaning up failed install of " + file);
4112                file.delete();
4113            }
4114        }
4115    }
4116
4117    private static File getSettingsProblemFile() {
4118        File dataDir = Environment.getDataDirectory();
4119        File systemDir = new File(dataDir, "system");
4120        File fname = new File(systemDir, "uiderrors.txt");
4121        return fname;
4122    }
4123
4124    static void reportSettingsProblem(int priority, String msg) {
4125        try {
4126            File fname = getSettingsProblemFile();
4127            FileOutputStream out = new FileOutputStream(fname, true);
4128            PrintWriter pw = new FastPrintWriter(out);
4129            SimpleDateFormat formatter = new SimpleDateFormat();
4130            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4131            pw.println(dateString + ": " + msg);
4132            pw.close();
4133            FileUtils.setPermissions(
4134                    fname.toString(),
4135                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4136                    -1, -1);
4137        } catch (java.io.IOException e) {
4138        }
4139        Slog.println(priority, TAG, msg);
4140    }
4141
4142    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4143            PackageParser.Package pkg, File srcFile, int parseFlags) {
4144        if (ps != null
4145                && ps.codePath.equals(srcFile)
4146                && ps.timeStamp == srcFile.lastModified()
4147                && !isCompatSignatureUpdateNeeded(pkg)) {
4148            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4149            if (ps.signatures.mSignatures != null
4150                    && ps.signatures.mSignatures.length != 0
4151                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4152                // Optimization: reuse the existing cached certificates
4153                // if the package appears to be unchanged.
4154                pkg.mSignatures = ps.signatures.mSignatures;
4155                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4156                pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId);
4157                return true;
4158            }
4159
4160            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4161        } else {
4162            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4163        }
4164
4165        try {
4166            pp.collectCertificates(pkg, parseFlags);
4167            pp.collectManifestDigest(pkg);
4168        } catch (PackageParserException e) {
4169            Slog.e(TAG, "Failed during collect: " + e);
4170            mLastScanError = e.error;
4171            return false;
4172        }
4173        return true;
4174    }
4175
4176    /*
4177     *  Scan a package and return the newly parsed package.
4178     *  Returns null in case of errors and the error code is stored in mLastScanError
4179     */
4180    private PackageParser.Package scanPackageLI(File scanFile,
4181            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4182        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4183        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4184        parseFlags |= mDefParseFlags;
4185        PackageParser pp = new PackageParser();
4186        pp.setSeparateProcesses(mSeparateProcesses);
4187        pp.setOnlyCoreApps(mOnlyCore);
4188        pp.setDisplayMetrics(mMetrics);
4189
4190        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4191            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4192        }
4193
4194        final PackageParser.Package pkg;
4195        try {
4196            pkg = pp.parsePackage(scanFile, parseFlags);
4197        } catch (PackageParserException e) {
4198            Slog.e(TAG, "Failed during scan: " + e);
4199            mLastScanError = e.error;
4200            return null;
4201        }
4202
4203        PackageSetting ps = null;
4204        PackageSetting updatedPkg;
4205        // reader
4206        synchronized (mPackages) {
4207            // Look to see if we already know about this package.
4208            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4209            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4210                // This package has been renamed to its original name.  Let's
4211                // use that.
4212                ps = mSettings.peekPackageLPr(oldName);
4213            }
4214            // If there was no original package, see one for the real package name.
4215            if (ps == null) {
4216                ps = mSettings.peekPackageLPr(pkg.packageName);
4217            }
4218            // Check to see if this package could be hiding/updating a system
4219            // package.  Must look for it either under the original or real
4220            // package name depending on our state.
4221            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4222            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4223        }
4224        boolean updatedPkgBetter = false;
4225        // First check if this is a system package that may involve an update
4226        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4227            if (ps != null && !ps.codePath.equals(scanFile)) {
4228                // The path has changed from what was last scanned...  check the
4229                // version of the new path against what we have stored to determine
4230                // what to do.
4231                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4232                if (pkg.mVersionCode < ps.versionCode) {
4233                    // The system package has been updated and the code path does not match
4234                    // Ignore entry. Skip it.
4235                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4236                            + " ignored: updated version " + ps.versionCode
4237                            + " better than this " + pkg.mVersionCode);
4238                    if (!updatedPkg.codePath.equals(scanFile)) {
4239                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4240                                + ps.name + " changing from " + updatedPkg.codePathString
4241                                + " to " + scanFile);
4242                        updatedPkg.codePath = scanFile;
4243                        updatedPkg.codePathString = scanFile.toString();
4244                        // This is the point at which we know that the system-disk APK
4245                        // for this package has moved during a reboot (e.g. due to an OTA),
4246                        // so we need to reevaluate it for privilege policy.
4247                        if (locationIsPrivileged(scanFile)) {
4248                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4249                        }
4250                    }
4251                    updatedPkg.pkg = pkg;
4252                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4253                    return null;
4254                } else {
4255                    // The current app on the system partition is better than
4256                    // what we have updated to on the data partition; switch
4257                    // back to the system partition version.
4258                    // At this point, its safely assumed that package installation for
4259                    // apps in system partition will go through. If not there won't be a working
4260                    // version of the app
4261                    // writer
4262                    synchronized (mPackages) {
4263                        // Just remove the loaded entries from package lists.
4264                        mPackages.remove(ps.name);
4265                    }
4266                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4267                            + "reverting from " + ps.codePathString
4268                            + ": new version " + pkg.mVersionCode
4269                            + " better than installed " + ps.versionCode);
4270
4271                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4272                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4273                            getAppInstructionSetFromSettings(ps));
4274                    synchronized (mInstallLock) {
4275                        args.cleanUpResourcesLI();
4276                    }
4277                    synchronized (mPackages) {
4278                        mSettings.enableSystemPackageLPw(ps.name);
4279                    }
4280                    updatedPkgBetter = true;
4281                }
4282            }
4283        }
4284
4285        if (updatedPkg != null) {
4286            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4287            // initially
4288            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4289
4290            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4291            // flag set initially
4292            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4293                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4294            }
4295        }
4296        // Verify certificates against what was last scanned
4297        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4298            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4299            return null;
4300        }
4301
4302        /*
4303         * A new system app appeared, but we already had a non-system one of the
4304         * same name installed earlier.
4305         */
4306        boolean shouldHideSystemApp = false;
4307        if (updatedPkg == null && ps != null
4308                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4309            /*
4310             * Check to make sure the signatures match first. If they don't,
4311             * wipe the installed application and its data.
4312             */
4313            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4314                    != PackageManager.SIGNATURE_MATCH) {
4315                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4316                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4317                ps = null;
4318            } else {
4319                /*
4320                 * If the newly-added system app is an older version than the
4321                 * already installed version, hide it. It will be scanned later
4322                 * and re-added like an update.
4323                 */
4324                if (pkg.mVersionCode < ps.versionCode) {
4325                    shouldHideSystemApp = true;
4326                } else {
4327                    /*
4328                     * The newly found system app is a newer version that the
4329                     * one previously installed. Simply remove the
4330                     * already-installed application and replace it with our own
4331                     * while keeping the application data.
4332                     */
4333                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4334                            + ps.codePathString + ": new version " + pkg.mVersionCode
4335                            + " better than installed " + ps.versionCode);
4336                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4337                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4338                            getAppInstructionSetFromSettings(ps));
4339                    synchronized (mInstallLock) {
4340                        args.cleanUpResourcesLI();
4341                    }
4342                }
4343            }
4344        }
4345
4346        // The apk is forward locked (not public) if its code and resources
4347        // are kept in different files. (except for app in either system or
4348        // vendor path).
4349        // TODO grab this value from PackageSettings
4350        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4351            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4352                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4353            }
4354        }
4355
4356        // TODO: extend to support forward-locked splits
4357        String resourcePath = null;
4358        String baseResourcePath = null;
4359        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4360            if (ps != null && ps.resourcePathString != null) {
4361                resourcePath = ps.resourcePathString;
4362                baseResourcePath = ps.resourcePathString;
4363            } else {
4364                // Should not happen at all. Just log an error.
4365                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4366            }
4367        } else {
4368            resourcePath = pkg.codePath;
4369            baseResourcePath = pkg.baseCodePath;
4370        }
4371
4372        // Set application objects path explicitly.
4373        pkg.applicationInfo.setCodePath(pkg.codePath);
4374        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4375        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4376        pkg.applicationInfo.setResourcePath(resourcePath);
4377        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4378        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4379
4380        // Note that we invoke the following method only if we are about to unpack an application
4381        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4382                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4383
4384        /*
4385         * If the system app should be overridden by a previously installed
4386         * data, hide the system app now and let the /data/app scan pick it up
4387         * again.
4388         */
4389        if (shouldHideSystemApp) {
4390            synchronized (mPackages) {
4391                /*
4392                 * We have to grant systems permissions before we hide, because
4393                 * grantPermissions will assume the package update is trying to
4394                 * expand its permissions.
4395                 */
4396                grantPermissionsLPw(pkg, true);
4397                mSettings.disableSystemPackageLPw(pkg.packageName);
4398            }
4399        }
4400
4401        return scannedPkg;
4402    }
4403
4404    private static String fixProcessName(String defProcessName,
4405            String processName, int uid) {
4406        if (processName == null) {
4407            return defProcessName;
4408        }
4409        return processName;
4410    }
4411
4412    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4413        if (pkgSetting.signatures.mSignatures != null) {
4414            // Already existing package. Make sure signatures match
4415            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4416                    == PackageManager.SIGNATURE_MATCH;
4417            if (!match) {
4418                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4419                        == PackageManager.SIGNATURE_MATCH;
4420            }
4421            if (!match) {
4422                Slog.e(TAG, "Package " + pkg.packageName
4423                        + " signatures do not match the previously installed version; ignoring!");
4424                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4425                return false;
4426            }
4427        }
4428
4429        // Check for shared user signatures
4430        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4431            // Already existing package. Make sure signatures match
4432            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4433                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4434            if (!match) {
4435                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4436                        == PackageManager.SIGNATURE_MATCH;
4437            }
4438            if (!match) {
4439                Slog.e(TAG, "Package " + pkg.packageName
4440                        + " has no signatures that match those in shared user "
4441                        + pkgSetting.sharedUser.name + "; ignoring!");
4442                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4443                return false;
4444            }
4445        }
4446        return true;
4447    }
4448
4449    /**
4450     * Enforces that only the system UID or root's UID can call a method exposed
4451     * via Binder.
4452     *
4453     * @param message used as message if SecurityException is thrown
4454     * @throws SecurityException if the caller is not system or root
4455     */
4456    private static final void enforceSystemOrRoot(String message) {
4457        final int uid = Binder.getCallingUid();
4458        if (uid != Process.SYSTEM_UID && uid != 0) {
4459            throw new SecurityException(message);
4460        }
4461    }
4462
4463    @Override
4464    public void performBootDexOpt() {
4465        enforceSystemOrRoot("Only the system can request dexopt be performed");
4466
4467        final HashSet<PackageParser.Package> pkgs;
4468        synchronized (mPackages) {
4469            pkgs = mDeferredDexOpt;
4470            mDeferredDexOpt = null;
4471        }
4472
4473        if (pkgs != null) {
4474            // Filter out packages that aren't recently used.
4475            //
4476            // The exception is first boot of a non-eng device, which
4477            // should do a full dexopt.
4478            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4479            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4480                // TODO: add a property to control this?
4481                long dexOptLRUThresholdInMinutes;
4482                if (eng) {
4483                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4484                } else {
4485                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4486                }
4487                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4488
4489                int total = pkgs.size();
4490                int skipped = 0;
4491                long now = System.currentTimeMillis();
4492                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4493                    PackageParser.Package pkg = i.next();
4494                    long then = pkg.mLastPackageUsageTimeInMills;
4495                    if (then + dexOptLRUThresholdInMills < now) {
4496                        if (DEBUG_DEXOPT) {
4497                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4498                                  ((then == 0) ? "never" : new Date(then)));
4499                        }
4500                        i.remove();
4501                        skipped++;
4502                    }
4503                }
4504                if (DEBUG_DEXOPT) {
4505                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4506                }
4507            }
4508
4509            int i = 0;
4510            for (PackageParser.Package pkg : pkgs) {
4511                i++;
4512                if (DEBUG_DEXOPT) {
4513                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4514                          + ": " + pkg.packageName);
4515                }
4516                if (!isFirstBoot()) {
4517                    try {
4518                        ActivityManagerNative.getDefault().showBootMessage(
4519                                mContext.getResources().getString(
4520                                        R.string.android_upgrading_apk,
4521                                        i, pkgs.size()), true);
4522                    } catch (RemoteException e) {
4523                    }
4524                }
4525                PackageParser.Package p = pkg;
4526                synchronized (mInstallLock) {
4527                    if (p.mDexOptNeeded) {
4528                        performDexOptLI(p, false /* force dex */, false /* defer */,
4529                                true /* include dependencies */);
4530                    }
4531                }
4532            }
4533        }
4534    }
4535
4536    @Override
4537    public boolean performDexOpt(String packageName) {
4538        enforceSystemOrRoot("Only the system can request dexopt be performed");
4539        return performDexOpt(packageName, true);
4540    }
4541
4542    public boolean performDexOpt(String packageName, boolean updateUsage) {
4543
4544        PackageParser.Package p;
4545        synchronized (mPackages) {
4546            p = mPackages.get(packageName);
4547            if (p == null) {
4548                return false;
4549            }
4550            if (updateUsage) {
4551                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4552            }
4553            mPackageUsage.write(false);
4554            if (!p.mDexOptNeeded) {
4555                return false;
4556            }
4557        }
4558
4559        synchronized (mInstallLock) {
4560            return performDexOptLI(p, false /* force dex */, false /* defer */,
4561                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4562        }
4563    }
4564
4565    public HashSet<String> getPackagesThatNeedDexOpt() {
4566        HashSet<String> pkgs = null;
4567        synchronized (mPackages) {
4568            for (PackageParser.Package p : mPackages.values()) {
4569                if (DEBUG_DEXOPT) {
4570                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4571                }
4572                if (!p.mDexOptNeeded) {
4573                    continue;
4574                }
4575                if (pkgs == null) {
4576                    pkgs = new HashSet<String>();
4577                }
4578                pkgs.add(p.packageName);
4579            }
4580        }
4581        return pkgs;
4582    }
4583
4584    public void shutdown() {
4585        mPackageUsage.write(true);
4586    }
4587
4588    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4589             boolean forceDex, boolean defer, HashSet<String> done) {
4590        for (int i=0; i<libs.size(); i++) {
4591            PackageParser.Package libPkg;
4592            String libName;
4593            synchronized (mPackages) {
4594                libName = libs.get(i);
4595                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4596                if (lib != null && lib.apk != null) {
4597                    libPkg = mPackages.get(lib.apk);
4598                } else {
4599                    libPkg = null;
4600                }
4601            }
4602            if (libPkg != null && !done.contains(libName)) {
4603                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4604            }
4605        }
4606    }
4607
4608    static final int DEX_OPT_SKIPPED = 0;
4609    static final int DEX_OPT_PERFORMED = 1;
4610    static final int DEX_OPT_DEFERRED = 2;
4611    static final int DEX_OPT_FAILED = -1;
4612
4613    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4614            boolean forceDex, boolean defer, HashSet<String> done) {
4615        final String instructionSet = instructionSetOverride != null ?
4616                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4617
4618        if (done != null) {
4619            done.add(pkg.packageName);
4620            if (pkg.usesLibraries != null) {
4621                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4622            }
4623            if (pkg.usesOptionalLibraries != null) {
4624                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4625            }
4626        }
4627
4628        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
4629            final Collection<String> paths = pkg.getAllCodePaths();
4630            for (String path : paths) {
4631                try {
4632                    boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4633                            pkg.packageName, instructionSet, defer);
4634                    // There are three basic cases here:
4635                    // 1.) we need to dexopt, either because we are forced or it is needed
4636                    // 2.) we are defering a needed dexopt
4637                    // 3.) we are skipping an unneeded dexopt
4638                    if (forceDex || (!defer && isDexOptNeededInternal)) {
4639                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4640                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4641                        int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4642                                                    pkg.packageName, instructionSet);
4643                        // Note that we ran dexopt, since rerunning will
4644                        // probably just result in an error again.
4645                        pkg.mDexOptNeeded = false;
4646                        if (ret < 0) {
4647                            return DEX_OPT_FAILED;
4648                        }
4649                        return DEX_OPT_PERFORMED;
4650                    }
4651                    if (defer && isDexOptNeededInternal) {
4652                        if (mDeferredDexOpt == null) {
4653                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4654                        }
4655                        mDeferredDexOpt.add(pkg);
4656                        return DEX_OPT_DEFERRED;
4657                    }
4658                    pkg.mDexOptNeeded = false;
4659                    return DEX_OPT_SKIPPED;
4660                } catch (FileNotFoundException e) {
4661                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4662                    return DEX_OPT_FAILED;
4663                } catch (IOException e) {
4664                    Slog.w(TAG, "IOException reading apk: " + path, e);
4665                    return DEX_OPT_FAILED;
4666                } catch (StaleDexCacheError e) {
4667                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4668                    return DEX_OPT_FAILED;
4669                } catch (Exception e) {
4670                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4671                    return DEX_OPT_FAILED;
4672                }
4673            }
4674        }
4675        return DEX_OPT_SKIPPED;
4676    }
4677
4678    private String getAppInstructionSet(ApplicationInfo info) {
4679        String instructionSet = getPreferredInstructionSet();
4680
4681        if (info.cpuAbi != null) {
4682            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4683        }
4684
4685        return instructionSet;
4686    }
4687
4688    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4689        String instructionSet = getPreferredInstructionSet();
4690
4691        if (ps.cpuAbiString != null) {
4692            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4693        }
4694
4695        return instructionSet;
4696    }
4697
4698    private static String getPreferredInstructionSet() {
4699        if (sPreferredInstructionSet == null) {
4700            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4701        }
4702
4703        return sPreferredInstructionSet;
4704    }
4705
4706    private static List<String> getAllInstructionSets() {
4707        final String[] allAbis = Build.SUPPORTED_ABIS;
4708        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4709
4710        for (String abi : allAbis) {
4711            final String instructionSet = VMRuntime.getInstructionSet(abi);
4712            if (!allInstructionSets.contains(instructionSet)) {
4713                allInstructionSets.add(instructionSet);
4714            }
4715        }
4716
4717        return allInstructionSets;
4718    }
4719
4720    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4721            boolean inclDependencies) {
4722        HashSet<String> done;
4723        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4724            done = new HashSet<String>();
4725            done.add(pkg.packageName);
4726        } else {
4727            done = null;
4728        }
4729        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4730    }
4731
4732    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4733        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4734            Slog.w(TAG, "Unable to update from " + oldPkg.name
4735                    + " to " + newPkg.packageName
4736                    + ": old package not in system partition");
4737            return false;
4738        } else if (mPackages.get(oldPkg.name) != null) {
4739            Slog.w(TAG, "Unable to update from " + oldPkg.name
4740                    + " to " + newPkg.packageName
4741                    + ": old package still exists");
4742            return false;
4743        }
4744        return true;
4745    }
4746
4747    File getDataPathForUser(int userId) {
4748        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4749    }
4750
4751    private File getDataPathForPackage(String packageName, int userId) {
4752        /*
4753         * Until we fully support multiple users, return the directory we
4754         * previously would have. The PackageManagerTests will need to be
4755         * revised when this is changed back..
4756         */
4757        if (userId == 0) {
4758            return new File(mAppDataDir, packageName);
4759        } else {
4760            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4761                + File.separator + packageName);
4762        }
4763    }
4764
4765    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4766        int[] users = sUserManager.getUserIds();
4767        int res = mInstaller.install(packageName, uid, uid, seinfo);
4768        if (res < 0) {
4769            return res;
4770        }
4771        for (int user : users) {
4772            if (user != 0) {
4773                res = mInstaller.createUserData(packageName,
4774                        UserHandle.getUid(user, uid), user, seinfo);
4775                if (res < 0) {
4776                    return res;
4777                }
4778            }
4779        }
4780        return res;
4781    }
4782
4783    private int removeDataDirsLI(String packageName) {
4784        int[] users = sUserManager.getUserIds();
4785        int res = 0;
4786        for (int user : users) {
4787            int resInner = mInstaller.remove(packageName, user);
4788            if (resInner < 0) {
4789                res = resInner;
4790            }
4791        }
4792
4793        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4794        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4795        if (!nativeLibraryFile.delete()) {
4796            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4797        }
4798
4799        return res;
4800    }
4801
4802    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4803            PackageParser.Package changingLib) {
4804        if (file.path != null) {
4805            usesLibraryFiles.add(file.path);
4806            return;
4807        }
4808        PackageParser.Package p = mPackages.get(file.apk);
4809        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4810            // If we are doing this while in the middle of updating a library apk,
4811            // then we need to make sure to use that new apk for determining the
4812            // dependencies here.  (We haven't yet finished committing the new apk
4813            // to the package manager state.)
4814            if (p == null || p.packageName.equals(changingLib.packageName)) {
4815                p = changingLib;
4816            }
4817        }
4818        if (p != null) {
4819            usesLibraryFiles.addAll(p.getAllCodePaths());
4820        }
4821    }
4822
4823    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4824            PackageParser.Package changingLib) {
4825        // We might be upgrading from a version of the platform that did not
4826        // provide per-package native library directories for system apps.
4827        // Fix that up here.
4828        if (isSystemApp(pkg)) {
4829            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4830            setInternalAppNativeLibraryPath(pkg, ps);
4831        }
4832
4833        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4834            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4835            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4836            for (int i=0; i<N; i++) {
4837                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4838                if (file == null) {
4839                    Slog.e(TAG, "Package " + pkg.packageName
4840                            + " requires unavailable shared library "
4841                            + pkg.usesLibraries.get(i) + "; failing!");
4842                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4843                    return false;
4844                }
4845                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4846            }
4847            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4848            for (int i=0; i<N; i++) {
4849                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4850                if (file == null) {
4851                    Slog.w(TAG, "Package " + pkg.packageName
4852                            + " desires unavailable shared library "
4853                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4854                } else {
4855                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4856                }
4857            }
4858            N = usesLibraryFiles.size();
4859            if (N > 0) {
4860                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4861            } else {
4862                pkg.usesLibraryFiles = null;
4863            }
4864        }
4865        return true;
4866    }
4867
4868    private static boolean hasString(List<String> list, List<String> which) {
4869        if (list == null) {
4870            return false;
4871        }
4872        for (int i=list.size()-1; i>=0; i--) {
4873            for (int j=which.size()-1; j>=0; j--) {
4874                if (which.get(j).equals(list.get(i))) {
4875                    return true;
4876                }
4877            }
4878        }
4879        return false;
4880    }
4881
4882    private void updateAllSharedLibrariesLPw() {
4883        for (PackageParser.Package pkg : mPackages.values()) {
4884            updateSharedLibrariesLPw(pkg, null);
4885        }
4886    }
4887
4888    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4889            PackageParser.Package changingPkg) {
4890        ArrayList<PackageParser.Package> res = null;
4891        for (PackageParser.Package pkg : mPackages.values()) {
4892            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4893                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4894                if (res == null) {
4895                    res = new ArrayList<PackageParser.Package>();
4896                }
4897                res.add(pkg);
4898                updateSharedLibrariesLPw(pkg, changingPkg);
4899            }
4900        }
4901        return res;
4902    }
4903
4904    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4905            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4906        final File scanFile = new File(pkg.codePath);
4907        if (pkg.applicationInfo.getCodePath() == null ||
4908                pkg.applicationInfo.getResourcePath() == null) {
4909            // Bail out. The resource and code paths haven't been set.
4910            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4911            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4912            return null;
4913        }
4914
4915        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4916            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4917        }
4918
4919        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4920            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4921        }
4922
4923        if (mCustomResolverComponentName != null &&
4924                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4925            setUpCustomResolverActivity(pkg);
4926        }
4927
4928        if (pkg.packageName.equals("android")) {
4929            synchronized (mPackages) {
4930                if (mAndroidApplication != null) {
4931                    Slog.w(TAG, "*************************************************");
4932                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4933                    Slog.w(TAG, " file=" + scanFile);
4934                    Slog.w(TAG, "*************************************************");
4935                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4936                    return null;
4937                }
4938
4939                // Set up information for our fall-back user intent resolution activity.
4940                mPlatformPackage = pkg;
4941                pkg.mVersionCode = mSdkVersion;
4942                mAndroidApplication = pkg.applicationInfo;
4943
4944                if (!mResolverReplaced) {
4945                    mResolveActivity.applicationInfo = mAndroidApplication;
4946                    mResolveActivity.name = ResolverActivity.class.getName();
4947                    mResolveActivity.packageName = mAndroidApplication.packageName;
4948                    mResolveActivity.processName = "system:ui";
4949                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4950                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4951                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4952                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4953                    mResolveActivity.exported = true;
4954                    mResolveActivity.enabled = true;
4955                    mResolveInfo.activityInfo = mResolveActivity;
4956                    mResolveInfo.priority = 0;
4957                    mResolveInfo.preferredOrder = 0;
4958                    mResolveInfo.match = 0;
4959                    mResolveComponentName = new ComponentName(
4960                            mAndroidApplication.packageName, mResolveActivity.name);
4961                }
4962            }
4963        }
4964
4965        if (DEBUG_PACKAGE_SCANNING) {
4966            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4967                Log.d(TAG, "Scanning package " + pkg.packageName);
4968        }
4969
4970        if (mPackages.containsKey(pkg.packageName)
4971                || mSharedLibraries.containsKey(pkg.packageName)) {
4972            Slog.w(TAG, "Application package " + pkg.packageName
4973                    + " already installed.  Skipping duplicate.");
4974            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4975            return null;
4976        }
4977
4978        // Initialize package source and resource directories
4979        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
4980        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
4981
4982        SharedUserSetting suid = null;
4983        PackageSetting pkgSetting = null;
4984
4985        if (!isSystemApp(pkg)) {
4986            // Only system apps can use these features.
4987            pkg.mOriginalPackages = null;
4988            pkg.mRealPackage = null;
4989            pkg.mAdoptPermissions = null;
4990        }
4991
4992        // writer
4993        synchronized (mPackages) {
4994            if (pkg.mSharedUserId != null) {
4995                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4996                if (suid == null) {
4997                    Slog.w(TAG, "Creating application package " + pkg.packageName
4998                            + " for shared user failed");
4999                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5000                    return null;
5001                }
5002                if (DEBUG_PACKAGE_SCANNING) {
5003                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5004                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5005                                + "): packages=" + suid.packages);
5006                }
5007            }
5008
5009            // Check if we are renaming from an original package name.
5010            PackageSetting origPackage = null;
5011            String realName = null;
5012            if (pkg.mOriginalPackages != null) {
5013                // This package may need to be renamed to a previously
5014                // installed name.  Let's check on that...
5015                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5016                if (pkg.mOriginalPackages.contains(renamed)) {
5017                    // This package had originally been installed as the
5018                    // original name, and we have already taken care of
5019                    // transitioning to the new one.  Just update the new
5020                    // one to continue using the old name.
5021                    realName = pkg.mRealPackage;
5022                    if (!pkg.packageName.equals(renamed)) {
5023                        // Callers into this function may have already taken
5024                        // care of renaming the package; only do it here if
5025                        // it is not already done.
5026                        pkg.setPackageName(renamed);
5027                    }
5028
5029                } else {
5030                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5031                        if ((origPackage = mSettings.peekPackageLPr(
5032                                pkg.mOriginalPackages.get(i))) != null) {
5033                            // We do have the package already installed under its
5034                            // original name...  should we use it?
5035                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5036                                // New package is not compatible with original.
5037                                origPackage = null;
5038                                continue;
5039                            } else if (origPackage.sharedUser != null) {
5040                                // Make sure uid is compatible between packages.
5041                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5042                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5043                                            + " to " + pkg.packageName + ": old uid "
5044                                            + origPackage.sharedUser.name
5045                                            + " differs from " + pkg.mSharedUserId);
5046                                    origPackage = null;
5047                                    continue;
5048                                }
5049                            } else {
5050                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5051                                        + pkg.packageName + " to old name " + origPackage.name);
5052                            }
5053                            break;
5054                        }
5055                    }
5056                }
5057            }
5058
5059            if (mTransferedPackages.contains(pkg.packageName)) {
5060                Slog.w(TAG, "Package " + pkg.packageName
5061                        + " was transferred to another, but its .apk remains");
5062            }
5063
5064            // Just create the setting, don't add it yet. For already existing packages
5065            // the PkgSetting exists already and doesn't have to be created.
5066            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5067                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5068                    pkg.applicationInfo.cpuAbi,
5069                    pkg.applicationInfo.flags, user, false);
5070            if (pkgSetting == null) {
5071                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5072                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5073                return null;
5074            }
5075
5076            if (pkgSetting.origPackage != null) {
5077                // If we are first transitioning from an original package,
5078                // fix up the new package's name now.  We need to do this after
5079                // looking up the package under its new name, so getPackageLP
5080                // can take care of fiddling things correctly.
5081                pkg.setPackageName(origPackage.name);
5082
5083                // File a report about this.
5084                String msg = "New package " + pkgSetting.realName
5085                        + " renamed to replace old package " + pkgSetting.name;
5086                reportSettingsProblem(Log.WARN, msg);
5087
5088                // Make a note of it.
5089                mTransferedPackages.add(origPackage.name);
5090
5091                // No longer need to retain this.
5092                pkgSetting.origPackage = null;
5093            }
5094
5095            if (realName != null) {
5096                // Make a note of it.
5097                mTransferedPackages.add(pkg.packageName);
5098            }
5099
5100            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5101                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5102            }
5103
5104            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5105                // Check all shared libraries and map to their actual file path.
5106                // We only do this here for apps not on a system dir, because those
5107                // are the only ones that can fail an install due to this.  We
5108                // will take care of the system apps by updating all of their
5109                // library paths after the scan is done.
5110                if (!updateSharedLibrariesLPw(pkg, null)) {
5111                    return null;
5112                }
5113            }
5114
5115            if (mFoundPolicyFile) {
5116                SELinuxMMAC.assignSeinfoValue(pkg);
5117            }
5118
5119            pkg.applicationInfo.uid = pkgSetting.appId;
5120            pkg.mExtras = pkgSetting;
5121            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5122                if (!verifySignaturesLP(pkgSetting, pkg)) {
5123                    if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5124                        return null;
5125                    }
5126                    // The signature has changed, but this package is in the system
5127                    // image...  let's recover!
5128                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5129                    // However...  if this package is part of a shared user, but it
5130                    // doesn't match the signature of the shared user, let's fail.
5131                    // What this means is that you can't change the signatures
5132                    // associated with an overall shared user, which doesn't seem all
5133                    // that unreasonable.
5134                    if (pkgSetting.sharedUser != null) {
5135                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5136                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5137                            Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5138                            mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5139                            return null;
5140                        }
5141                    }
5142                    // File a report about this.
5143                    String msg = "System package " + pkg.packageName
5144                        + " signature changed; retaining data.";
5145                    reportSettingsProblem(Log.WARN, msg);
5146                }
5147            } else {
5148                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5149                    Slog.e(TAG, "Package " + pkg.packageName
5150                           + " upgrade keys do not match the previously installed version; ");
5151                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5152                    return null;
5153                } else {
5154                    // signatures may have changed as result of upgrade
5155                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5156                }
5157            }
5158            // Verify that this new package doesn't have any content providers
5159            // that conflict with existing packages.  Only do this if the
5160            // package isn't already installed, since we don't want to break
5161            // things that are installed.
5162            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5163                final int N = pkg.providers.size();
5164                int i;
5165                for (i=0; i<N; i++) {
5166                    PackageParser.Provider p = pkg.providers.get(i);
5167                    if (p.info.authority != null) {
5168                        String names[] = p.info.authority.split(";");
5169                        for (int j = 0; j < names.length; j++) {
5170                            if (mProvidersByAuthority.containsKey(names[j])) {
5171                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5172                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5173                                        " (in package " + pkg.applicationInfo.packageName +
5174                                        ") is already used by "
5175                                        + ((other != null && other.getComponentName() != null)
5176                                                ? other.getComponentName().getPackageName() : "?"));
5177                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5178                                return null;
5179                            }
5180                        }
5181                    }
5182                }
5183            }
5184
5185            if (pkg.mAdoptPermissions != null) {
5186                // This package wants to adopt ownership of permissions from
5187                // another package.
5188                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5189                    final String origName = pkg.mAdoptPermissions.get(i);
5190                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5191                    if (orig != null) {
5192                        if (verifyPackageUpdateLPr(orig, pkg)) {
5193                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5194                                    + pkg.packageName);
5195                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5196                        }
5197                    }
5198                }
5199            }
5200        }
5201
5202        final String pkgName = pkg.packageName;
5203
5204        final long scanFileTime = scanFile.lastModified();
5205        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5206        pkg.applicationInfo.processName = fixProcessName(
5207                pkg.applicationInfo.packageName,
5208                pkg.applicationInfo.processName,
5209                pkg.applicationInfo.uid);
5210
5211        File dataPath;
5212        if (mPlatformPackage == pkg) {
5213            // The system package is special.
5214            dataPath = new File (Environment.getDataDirectory(), "system");
5215            pkg.applicationInfo.dataDir = dataPath.getPath();
5216        } else {
5217            // This is a normal package, need to make its data directory.
5218            dataPath = getDataPathForPackage(pkg.packageName, 0);
5219
5220            boolean uidError = false;
5221
5222            if (dataPath.exists()) {
5223                int currentUid = 0;
5224                try {
5225                    StructStat stat = Os.stat(dataPath.getPath());
5226                    currentUid = stat.st_uid;
5227                } catch (ErrnoException e) {
5228                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5229                }
5230
5231                // If we have mismatched owners for the data path, we have a problem.
5232                if (currentUid != pkg.applicationInfo.uid) {
5233                    boolean recovered = false;
5234                    if (currentUid == 0) {
5235                        // The directory somehow became owned by root.  Wow.
5236                        // This is probably because the system was stopped while
5237                        // installd was in the middle of messing with its libs
5238                        // directory.  Ask installd to fix that.
5239                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5240                                pkg.applicationInfo.uid);
5241                        if (ret >= 0) {
5242                            recovered = true;
5243                            String msg = "Package " + pkg.packageName
5244                                    + " unexpectedly changed to uid 0; recovered to " +
5245                                    + pkg.applicationInfo.uid;
5246                            reportSettingsProblem(Log.WARN, msg);
5247                        }
5248                    }
5249                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5250                            || (scanMode&SCAN_BOOTING) != 0)) {
5251                        // If this is a system app, we can at least delete its
5252                        // current data so the application will still work.
5253                        int ret = removeDataDirsLI(pkgName);
5254                        if (ret >= 0) {
5255                            // TODO: Kill the processes first
5256                            // Old data gone!
5257                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5258                                    ? "System package " : "Third party package ";
5259                            String msg = prefix + pkg.packageName
5260                                    + " has changed from uid: "
5261                                    + currentUid + " to "
5262                                    + pkg.applicationInfo.uid + "; old data erased";
5263                            reportSettingsProblem(Log.WARN, msg);
5264                            recovered = true;
5265
5266                            // And now re-install the app.
5267                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5268                                                   pkg.applicationInfo.seinfo);
5269                            if (ret == -1) {
5270                                // Ack should not happen!
5271                                msg = prefix + pkg.packageName
5272                                        + " could not have data directory re-created after delete.";
5273                                reportSettingsProblem(Log.WARN, msg);
5274                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5275                                return null;
5276                            }
5277                        }
5278                        if (!recovered) {
5279                            mHasSystemUidErrors = true;
5280                        }
5281                    } else if (!recovered) {
5282                        // If we allow this install to proceed, we will be broken.
5283                        // Abort, abort!
5284                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5285                        return null;
5286                    }
5287                    if (!recovered) {
5288                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5289                            + pkg.applicationInfo.uid + "/fs_"
5290                            + currentUid;
5291                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5292                        String msg = "Package " + pkg.packageName
5293                                + " has mismatched uid: "
5294                                + currentUid + " on disk, "
5295                                + pkg.applicationInfo.uid + " in settings";
5296                        // writer
5297                        synchronized (mPackages) {
5298                            mSettings.mReadMessages.append(msg);
5299                            mSettings.mReadMessages.append('\n');
5300                            uidError = true;
5301                            if (!pkgSetting.uidError) {
5302                                reportSettingsProblem(Log.ERROR, msg);
5303                            }
5304                        }
5305                    }
5306                }
5307                pkg.applicationInfo.dataDir = dataPath.getPath();
5308                if (mShouldRestoreconData) {
5309                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5310                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5311                                pkg.applicationInfo.uid);
5312                }
5313            } else {
5314                if (DEBUG_PACKAGE_SCANNING) {
5315                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5316                        Log.v(TAG, "Want this data dir: " + dataPath);
5317                }
5318                //invoke installer to do the actual installation
5319                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5320                                           pkg.applicationInfo.seinfo);
5321                if (ret < 0) {
5322                    // Error from installer
5323                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5324                    return null;
5325                }
5326
5327                if (dataPath.exists()) {
5328                    pkg.applicationInfo.dataDir = dataPath.getPath();
5329                } else {
5330                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5331                    pkg.applicationInfo.dataDir = null;
5332                }
5333            }
5334
5335            /*
5336             * Set the data dir to the default "/data/data/<package name>/lib"
5337             * if we got here without anyone telling us different (e.g., apps
5338             * stored on SD card have their native libraries stored in the ASEC
5339             * container with the APK).
5340             *
5341             * This happens during an upgrade from a package settings file that
5342             * doesn't have a native library path attribute at all.
5343             */
5344            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5345                if (pkgSetting.nativeLibraryPathString == null) {
5346                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5347                } else {
5348                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5349                }
5350            }
5351            pkgSetting.uidError = uidError;
5352        }
5353
5354        final String path = scanFile.getPath();
5355        /* Note: We don't want to unpack the native binaries for
5356         *        system applications, unless they have been updated
5357         *        (the binaries are already under /system/lib).
5358         *        Also, don't unpack libs for apps on the external card
5359         *        since they should have their libraries in the ASEC
5360         *        container already.
5361         *
5362         *        In other words, we're going to unpack the binaries
5363         *        only for non-system apps and system app upgrades.
5364         */
5365        if (pkg.applicationInfo.nativeLibraryDir != null) {
5366            NativeLibraryHelper.Handle handle = null;
5367            try {
5368                handle = NativeLibraryHelper.Handle.create(scanFile);
5369                // Enable gross and lame hacks for apps that are built with old
5370                // SDK tools. We must scan their APKs for renderscript bitcode and
5371                // not launch them if it's present. Don't bother checking on devices
5372                // that don't have 64 bit support.
5373                String[] abiList = Build.SUPPORTED_ABIS;
5374                boolean hasLegacyRenderscriptBitcode = false;
5375                if (abiOverride != null) {
5376                    abiList = new String[] { abiOverride };
5377                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5378                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5379                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5380                    hasLegacyRenderscriptBitcode = true;
5381                }
5382
5383                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5384                final String dataPathString = dataPath.getCanonicalPath();
5385
5386                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5387                    /*
5388                     * Upgrading from a previous version of the OS sometimes
5389                     * leaves native libraries in the /data/data/<app>/lib
5390                     * directory for system apps even when they shouldn't be.
5391                     * Recent changes in the JNI library search path
5392                     * necessitates we remove those to match previous behavior.
5393                     */
5394                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5395                        Log.i(TAG, "removed obsolete native libraries for system package "
5396                                + path);
5397                    }
5398                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5399                        pkg.applicationInfo.cpuAbi = abiList[0];
5400                        pkgSetting.cpuAbiString = abiList[0];
5401                    } else {
5402                        setInternalAppAbi(pkg, pkgSetting);
5403                    }
5404                } else {
5405                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5406                        /*
5407                        * Update native library dir if it starts with
5408                        * /data/data
5409                        */
5410                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5411                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5412                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5413                        }
5414
5415                        try {
5416                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5417                                    nativeLibraryDir, abiList);
5418                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5419                                Slog.e(TAG, "Unable to copy native libraries");
5420                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5421                                return null;
5422                            }
5423
5424                            // We've successfully copied native libraries across, so we make a
5425                            // note of what ABI we're using
5426                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5427                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5428                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5429                                pkg.applicationInfo.cpuAbi = abiList[0];
5430                            } else {
5431                                pkg.applicationInfo.cpuAbi = null;
5432                            }
5433                        } catch (IOException e) {
5434                            Slog.e(TAG, "Unable to copy native libraries", e);
5435                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5436                            return null;
5437                        }
5438                    } else {
5439                        // We don't have to copy the shared libraries if we're in the ASEC container
5440                        // but we still need to scan the file to figure out what ABI the app needs.
5441                        //
5442                        // TODO: This duplicates work done in the default container service. It's possible
5443                        // to clean this up but we'll need to change the interface between this service
5444                        // and IMediaContainerService (but doing so will spread this logic out, rather
5445                        // than centralizing it).
5446                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5447                        if (abi >= 0) {
5448                            pkg.applicationInfo.cpuAbi = abiList[abi];
5449                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5450                            // Note that (non upgraded) system apps will not have any native
5451                            // libraries bundled in their APK, but we're guaranteed not to be
5452                            // such an app at this point.
5453                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5454                                pkg.applicationInfo.cpuAbi = abiList[0];
5455                            } else {
5456                                pkg.applicationInfo.cpuAbi = null;
5457                            }
5458                        } else {
5459                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5460                            return null;
5461                        }
5462                    }
5463
5464                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5465                    final int[] userIds = sUserManager.getUserIds();
5466                    synchronized (mInstallLock) {
5467                        for (int userId : userIds) {
5468                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5469                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5470                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5471                                        + ")");
5472                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5473                                return null;
5474                            }
5475                        }
5476                    }
5477                }
5478
5479                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5480            } catch (IOException ioe) {
5481                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5482            } finally {
5483                IoUtils.closeQuietly(handle);
5484            }
5485        }
5486
5487        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5488            // We don't do this here during boot because we can do it all
5489            // at once after scanning all existing packages.
5490            //
5491            // We also do this *before* we perform dexopt on this package, so that
5492            // we can avoid redundant dexopts, and also to make sure we've got the
5493            // code and package path correct.
5494            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5495                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5496                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5497                return null;
5498            }
5499        }
5500
5501        if ((scanMode&SCAN_NO_DEX) == 0) {
5502            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5503                    == DEX_OPT_FAILED) {
5504                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5505                    removeDataDirsLI(pkg.packageName);
5506                }
5507
5508                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5509                return null;
5510            }
5511        }
5512
5513        if (mFactoryTest && pkg.requestedPermissions.contains(
5514                android.Manifest.permission.FACTORY_TEST)) {
5515            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5516        }
5517
5518        ArrayList<PackageParser.Package> clientLibPkgs = null;
5519
5520        // writer
5521        synchronized (mPackages) {
5522            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5523                // Only system apps can add new shared libraries.
5524                if (pkg.libraryNames != null) {
5525                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5526                        String name = pkg.libraryNames.get(i);
5527                        boolean allowed = false;
5528                        if (isUpdatedSystemApp(pkg)) {
5529                            // New library entries can only be added through the
5530                            // system image.  This is important to get rid of a lot
5531                            // of nasty edge cases: for example if we allowed a non-
5532                            // system update of the app to add a library, then uninstalling
5533                            // the update would make the library go away, and assumptions
5534                            // we made such as through app install filtering would now
5535                            // have allowed apps on the device which aren't compatible
5536                            // with it.  Better to just have the restriction here, be
5537                            // conservative, and create many fewer cases that can negatively
5538                            // impact the user experience.
5539                            final PackageSetting sysPs = mSettings
5540                                    .getDisabledSystemPkgLPr(pkg.packageName);
5541                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5542                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5543                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5544                                        allowed = true;
5545                                        allowed = true;
5546                                        break;
5547                                    }
5548                                }
5549                            }
5550                        } else {
5551                            allowed = true;
5552                        }
5553                        if (allowed) {
5554                            if (!mSharedLibraries.containsKey(name)) {
5555                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5556                            } else if (!name.equals(pkg.packageName)) {
5557                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5558                                        + name + " already exists; skipping");
5559                            }
5560                        } else {
5561                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5562                                    + name + " that is not declared on system image; skipping");
5563                        }
5564                    }
5565                    if ((scanMode&SCAN_BOOTING) == 0) {
5566                        // If we are not booting, we need to update any applications
5567                        // that are clients of our shared library.  If we are booting,
5568                        // this will all be done once the scan is complete.
5569                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5570                    }
5571                }
5572            }
5573        }
5574
5575        // We also need to dexopt any apps that are dependent on this library.  Note that
5576        // if these fail, we should abort the install since installing the library will
5577        // result in some apps being broken.
5578        if (clientLibPkgs != null) {
5579            if ((scanMode&SCAN_NO_DEX) == 0) {
5580                for (int i=0; i<clientLibPkgs.size(); i++) {
5581                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5582                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5583                            == DEX_OPT_FAILED) {
5584                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5585                            removeDataDirsLI(pkg.packageName);
5586                        }
5587
5588                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5589                        return null;
5590                    }
5591                }
5592            }
5593        }
5594
5595        // Request the ActivityManager to kill the process(only for existing packages)
5596        // so that we do not end up in a confused state while the user is still using the older
5597        // version of the application while the new one gets installed.
5598        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5599            // If the package lives in an asec, tell everyone that the container is going
5600            // away so they can clean up any references to its resources (which would prevent
5601            // vold from being able to unmount the asec)
5602            if (isForwardLocked(pkg) || isExternal(pkg)) {
5603                if (DEBUG_INSTALL) {
5604                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5605                }
5606                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5607                final ArrayList<String> pkgList = new ArrayList<String>(1);
5608                pkgList.add(pkg.applicationInfo.packageName);
5609                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5610            }
5611
5612            // Post the request that it be killed now that the going-away broadcast is en route
5613            killApplication(pkg.applicationInfo.packageName,
5614                        pkg.applicationInfo.uid, "update pkg");
5615        }
5616
5617        // Also need to kill any apps that are dependent on the library.
5618        if (clientLibPkgs != null) {
5619            for (int i=0; i<clientLibPkgs.size(); i++) {
5620                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5621                killApplication(clientPkg.applicationInfo.packageName,
5622                        clientPkg.applicationInfo.uid, "update lib");
5623            }
5624        }
5625
5626        // writer
5627        synchronized (mPackages) {
5628            // We don't expect installation to fail beyond this point,
5629            if ((scanMode&SCAN_MONITOR) != 0) {
5630                mAppDirs.put(pkg.codePath, pkg);
5631            }
5632            // Add the new setting to mSettings
5633            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5634            // Add the new setting to mPackages
5635            mPackages.put(pkg.applicationInfo.packageName, pkg);
5636            // Make sure we don't accidentally delete its data.
5637            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5638            while (iter.hasNext()) {
5639                PackageCleanItem item = iter.next();
5640                if (pkgName.equals(item.packageName)) {
5641                    iter.remove();
5642                }
5643            }
5644
5645            // Take care of first install / last update times.
5646            if (currentTime != 0) {
5647                if (pkgSetting.firstInstallTime == 0) {
5648                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5649                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5650                    pkgSetting.lastUpdateTime = currentTime;
5651                }
5652            } else if (pkgSetting.firstInstallTime == 0) {
5653                // We need *something*.  Take time time stamp of the file.
5654                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5655            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5656                if (scanFileTime != pkgSetting.timeStamp) {
5657                    // A package on the system image has changed; consider this
5658                    // to be an update.
5659                    pkgSetting.lastUpdateTime = scanFileTime;
5660                }
5661            }
5662
5663            // Add the package's KeySets to the global KeySetManagerService
5664            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5665            try {
5666                // Old KeySetData no longer valid.
5667                ksms.removeAppKeySetData(pkg.packageName);
5668                ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5669                if (pkg.mKeySetMapping != null) {
5670                    for (Map.Entry<String, Set<PublicKey>> entry :
5671                            pkg.mKeySetMapping.entrySet()) {
5672                        if (entry.getValue() != null) {
5673                            ksms.addDefinedKeySetToPackage(pkg.packageName,
5674                                                          entry.getValue(), entry.getKey());
5675                        }
5676                    }
5677                    if (pkg.mUpgradeKeySets != null
5678                            && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) {
5679                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5680                            ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias);
5681                        }
5682                    }
5683                }
5684            } catch (NullPointerException e) {
5685                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5686            } catch (IllegalArgumentException e) {
5687                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5688            }
5689
5690            int N = pkg.providers.size();
5691            StringBuilder r = null;
5692            int i;
5693            for (i=0; i<N; i++) {
5694                PackageParser.Provider p = pkg.providers.get(i);
5695                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5696                        p.info.processName, pkg.applicationInfo.uid);
5697                mProviders.addProvider(p);
5698                p.syncable = p.info.isSyncable;
5699                if (p.info.authority != null) {
5700                    String names[] = p.info.authority.split(";");
5701                    p.info.authority = null;
5702                    for (int j = 0; j < names.length; j++) {
5703                        if (j == 1 && p.syncable) {
5704                            // We only want the first authority for a provider to possibly be
5705                            // syncable, so if we already added this provider using a different
5706                            // authority clear the syncable flag. We copy the provider before
5707                            // changing it because the mProviders object contains a reference
5708                            // to a provider that we don't want to change.
5709                            // Only do this for the second authority since the resulting provider
5710                            // object can be the same for all future authorities for this provider.
5711                            p = new PackageParser.Provider(p);
5712                            p.syncable = false;
5713                        }
5714                        if (!mProvidersByAuthority.containsKey(names[j])) {
5715                            mProvidersByAuthority.put(names[j], p);
5716                            if (p.info.authority == null) {
5717                                p.info.authority = names[j];
5718                            } else {
5719                                p.info.authority = p.info.authority + ";" + names[j];
5720                            }
5721                            if (DEBUG_PACKAGE_SCANNING) {
5722                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5723                                    Log.d(TAG, "Registered content provider: " + names[j]
5724                                            + ", className = " + p.info.name + ", isSyncable = "
5725                                            + p.info.isSyncable);
5726                            }
5727                        } else {
5728                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5729                            Slog.w(TAG, "Skipping provider name " + names[j] +
5730                                    " (in package " + pkg.applicationInfo.packageName +
5731                                    "): name already used by "
5732                                    + ((other != null && other.getComponentName() != null)
5733                                            ? other.getComponentName().getPackageName() : "?"));
5734                        }
5735                    }
5736                }
5737                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5738                    if (r == null) {
5739                        r = new StringBuilder(256);
5740                    } else {
5741                        r.append(' ');
5742                    }
5743                    r.append(p.info.name);
5744                }
5745            }
5746            if (r != null) {
5747                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5748            }
5749
5750            N = pkg.services.size();
5751            r = null;
5752            for (i=0; i<N; i++) {
5753                PackageParser.Service s = pkg.services.get(i);
5754                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5755                        s.info.processName, pkg.applicationInfo.uid);
5756                mServices.addService(s);
5757                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5758                    if (r == null) {
5759                        r = new StringBuilder(256);
5760                    } else {
5761                        r.append(' ');
5762                    }
5763                    r.append(s.info.name);
5764                }
5765            }
5766            if (r != null) {
5767                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5768            }
5769
5770            N = pkg.receivers.size();
5771            r = null;
5772            for (i=0; i<N; i++) {
5773                PackageParser.Activity a = pkg.receivers.get(i);
5774                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5775                        a.info.processName, pkg.applicationInfo.uid);
5776                mReceivers.addActivity(a, "receiver");
5777                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5778                    if (r == null) {
5779                        r = new StringBuilder(256);
5780                    } else {
5781                        r.append(' ');
5782                    }
5783                    r.append(a.info.name);
5784                }
5785            }
5786            if (r != null) {
5787                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5788            }
5789
5790            N = pkg.activities.size();
5791            r = null;
5792            for (i=0; i<N; i++) {
5793                PackageParser.Activity a = pkg.activities.get(i);
5794                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5795                        a.info.processName, pkg.applicationInfo.uid);
5796                mActivities.addActivity(a, "activity");
5797                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5798                    if (r == null) {
5799                        r = new StringBuilder(256);
5800                    } else {
5801                        r.append(' ');
5802                    }
5803                    r.append(a.info.name);
5804                }
5805            }
5806            if (r != null) {
5807                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5808            }
5809
5810            N = pkg.permissionGroups.size();
5811            r = null;
5812            for (i=0; i<N; i++) {
5813                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5814                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5815                if (cur == null) {
5816                    mPermissionGroups.put(pg.info.name, pg);
5817                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5818                        if (r == null) {
5819                            r = new StringBuilder(256);
5820                        } else {
5821                            r.append(' ');
5822                        }
5823                        r.append(pg.info.name);
5824                    }
5825                } else {
5826                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5827                            + pg.info.packageName + " ignored: original from "
5828                            + cur.info.packageName);
5829                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5830                        if (r == null) {
5831                            r = new StringBuilder(256);
5832                        } else {
5833                            r.append(' ');
5834                        }
5835                        r.append("DUP:");
5836                        r.append(pg.info.name);
5837                    }
5838                }
5839            }
5840            if (r != null) {
5841                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5842            }
5843
5844            N = pkg.permissions.size();
5845            r = null;
5846            for (i=0; i<N; i++) {
5847                PackageParser.Permission p = pkg.permissions.get(i);
5848                HashMap<String, BasePermission> permissionMap =
5849                        p.tree ? mSettings.mPermissionTrees
5850                        : mSettings.mPermissions;
5851                p.group = mPermissionGroups.get(p.info.group);
5852                if (p.info.group == null || p.group != null) {
5853                    BasePermission bp = permissionMap.get(p.info.name);
5854                    if (bp == null) {
5855                        bp = new BasePermission(p.info.name, p.info.packageName,
5856                                BasePermission.TYPE_NORMAL);
5857                        permissionMap.put(p.info.name, bp);
5858                    }
5859                    if (bp.perm == null) {
5860                        if (bp.sourcePackage != null
5861                                && !bp.sourcePackage.equals(p.info.packageName)) {
5862                            // If this is a permission that was formerly defined by a non-system
5863                            // app, but is now defined by a system app (following an upgrade),
5864                            // discard the previous declaration and consider the system's to be
5865                            // canonical.
5866                            if (isSystemApp(p.owner)) {
5867                                String msg = "New decl " + p.owner + " of permission  "
5868                                        + p.info.name + " is system";
5869                                reportSettingsProblem(Log.WARN, msg);
5870                                bp.sourcePackage = null;
5871                            }
5872                        }
5873                        if (bp.sourcePackage == null
5874                                || bp.sourcePackage.equals(p.info.packageName)) {
5875                            BasePermission tree = findPermissionTreeLP(p.info.name);
5876                            if (tree == null
5877                                    || tree.sourcePackage.equals(p.info.packageName)) {
5878                                bp.packageSetting = pkgSetting;
5879                                bp.perm = p;
5880                                bp.uid = pkg.applicationInfo.uid;
5881                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5882                                    if (r == null) {
5883                                        r = new StringBuilder(256);
5884                                    } else {
5885                                        r.append(' ');
5886                                    }
5887                                    r.append(p.info.name);
5888                                }
5889                            } else {
5890                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5891                                        + p.info.packageName + " ignored: base tree "
5892                                        + tree.name + " is from package "
5893                                        + tree.sourcePackage);
5894                            }
5895                        } else {
5896                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5897                                    + p.info.packageName + " ignored: original from "
5898                                    + bp.sourcePackage);
5899                        }
5900                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5901                        if (r == null) {
5902                            r = new StringBuilder(256);
5903                        } else {
5904                            r.append(' ');
5905                        }
5906                        r.append("DUP:");
5907                        r.append(p.info.name);
5908                    }
5909                    if (bp.perm == p) {
5910                        bp.protectionLevel = p.info.protectionLevel;
5911                    }
5912                } else {
5913                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5914                            + p.info.packageName + " ignored: no group "
5915                            + p.group);
5916                }
5917            }
5918            if (r != null) {
5919                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5920            }
5921
5922            N = pkg.instrumentation.size();
5923            r = null;
5924            for (i=0; i<N; i++) {
5925                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5926                a.info.packageName = pkg.applicationInfo.packageName;
5927                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5928                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5929                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5930                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5931                a.info.dataDir = pkg.applicationInfo.dataDir;
5932                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5933                mInstrumentation.put(a.getComponentName(), a);
5934                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5935                    if (r == null) {
5936                        r = new StringBuilder(256);
5937                    } else {
5938                        r.append(' ');
5939                    }
5940                    r.append(a.info.name);
5941                }
5942            }
5943            if (r != null) {
5944                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5945            }
5946
5947            if (pkg.protectedBroadcasts != null) {
5948                N = pkg.protectedBroadcasts.size();
5949                for (i=0; i<N; i++) {
5950                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5951                }
5952            }
5953
5954            pkgSetting.setTimeStamp(scanFileTime);
5955
5956            // Create idmap files for pairs of (packages, overlay packages).
5957            // Note: "android", ie framework-res.apk, is handled by native layers.
5958            if (pkg.mOverlayTarget != null) {
5959                // This is an overlay package.
5960                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5961                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5962                        mOverlays.put(pkg.mOverlayTarget,
5963                                new HashMap<String, PackageParser.Package>());
5964                    }
5965                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5966                    map.put(pkg.packageName, pkg);
5967                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5968                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5969                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5970                        return null;
5971                    }
5972                }
5973            } else if (mOverlays.containsKey(pkg.packageName) &&
5974                    !pkg.packageName.equals("android")) {
5975                // This is a regular package, with one or more known overlay packages.
5976                createIdmapsForPackageLI(pkg);
5977            }
5978        }
5979
5980        return pkg;
5981    }
5982
5983    /**
5984     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5985     * i.e, so that all packages can be run inside a single process if required.
5986     *
5987     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5988     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5989     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5990     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5991     * updating a package that belongs to a shared user.
5992     */
5993    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5994            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5995        String requiredInstructionSet = null;
5996        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5997            requiredInstructionSet = VMRuntime.getInstructionSet(
5998                     scannedPackage.applicationInfo.cpuAbi);
5999        }
6000
6001        PackageSetting requirer = null;
6002        for (PackageSetting ps : packagesForUser) {
6003            // If packagesForUser contains scannedPackage, we skip it. This will happen
6004            // when scannedPackage is an update of an existing package. Without this check,
6005            // we will never be able to change the ABI of any package belonging to a shared
6006            // user, even if it's compatible with other packages.
6007            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6008                if (ps.cpuAbiString == null) {
6009                    continue;
6010                }
6011
6012                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6013                if (requiredInstructionSet != null) {
6014                    if (!instructionSet.equals(requiredInstructionSet)) {
6015                        // We have a mismatch between instruction sets (say arm vs arm64).
6016                        // bail out.
6017                        String errorMessage = "Instruction set mismatch, "
6018                                + ((requirer == null) ? "[caller]" : requirer)
6019                                + " requires " + requiredInstructionSet + " whereas " + ps
6020                                + " requires " + instructionSet;
6021                        Slog.e(TAG, errorMessage);
6022
6023                        reportSettingsProblem(Log.WARN, errorMessage);
6024                        // Give up, don't bother making any other changes to the package settings.
6025                        return false;
6026                    }
6027                } else {
6028                    requiredInstructionSet = instructionSet;
6029                    requirer = ps;
6030                }
6031            }
6032        }
6033
6034        if (requiredInstructionSet != null) {
6035            String adjustedAbi;
6036            if (requirer != null) {
6037                // requirer != null implies that either scannedPackage was null or that scannedPackage
6038                // did not require an ABI, in which case we have to adjust scannedPackage to match
6039                // the ABI of the set (which is the same as requirer's ABI)
6040                adjustedAbi = requirer.cpuAbiString;
6041                if (scannedPackage != null) {
6042                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6043                }
6044            } else {
6045                // requirer == null implies that we're updating all ABIs in the set to
6046                // match scannedPackage.
6047                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6048            }
6049
6050            for (PackageSetting ps : packagesForUser) {
6051                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6052                    if (ps.cpuAbiString != null) {
6053                        continue;
6054                    }
6055
6056                    ps.cpuAbiString = adjustedAbi;
6057                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6058                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6059                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6060
6061                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6062                            ps.cpuAbiString = null;
6063                            ps.pkg.applicationInfo.cpuAbi = null;
6064                            return false;
6065                        } else {
6066                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6067                        }
6068                    }
6069                }
6070            }
6071        }
6072
6073        return true;
6074    }
6075
6076    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6077        synchronized (mPackages) {
6078            mResolverReplaced = true;
6079            // Set up information for custom user intent resolution activity.
6080            mResolveActivity.applicationInfo = pkg.applicationInfo;
6081            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6082            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6083            mResolveActivity.processName = null;
6084            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6085            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6086                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6087            mResolveActivity.theme = 0;
6088            mResolveActivity.exported = true;
6089            mResolveActivity.enabled = true;
6090            mResolveInfo.activityInfo = mResolveActivity;
6091            mResolveInfo.priority = 0;
6092            mResolveInfo.preferredOrder = 0;
6093            mResolveInfo.match = 0;
6094            mResolveComponentName = mCustomResolverComponentName;
6095            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6096                    mResolveComponentName);
6097        }
6098    }
6099
6100    private String calculateApkRoot(final String codePathString) {
6101        final File codePath = new File(codePathString);
6102        final File codeRoot;
6103        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6104            codeRoot = Environment.getRootDirectory();
6105        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6106            codeRoot = Environment.getOemDirectory();
6107        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6108            codeRoot = Environment.getVendorDirectory();
6109        } else {
6110            // Unrecognized code path; take its top real segment as the apk root:
6111            // e.g. /something/app/blah.apk => /something
6112            try {
6113                File f = codePath.getCanonicalFile();
6114                File parent = f.getParentFile();    // non-null because codePath is a file
6115                File tmp;
6116                while ((tmp = parent.getParentFile()) != null) {
6117                    f = parent;
6118                    parent = tmp;
6119                }
6120                codeRoot = f;
6121                Slog.w(TAG, "Unrecognized code path "
6122                        + codePath + " - using " + codeRoot);
6123            } catch (IOException e) {
6124                // Can't canonicalize the lib path -- shenanigans?
6125                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6126                return Environment.getRootDirectory().getPath();
6127            }
6128        }
6129        return codeRoot.getPath();
6130    }
6131
6132    // This is the initial scan-time determination of how to handle a given
6133    // package for purposes of native library location.
6134    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6135            PackageSetting pkgSetting) {
6136        // "bundled" here means system-installed with no overriding update
6137        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6138        final File codeFile = new File(pkg.applicationInfo.getCodePath());
6139        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6140
6141        String nativeLibraryPath = null;
6142        if (bundledApk) {
6143            // If "/system/lib64/apkname" exists, assume that is the per-package
6144            // native library directory to use; otherwise use "/system/lib/apkname".
6145            String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath());
6146            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6147            File packLib64 = new File(lib64, apkName);
6148            File libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6149            nativeLibraryPath = (new File(libDir, apkName)).getAbsolutePath();
6150        } else if (isApkFile(codeFile)) {
6151            // Monolithic install
6152            nativeLibraryPath = (new File(mAppLibInstallDir, apkName)).getAbsolutePath();
6153        } else {
6154            // Cluster install
6155            // TODO: pipe through abiOverride
6156            String[] abiList = Build.SUPPORTED_ABIS;
6157            NativeLibraryHelper.Handle handle = null;
6158            try {
6159                handle = NativeLibraryHelper.Handle.create(codeFile);
6160                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
6161                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6162                    abiList = Build.SUPPORTED_32_BIT_ABIS;
6163                }
6164
6165                final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6166                if (abiIndex >= 0) {
6167                    final File baseLibFile = new File(codeFile, LIB_DIR_NAME);
6168                    final String abi = Build.SUPPORTED_ABIS[abiIndex];
6169                    final String instructionSet = VMRuntime.getInstructionSet(abi);
6170                    nativeLibraryPath = new File(baseLibFile, instructionSet).getAbsolutePath();
6171                }
6172            } catch (IOException e) {
6173                Slog.e(TAG, "Failed to detect native libraries", e);
6174            } finally {
6175                IoUtils.closeQuietly(handle);
6176            }
6177        }
6178        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6179        // pkgSetting might be null during rescan following uninstall of updates
6180        // to a bundled app, so accommodate that possibility.  The settings in
6181        // that case will be established later from the parsed package.
6182        if (pkgSetting != null) {
6183            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6184        }
6185    }
6186
6187    // Deduces the required ABI of an upgraded system app.
6188    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6189        final String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath());
6190        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6191
6192        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6193        // or similar.
6194        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6195        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6196
6197        // Assume that the bundled native libraries always correspond to the
6198        // most preferred 32 or 64 bit ABI.
6199        if (lib64.exists()) {
6200            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6201            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6202        } else if (lib.exists()) {
6203            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6204            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6205        } else {
6206            // This is the case where the app has no native code.
6207            pkg.applicationInfo.cpuAbi = null;
6208            pkgSetting.cpuAbiString = null;
6209        }
6210    }
6211
6212    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6213            final File nativeLibraryDir, String[] abiList) throws IOException {
6214        if (!nativeLibraryDir.isDirectory()) {
6215            nativeLibraryDir.delete();
6216
6217            if (!nativeLibraryDir.mkdir()) {
6218                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6219            }
6220
6221            try {
6222                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6223            } catch (ErrnoException e) {
6224                throw new IOException("Cannot chmod native library directory "
6225                        + nativeLibraryDir.getPath(), e);
6226            }
6227        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6228            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6229        }
6230
6231        /*
6232         * If this is an internal application or our nativeLibraryPath points to
6233         * the app-lib directory, unpack the libraries if necessary.
6234         */
6235        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6236        if (abi >= 0) {
6237            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6238                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6239            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6240                return copyRet;
6241            }
6242        }
6243
6244        return abi;
6245    }
6246
6247    private void killApplication(String pkgName, int appId, String reason) {
6248        // Request the ActivityManager to kill the process(only for existing packages)
6249        // so that we do not end up in a confused state while the user is still using the older
6250        // version of the application while the new one gets installed.
6251        IActivityManager am = ActivityManagerNative.getDefault();
6252        if (am != null) {
6253            try {
6254                am.killApplicationWithAppId(pkgName, appId, reason);
6255            } catch (RemoteException e) {
6256            }
6257        }
6258    }
6259
6260    void removePackageLI(PackageSetting ps, boolean chatty) {
6261        if (DEBUG_INSTALL) {
6262            if (chatty)
6263                Log.d(TAG, "Removing package " + ps.name);
6264        }
6265
6266        // writer
6267        synchronized (mPackages) {
6268            mPackages.remove(ps.name);
6269            if (ps.codePathString != null) {
6270                mAppDirs.remove(ps.codePathString);
6271            }
6272
6273            final PackageParser.Package pkg = ps.pkg;
6274            if (pkg != null) {
6275                cleanPackageDataStructuresLILPw(pkg, chatty);
6276            }
6277        }
6278    }
6279
6280    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6281        if (DEBUG_INSTALL) {
6282            if (chatty)
6283                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6284        }
6285
6286        // writer
6287        synchronized (mPackages) {
6288            mPackages.remove(pkg.applicationInfo.packageName);
6289            if (pkg.codePath != null) {
6290                mAppDirs.remove(pkg.codePath);
6291            }
6292            cleanPackageDataStructuresLILPw(pkg, chatty);
6293        }
6294    }
6295
6296    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6297        int N = pkg.providers.size();
6298        StringBuilder r = null;
6299        int i;
6300        for (i=0; i<N; i++) {
6301            PackageParser.Provider p = pkg.providers.get(i);
6302            mProviders.removeProvider(p);
6303            if (p.info.authority == null) {
6304
6305                /* There was another ContentProvider with this authority when
6306                 * this app was installed so this authority is null,
6307                 * Ignore it as we don't have to unregister the provider.
6308                 */
6309                continue;
6310            }
6311            String names[] = p.info.authority.split(";");
6312            for (int j = 0; j < names.length; j++) {
6313                if (mProvidersByAuthority.get(names[j]) == p) {
6314                    mProvidersByAuthority.remove(names[j]);
6315                    if (DEBUG_REMOVE) {
6316                        if (chatty)
6317                            Log.d(TAG, "Unregistered content provider: " + names[j]
6318                                    + ", className = " + p.info.name + ", isSyncable = "
6319                                    + p.info.isSyncable);
6320                    }
6321                }
6322            }
6323            if (DEBUG_REMOVE && chatty) {
6324                if (r == null) {
6325                    r = new StringBuilder(256);
6326                } else {
6327                    r.append(' ');
6328                }
6329                r.append(p.info.name);
6330            }
6331        }
6332        if (r != null) {
6333            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6334        }
6335
6336        N = pkg.services.size();
6337        r = null;
6338        for (i=0; i<N; i++) {
6339            PackageParser.Service s = pkg.services.get(i);
6340            mServices.removeService(s);
6341            if (chatty) {
6342                if (r == null) {
6343                    r = new StringBuilder(256);
6344                } else {
6345                    r.append(' ');
6346                }
6347                r.append(s.info.name);
6348            }
6349        }
6350        if (r != null) {
6351            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6352        }
6353
6354        N = pkg.receivers.size();
6355        r = null;
6356        for (i=0; i<N; i++) {
6357            PackageParser.Activity a = pkg.receivers.get(i);
6358            mReceivers.removeActivity(a, "receiver");
6359            if (DEBUG_REMOVE && chatty) {
6360                if (r == null) {
6361                    r = new StringBuilder(256);
6362                } else {
6363                    r.append(' ');
6364                }
6365                r.append(a.info.name);
6366            }
6367        }
6368        if (r != null) {
6369            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6370        }
6371
6372        N = pkg.activities.size();
6373        r = null;
6374        for (i=0; i<N; i++) {
6375            PackageParser.Activity a = pkg.activities.get(i);
6376            mActivities.removeActivity(a, "activity");
6377            if (DEBUG_REMOVE && chatty) {
6378                if (r == null) {
6379                    r = new StringBuilder(256);
6380                } else {
6381                    r.append(' ');
6382                }
6383                r.append(a.info.name);
6384            }
6385        }
6386        if (r != null) {
6387            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6388        }
6389
6390        N = pkg.permissions.size();
6391        r = null;
6392        for (i=0; i<N; i++) {
6393            PackageParser.Permission p = pkg.permissions.get(i);
6394            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6395            if (bp == null) {
6396                bp = mSettings.mPermissionTrees.get(p.info.name);
6397            }
6398            if (bp != null && bp.perm == p) {
6399                bp.perm = null;
6400                if (DEBUG_REMOVE && chatty) {
6401                    if (r == null) {
6402                        r = new StringBuilder(256);
6403                    } else {
6404                        r.append(' ');
6405                    }
6406                    r.append(p.info.name);
6407                }
6408            }
6409        }
6410        if (r != null) {
6411            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6412        }
6413
6414        N = pkg.instrumentation.size();
6415        r = null;
6416        for (i=0; i<N; i++) {
6417            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6418            mInstrumentation.remove(a.getComponentName());
6419            if (DEBUG_REMOVE && chatty) {
6420                if (r == null) {
6421                    r = new StringBuilder(256);
6422                } else {
6423                    r.append(' ');
6424                }
6425                r.append(a.info.name);
6426            }
6427        }
6428        if (r != null) {
6429            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6430        }
6431
6432        r = null;
6433        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6434            // Only system apps can hold shared libraries.
6435            if (pkg.libraryNames != null) {
6436                for (i=0; i<pkg.libraryNames.size(); i++) {
6437                    String name = pkg.libraryNames.get(i);
6438                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6439                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6440                        mSharedLibraries.remove(name);
6441                        if (DEBUG_REMOVE && chatty) {
6442                            if (r == null) {
6443                                r = new StringBuilder(256);
6444                            } else {
6445                                r.append(' ');
6446                            }
6447                            r.append(name);
6448                        }
6449                    }
6450                }
6451            }
6452        }
6453        if (r != null) {
6454            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6455        }
6456    }
6457
6458    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6459        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6460            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6461                return true;
6462            }
6463        }
6464        return false;
6465    }
6466
6467    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6468    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6469    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6470
6471    private void updatePermissionsLPw(String changingPkg,
6472            PackageParser.Package pkgInfo, int flags) {
6473        // Make sure there are no dangling permission trees.
6474        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6475        while (it.hasNext()) {
6476            final BasePermission bp = it.next();
6477            if (bp.packageSetting == null) {
6478                // We may not yet have parsed the package, so just see if
6479                // we still know about its settings.
6480                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6481            }
6482            if (bp.packageSetting == null) {
6483                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6484                        + " from package " + bp.sourcePackage);
6485                it.remove();
6486            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6487                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6488                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6489                            + " from package " + bp.sourcePackage);
6490                    flags |= UPDATE_PERMISSIONS_ALL;
6491                    it.remove();
6492                }
6493            }
6494        }
6495
6496        // Make sure all dynamic permissions have been assigned to a package,
6497        // and make sure there are no dangling permissions.
6498        it = mSettings.mPermissions.values().iterator();
6499        while (it.hasNext()) {
6500            final BasePermission bp = it.next();
6501            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6502                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6503                        + bp.name + " pkg=" + bp.sourcePackage
6504                        + " info=" + bp.pendingInfo);
6505                if (bp.packageSetting == null && bp.pendingInfo != null) {
6506                    final BasePermission tree = findPermissionTreeLP(bp.name);
6507                    if (tree != null && tree.perm != null) {
6508                        bp.packageSetting = tree.packageSetting;
6509                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6510                                new PermissionInfo(bp.pendingInfo));
6511                        bp.perm.info.packageName = tree.perm.info.packageName;
6512                        bp.perm.info.name = bp.name;
6513                        bp.uid = tree.uid;
6514                    }
6515                }
6516            }
6517            if (bp.packageSetting == null) {
6518                // We may not yet have parsed the package, so just see if
6519                // we still know about its settings.
6520                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6521            }
6522            if (bp.packageSetting == null) {
6523                Slog.w(TAG, "Removing dangling permission: " + bp.name
6524                        + " from package " + bp.sourcePackage);
6525                it.remove();
6526            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6527                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6528                    Slog.i(TAG, "Removing old permission: " + bp.name
6529                            + " from package " + bp.sourcePackage);
6530                    flags |= UPDATE_PERMISSIONS_ALL;
6531                    it.remove();
6532                }
6533            }
6534        }
6535
6536        // Now update the permissions for all packages, in particular
6537        // replace the granted permissions of the system packages.
6538        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6539            for (PackageParser.Package pkg : mPackages.values()) {
6540                if (pkg != pkgInfo) {
6541                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6542                }
6543            }
6544        }
6545
6546        if (pkgInfo != null) {
6547            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6548        }
6549    }
6550
6551    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6552        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6553        if (ps == null) {
6554            return;
6555        }
6556        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6557        HashSet<String> origPermissions = gp.grantedPermissions;
6558        boolean changedPermission = false;
6559
6560        if (replace) {
6561            ps.permissionsFixed = false;
6562            if (gp == ps) {
6563                origPermissions = new HashSet<String>(gp.grantedPermissions);
6564                gp.grantedPermissions.clear();
6565                gp.gids = mGlobalGids;
6566            }
6567        }
6568
6569        if (gp.gids == null) {
6570            gp.gids = mGlobalGids;
6571        }
6572
6573        final int N = pkg.requestedPermissions.size();
6574        for (int i=0; i<N; i++) {
6575            final String name = pkg.requestedPermissions.get(i);
6576            final boolean required = pkg.requestedPermissionsRequired.get(i);
6577            final BasePermission bp = mSettings.mPermissions.get(name);
6578            if (DEBUG_INSTALL) {
6579                if (gp != ps) {
6580                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6581                }
6582            }
6583
6584            if (bp == null || bp.packageSetting == null) {
6585                Slog.w(TAG, "Unknown permission " + name
6586                        + " in package " + pkg.packageName);
6587                continue;
6588            }
6589
6590            final String perm = bp.name;
6591            boolean allowed;
6592            boolean allowedSig = false;
6593            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6594            if (level == PermissionInfo.PROTECTION_NORMAL
6595                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6596                // We grant a normal or dangerous permission if any of the following
6597                // are true:
6598                // 1) The permission is required
6599                // 2) The permission is optional, but was granted in the past
6600                // 3) The permission is optional, but was requested by an
6601                //    app in /system (not /data)
6602                //
6603                // Otherwise, reject the permission.
6604                allowed = (required || origPermissions.contains(perm)
6605                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6606            } else if (bp.packageSetting == null) {
6607                // This permission is invalid; skip it.
6608                allowed = false;
6609            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6610                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6611                if (allowed) {
6612                    allowedSig = true;
6613                }
6614            } else {
6615                allowed = false;
6616            }
6617            if (DEBUG_INSTALL) {
6618                if (gp != ps) {
6619                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6620                }
6621            }
6622            if (allowed) {
6623                if (!isSystemApp(ps) && ps.permissionsFixed) {
6624                    // If this is an existing, non-system package, then
6625                    // we can't add any new permissions to it.
6626                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6627                        // Except...  if this is a permission that was added
6628                        // to the platform (note: need to only do this when
6629                        // updating the platform).
6630                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6631                    }
6632                }
6633                if (allowed) {
6634                    if (!gp.grantedPermissions.contains(perm)) {
6635                        changedPermission = true;
6636                        gp.grantedPermissions.add(perm);
6637                        gp.gids = appendInts(gp.gids, bp.gids);
6638                    } else if (!ps.haveGids) {
6639                        gp.gids = appendInts(gp.gids, bp.gids);
6640                    }
6641                } else {
6642                    Slog.w(TAG, "Not granting permission " + perm
6643                            + " to package " + pkg.packageName
6644                            + " because it was previously installed without");
6645                }
6646            } else {
6647                if (gp.grantedPermissions.remove(perm)) {
6648                    changedPermission = true;
6649                    gp.gids = removeInts(gp.gids, bp.gids);
6650                    Slog.i(TAG, "Un-granting permission " + perm
6651                            + " from package " + pkg.packageName
6652                            + " (protectionLevel=" + bp.protectionLevel
6653                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6654                            + ")");
6655                } else {
6656                    Slog.w(TAG, "Not granting permission " + perm
6657                            + " to package " + pkg.packageName
6658                            + " (protectionLevel=" + bp.protectionLevel
6659                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6660                            + ")");
6661                }
6662            }
6663        }
6664
6665        if ((changedPermission || replace) && !ps.permissionsFixed &&
6666                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6667            // This is the first that we have heard about this package, so the
6668            // permissions we have now selected are fixed until explicitly
6669            // changed.
6670            ps.permissionsFixed = true;
6671        }
6672        ps.haveGids = true;
6673    }
6674
6675    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6676        boolean allowed = false;
6677        final int NP = PackageParser.NEW_PERMISSIONS.length;
6678        for (int ip=0; ip<NP; ip++) {
6679            final PackageParser.NewPermissionInfo npi
6680                    = PackageParser.NEW_PERMISSIONS[ip];
6681            if (npi.name.equals(perm)
6682                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6683                allowed = true;
6684                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6685                        + pkg.packageName);
6686                break;
6687            }
6688        }
6689        return allowed;
6690    }
6691
6692    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6693                                          BasePermission bp, HashSet<String> origPermissions) {
6694        boolean allowed;
6695        allowed = (compareSignatures(
6696                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6697                        == PackageManager.SIGNATURE_MATCH)
6698                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6699                        == PackageManager.SIGNATURE_MATCH);
6700        if (!allowed && (bp.protectionLevel
6701                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6702            if (isSystemApp(pkg)) {
6703                // For updated system applications, a system permission
6704                // is granted only if it had been defined by the original application.
6705                if (isUpdatedSystemApp(pkg)) {
6706                    final PackageSetting sysPs = mSettings
6707                            .getDisabledSystemPkgLPr(pkg.packageName);
6708                    final GrantedPermissions origGp = sysPs.sharedUser != null
6709                            ? sysPs.sharedUser : sysPs;
6710
6711                    if (origGp.grantedPermissions.contains(perm)) {
6712                        // If the original was granted this permission, we take
6713                        // that grant decision as read and propagate it to the
6714                        // update.
6715                        allowed = true;
6716                    } else {
6717                        // The system apk may have been updated with an older
6718                        // version of the one on the data partition, but which
6719                        // granted a new system permission that it didn't have
6720                        // before.  In this case we do want to allow the app to
6721                        // now get the new permission if the ancestral apk is
6722                        // privileged to get it.
6723                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6724                            for (int j=0;
6725                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6726                                if (perm.equals(
6727                                        sysPs.pkg.requestedPermissions.get(j))) {
6728                                    allowed = true;
6729                                    break;
6730                                }
6731                            }
6732                        }
6733                    }
6734                } else {
6735                    allowed = isPrivilegedApp(pkg);
6736                }
6737            }
6738        }
6739        if (!allowed && (bp.protectionLevel
6740                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6741            // For development permissions, a development permission
6742            // is granted only if it was already granted.
6743            allowed = origPermissions.contains(perm);
6744        }
6745        return allowed;
6746    }
6747
6748    final class ActivityIntentResolver
6749            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6750        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6751                boolean defaultOnly, int userId) {
6752            if (!sUserManager.exists(userId)) return null;
6753            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6754            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6755        }
6756
6757        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6758                int userId) {
6759            if (!sUserManager.exists(userId)) return null;
6760            mFlags = flags;
6761            return super.queryIntent(intent, resolvedType,
6762                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6763        }
6764
6765        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6766                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6767            if (!sUserManager.exists(userId)) return null;
6768            if (packageActivities == null) {
6769                return null;
6770            }
6771            mFlags = flags;
6772            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6773            final int N = packageActivities.size();
6774            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6775                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6776
6777            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6778            for (int i = 0; i < N; ++i) {
6779                intentFilters = packageActivities.get(i).intents;
6780                if (intentFilters != null && intentFilters.size() > 0) {
6781                    PackageParser.ActivityIntentInfo[] array =
6782                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6783                    intentFilters.toArray(array);
6784                    listCut.add(array);
6785                }
6786            }
6787            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6788        }
6789
6790        public final void addActivity(PackageParser.Activity a, String type) {
6791            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6792            mActivities.put(a.getComponentName(), a);
6793            if (DEBUG_SHOW_INFO)
6794                Log.v(
6795                TAG, "  " + type + " " +
6796                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6797            if (DEBUG_SHOW_INFO)
6798                Log.v(TAG, "    Class=" + a.info.name);
6799            final int NI = a.intents.size();
6800            for (int j=0; j<NI; j++) {
6801                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6802                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6803                    intent.setPriority(0);
6804                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6805                            + a.className + " with priority > 0, forcing to 0");
6806                }
6807                if (DEBUG_SHOW_INFO) {
6808                    Log.v(TAG, "    IntentFilter:");
6809                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6810                }
6811                if (!intent.debugCheck()) {
6812                    Log.w(TAG, "==> For Activity " + a.info.name);
6813                }
6814                addFilter(intent);
6815            }
6816        }
6817
6818        public final void removeActivity(PackageParser.Activity a, String type) {
6819            mActivities.remove(a.getComponentName());
6820            if (DEBUG_SHOW_INFO) {
6821                Log.v(TAG, "  " + type + " "
6822                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6823                                : a.info.name) + ":");
6824                Log.v(TAG, "    Class=" + a.info.name);
6825            }
6826            final int NI = a.intents.size();
6827            for (int j=0; j<NI; j++) {
6828                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6829                if (DEBUG_SHOW_INFO) {
6830                    Log.v(TAG, "    IntentFilter:");
6831                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6832                }
6833                removeFilter(intent);
6834            }
6835        }
6836
6837        @Override
6838        protected boolean allowFilterResult(
6839                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6840            ActivityInfo filterAi = filter.activity.info;
6841            for (int i=dest.size()-1; i>=0; i--) {
6842                ActivityInfo destAi = dest.get(i).activityInfo;
6843                if (destAi.name == filterAi.name
6844                        && destAi.packageName == filterAi.packageName) {
6845                    return false;
6846                }
6847            }
6848            return true;
6849        }
6850
6851        @Override
6852        protected ActivityIntentInfo[] newArray(int size) {
6853            return new ActivityIntentInfo[size];
6854        }
6855
6856        @Override
6857        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6858            if (!sUserManager.exists(userId)) return true;
6859            PackageParser.Package p = filter.activity.owner;
6860            if (p != null) {
6861                PackageSetting ps = (PackageSetting)p.mExtras;
6862                if (ps != null) {
6863                    // System apps are never considered stopped for purposes of
6864                    // filtering, because there may be no way for the user to
6865                    // actually re-launch them.
6866                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6867                            && ps.getStopped(userId);
6868                }
6869            }
6870            return false;
6871        }
6872
6873        @Override
6874        protected boolean isPackageForFilter(String packageName,
6875                PackageParser.ActivityIntentInfo info) {
6876            return packageName.equals(info.activity.owner.packageName);
6877        }
6878
6879        @Override
6880        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6881                int match, int userId) {
6882            if (!sUserManager.exists(userId)) return null;
6883            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6884                return null;
6885            }
6886            final PackageParser.Activity activity = info.activity;
6887            if (mSafeMode && (activity.info.applicationInfo.flags
6888                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6889                return null;
6890            }
6891            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6892            if (ps == null) {
6893                return null;
6894            }
6895            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6896                    ps.readUserState(userId), userId);
6897            if (ai == null) {
6898                return null;
6899            }
6900            final ResolveInfo res = new ResolveInfo();
6901            res.activityInfo = ai;
6902            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6903                res.filter = info;
6904            }
6905            res.priority = info.getPriority();
6906            res.preferredOrder = activity.owner.mPreferredOrder;
6907            //System.out.println("Result: " + res.activityInfo.className +
6908            //                   " = " + res.priority);
6909            res.match = match;
6910            res.isDefault = info.hasDefault;
6911            res.labelRes = info.labelRes;
6912            res.nonLocalizedLabel = info.nonLocalizedLabel;
6913            if (userNeedsBadging(userId)) {
6914                res.noResourceId = true;
6915            } else {
6916                res.icon = info.icon;
6917            }
6918            res.system = isSystemApp(res.activityInfo.applicationInfo);
6919            return res;
6920        }
6921
6922        @Override
6923        protected void sortResults(List<ResolveInfo> results) {
6924            Collections.sort(results, mResolvePrioritySorter);
6925        }
6926
6927        @Override
6928        protected void dumpFilter(PrintWriter out, String prefix,
6929                PackageParser.ActivityIntentInfo filter) {
6930            out.print(prefix); out.print(
6931                    Integer.toHexString(System.identityHashCode(filter.activity)));
6932                    out.print(' ');
6933                    filter.activity.printComponentShortName(out);
6934                    out.print(" filter ");
6935                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6936        }
6937
6938//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6939//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6940//            final List<ResolveInfo> retList = Lists.newArrayList();
6941//            while (i.hasNext()) {
6942//                final ResolveInfo resolveInfo = i.next();
6943//                if (isEnabledLP(resolveInfo.activityInfo)) {
6944//                    retList.add(resolveInfo);
6945//                }
6946//            }
6947//            return retList;
6948//        }
6949
6950        // Keys are String (activity class name), values are Activity.
6951        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6952                = new HashMap<ComponentName, PackageParser.Activity>();
6953        private int mFlags;
6954    }
6955
6956    private final class ServiceIntentResolver
6957            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6958        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6959                boolean defaultOnly, int userId) {
6960            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6961            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6962        }
6963
6964        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6965                int userId) {
6966            if (!sUserManager.exists(userId)) return null;
6967            mFlags = flags;
6968            return super.queryIntent(intent, resolvedType,
6969                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6970        }
6971
6972        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6973                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6974            if (!sUserManager.exists(userId)) return null;
6975            if (packageServices == null) {
6976                return null;
6977            }
6978            mFlags = flags;
6979            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6980            final int N = packageServices.size();
6981            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6982                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6983
6984            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6985            for (int i = 0; i < N; ++i) {
6986                intentFilters = packageServices.get(i).intents;
6987                if (intentFilters != null && intentFilters.size() > 0) {
6988                    PackageParser.ServiceIntentInfo[] array =
6989                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6990                    intentFilters.toArray(array);
6991                    listCut.add(array);
6992                }
6993            }
6994            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6995        }
6996
6997        public final void addService(PackageParser.Service s) {
6998            mServices.put(s.getComponentName(), s);
6999            if (DEBUG_SHOW_INFO) {
7000                Log.v(TAG, "  "
7001                        + (s.info.nonLocalizedLabel != null
7002                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7003                Log.v(TAG, "    Class=" + s.info.name);
7004            }
7005            final int NI = s.intents.size();
7006            int j;
7007            for (j=0; j<NI; j++) {
7008                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7009                if (DEBUG_SHOW_INFO) {
7010                    Log.v(TAG, "    IntentFilter:");
7011                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7012                }
7013                if (!intent.debugCheck()) {
7014                    Log.w(TAG, "==> For Service " + s.info.name);
7015                }
7016                addFilter(intent);
7017            }
7018        }
7019
7020        public final void removeService(PackageParser.Service s) {
7021            mServices.remove(s.getComponentName());
7022            if (DEBUG_SHOW_INFO) {
7023                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7024                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7025                Log.v(TAG, "    Class=" + s.info.name);
7026            }
7027            final int NI = s.intents.size();
7028            int j;
7029            for (j=0; j<NI; j++) {
7030                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7031                if (DEBUG_SHOW_INFO) {
7032                    Log.v(TAG, "    IntentFilter:");
7033                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7034                }
7035                removeFilter(intent);
7036            }
7037        }
7038
7039        @Override
7040        protected boolean allowFilterResult(
7041                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7042            ServiceInfo filterSi = filter.service.info;
7043            for (int i=dest.size()-1; i>=0; i--) {
7044                ServiceInfo destAi = dest.get(i).serviceInfo;
7045                if (destAi.name == filterSi.name
7046                        && destAi.packageName == filterSi.packageName) {
7047                    return false;
7048                }
7049            }
7050            return true;
7051        }
7052
7053        @Override
7054        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7055            return new PackageParser.ServiceIntentInfo[size];
7056        }
7057
7058        @Override
7059        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7060            if (!sUserManager.exists(userId)) return true;
7061            PackageParser.Package p = filter.service.owner;
7062            if (p != null) {
7063                PackageSetting ps = (PackageSetting)p.mExtras;
7064                if (ps != null) {
7065                    // System apps are never considered stopped for purposes of
7066                    // filtering, because there may be no way for the user to
7067                    // actually re-launch them.
7068                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7069                            && ps.getStopped(userId);
7070                }
7071            }
7072            return false;
7073        }
7074
7075        @Override
7076        protected boolean isPackageForFilter(String packageName,
7077                PackageParser.ServiceIntentInfo info) {
7078            return packageName.equals(info.service.owner.packageName);
7079        }
7080
7081        @Override
7082        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7083                int match, int userId) {
7084            if (!sUserManager.exists(userId)) return null;
7085            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7086            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7087                return null;
7088            }
7089            final PackageParser.Service service = info.service;
7090            if (mSafeMode && (service.info.applicationInfo.flags
7091                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7092                return null;
7093            }
7094            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7095            if (ps == null) {
7096                return null;
7097            }
7098            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7099                    ps.readUserState(userId), userId);
7100            if (si == null) {
7101                return null;
7102            }
7103            final ResolveInfo res = new ResolveInfo();
7104            res.serviceInfo = si;
7105            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7106                res.filter = filter;
7107            }
7108            res.priority = info.getPriority();
7109            res.preferredOrder = service.owner.mPreferredOrder;
7110            //System.out.println("Result: " + res.activityInfo.className +
7111            //                   " = " + res.priority);
7112            res.match = match;
7113            res.isDefault = info.hasDefault;
7114            res.labelRes = info.labelRes;
7115            res.nonLocalizedLabel = info.nonLocalizedLabel;
7116            res.icon = info.icon;
7117            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7118            return res;
7119        }
7120
7121        @Override
7122        protected void sortResults(List<ResolveInfo> results) {
7123            Collections.sort(results, mResolvePrioritySorter);
7124        }
7125
7126        @Override
7127        protected void dumpFilter(PrintWriter out, String prefix,
7128                PackageParser.ServiceIntentInfo filter) {
7129            out.print(prefix); out.print(
7130                    Integer.toHexString(System.identityHashCode(filter.service)));
7131                    out.print(' ');
7132                    filter.service.printComponentShortName(out);
7133                    out.print(" filter ");
7134                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7135        }
7136
7137//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7138//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7139//            final List<ResolveInfo> retList = Lists.newArrayList();
7140//            while (i.hasNext()) {
7141//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7142//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7143//                    retList.add(resolveInfo);
7144//                }
7145//            }
7146//            return retList;
7147//        }
7148
7149        // Keys are String (activity class name), values are Activity.
7150        private final HashMap<ComponentName, PackageParser.Service> mServices
7151                = new HashMap<ComponentName, PackageParser.Service>();
7152        private int mFlags;
7153    };
7154
7155    private final class ProviderIntentResolver
7156            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7157        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7158                boolean defaultOnly, int userId) {
7159            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7160            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7161        }
7162
7163        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7164                int userId) {
7165            if (!sUserManager.exists(userId))
7166                return null;
7167            mFlags = flags;
7168            return super.queryIntent(intent, resolvedType,
7169                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7170        }
7171
7172        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7173                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7174            if (!sUserManager.exists(userId))
7175                return null;
7176            if (packageProviders == null) {
7177                return null;
7178            }
7179            mFlags = flags;
7180            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7181            final int N = packageProviders.size();
7182            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7183                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7184
7185            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7186            for (int i = 0; i < N; ++i) {
7187                intentFilters = packageProviders.get(i).intents;
7188                if (intentFilters != null && intentFilters.size() > 0) {
7189                    PackageParser.ProviderIntentInfo[] array =
7190                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7191                    intentFilters.toArray(array);
7192                    listCut.add(array);
7193                }
7194            }
7195            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7196        }
7197
7198        public final void addProvider(PackageParser.Provider p) {
7199            if (mProviders.containsKey(p.getComponentName())) {
7200                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7201                return;
7202            }
7203
7204            mProviders.put(p.getComponentName(), p);
7205            if (DEBUG_SHOW_INFO) {
7206                Log.v(TAG, "  "
7207                        + (p.info.nonLocalizedLabel != null
7208                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7209                Log.v(TAG, "    Class=" + p.info.name);
7210            }
7211            final int NI = p.intents.size();
7212            int j;
7213            for (j = 0; j < NI; j++) {
7214                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7215                if (DEBUG_SHOW_INFO) {
7216                    Log.v(TAG, "    IntentFilter:");
7217                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7218                }
7219                if (!intent.debugCheck()) {
7220                    Log.w(TAG, "==> For Provider " + p.info.name);
7221                }
7222                addFilter(intent);
7223            }
7224        }
7225
7226        public final void removeProvider(PackageParser.Provider p) {
7227            mProviders.remove(p.getComponentName());
7228            if (DEBUG_SHOW_INFO) {
7229                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7230                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7231                Log.v(TAG, "    Class=" + p.info.name);
7232            }
7233            final int NI = p.intents.size();
7234            int j;
7235            for (j = 0; j < NI; j++) {
7236                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7237                if (DEBUG_SHOW_INFO) {
7238                    Log.v(TAG, "    IntentFilter:");
7239                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7240                }
7241                removeFilter(intent);
7242            }
7243        }
7244
7245        @Override
7246        protected boolean allowFilterResult(
7247                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7248            ProviderInfo filterPi = filter.provider.info;
7249            for (int i = dest.size() - 1; i >= 0; i--) {
7250                ProviderInfo destPi = dest.get(i).providerInfo;
7251                if (destPi.name == filterPi.name
7252                        && destPi.packageName == filterPi.packageName) {
7253                    return false;
7254                }
7255            }
7256            return true;
7257        }
7258
7259        @Override
7260        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7261            return new PackageParser.ProviderIntentInfo[size];
7262        }
7263
7264        @Override
7265        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7266            if (!sUserManager.exists(userId))
7267                return true;
7268            PackageParser.Package p = filter.provider.owner;
7269            if (p != null) {
7270                PackageSetting ps = (PackageSetting) p.mExtras;
7271                if (ps != null) {
7272                    // System apps are never considered stopped for purposes of
7273                    // filtering, because there may be no way for the user to
7274                    // actually re-launch them.
7275                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7276                            && ps.getStopped(userId);
7277                }
7278            }
7279            return false;
7280        }
7281
7282        @Override
7283        protected boolean isPackageForFilter(String packageName,
7284                PackageParser.ProviderIntentInfo info) {
7285            return packageName.equals(info.provider.owner.packageName);
7286        }
7287
7288        @Override
7289        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7290                int match, int userId) {
7291            if (!sUserManager.exists(userId))
7292                return null;
7293            final PackageParser.ProviderIntentInfo info = filter;
7294            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7295                return null;
7296            }
7297            final PackageParser.Provider provider = info.provider;
7298            if (mSafeMode && (provider.info.applicationInfo.flags
7299                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7300                return null;
7301            }
7302            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7303            if (ps == null) {
7304                return null;
7305            }
7306            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7307                    ps.readUserState(userId), userId);
7308            if (pi == null) {
7309                return null;
7310            }
7311            final ResolveInfo res = new ResolveInfo();
7312            res.providerInfo = pi;
7313            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7314                res.filter = filter;
7315            }
7316            res.priority = info.getPriority();
7317            res.preferredOrder = provider.owner.mPreferredOrder;
7318            res.match = match;
7319            res.isDefault = info.hasDefault;
7320            res.labelRes = info.labelRes;
7321            res.nonLocalizedLabel = info.nonLocalizedLabel;
7322            res.icon = info.icon;
7323            res.system = isSystemApp(res.providerInfo.applicationInfo);
7324            return res;
7325        }
7326
7327        @Override
7328        protected void sortResults(List<ResolveInfo> results) {
7329            Collections.sort(results, mResolvePrioritySorter);
7330        }
7331
7332        @Override
7333        protected void dumpFilter(PrintWriter out, String prefix,
7334                PackageParser.ProviderIntentInfo filter) {
7335            out.print(prefix);
7336            out.print(
7337                    Integer.toHexString(System.identityHashCode(filter.provider)));
7338            out.print(' ');
7339            filter.provider.printComponentShortName(out);
7340            out.print(" filter ");
7341            out.println(Integer.toHexString(System.identityHashCode(filter)));
7342        }
7343
7344        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7345                = new HashMap<ComponentName, PackageParser.Provider>();
7346        private int mFlags;
7347    };
7348
7349    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7350            new Comparator<ResolveInfo>() {
7351        public int compare(ResolveInfo r1, ResolveInfo r2) {
7352            int v1 = r1.priority;
7353            int v2 = r2.priority;
7354            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7355            if (v1 != v2) {
7356                return (v1 > v2) ? -1 : 1;
7357            }
7358            v1 = r1.preferredOrder;
7359            v2 = r2.preferredOrder;
7360            if (v1 != v2) {
7361                return (v1 > v2) ? -1 : 1;
7362            }
7363            if (r1.isDefault != r2.isDefault) {
7364                return r1.isDefault ? -1 : 1;
7365            }
7366            v1 = r1.match;
7367            v2 = r2.match;
7368            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7369            if (v1 != v2) {
7370                return (v1 > v2) ? -1 : 1;
7371            }
7372            if (r1.system != r2.system) {
7373                return r1.system ? -1 : 1;
7374            }
7375            return 0;
7376        }
7377    };
7378
7379    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7380            new Comparator<ProviderInfo>() {
7381        public int compare(ProviderInfo p1, ProviderInfo p2) {
7382            final int v1 = p1.initOrder;
7383            final int v2 = p2.initOrder;
7384            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7385        }
7386    };
7387
7388    static final void sendPackageBroadcast(String action, String pkg,
7389            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7390            int[] userIds) {
7391        IActivityManager am = ActivityManagerNative.getDefault();
7392        if (am != null) {
7393            try {
7394                if (userIds == null) {
7395                    userIds = am.getRunningUserIds();
7396                }
7397                for (int id : userIds) {
7398                    final Intent intent = new Intent(action,
7399                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7400                    if (extras != null) {
7401                        intent.putExtras(extras);
7402                    }
7403                    if (targetPkg != null) {
7404                        intent.setPackage(targetPkg);
7405                    }
7406                    // Modify the UID when posting to other users
7407                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7408                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7409                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7410                        intent.putExtra(Intent.EXTRA_UID, uid);
7411                    }
7412                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7413                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7414                    if (DEBUG_BROADCASTS) {
7415                        RuntimeException here = new RuntimeException("here");
7416                        here.fillInStackTrace();
7417                        Slog.d(TAG, "Sending to user " + id + ": "
7418                                + intent.toShortString(false, true, false, false)
7419                                + " " + intent.getExtras(), here);
7420                    }
7421                    am.broadcastIntent(null, intent, null, finishedReceiver,
7422                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7423                            finishedReceiver != null, false, id);
7424                }
7425            } catch (RemoteException ex) {
7426            }
7427        }
7428    }
7429
7430    /**
7431     * Check if the external storage media is available. This is true if there
7432     * is a mounted external storage medium or if the external storage is
7433     * emulated.
7434     */
7435    private boolean isExternalMediaAvailable() {
7436        return mMediaMounted || Environment.isExternalStorageEmulated();
7437    }
7438
7439    @Override
7440    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7441        // writer
7442        synchronized (mPackages) {
7443            if (!isExternalMediaAvailable()) {
7444                // If the external storage is no longer mounted at this point,
7445                // the caller may not have been able to delete all of this
7446                // packages files and can not delete any more.  Bail.
7447                return null;
7448            }
7449            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7450            if (lastPackage != null) {
7451                pkgs.remove(lastPackage);
7452            }
7453            if (pkgs.size() > 0) {
7454                return pkgs.get(0);
7455            }
7456        }
7457        return null;
7458    }
7459
7460    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7461        if (false) {
7462            RuntimeException here = new RuntimeException("here");
7463            here.fillInStackTrace();
7464            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7465                    + " andCode=" + andCode, here);
7466        }
7467        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7468                userId, andCode ? 1 : 0, packageName));
7469    }
7470
7471    void startCleaningPackages() {
7472        // reader
7473        synchronized (mPackages) {
7474            if (!isExternalMediaAvailable()) {
7475                return;
7476            }
7477            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7478                return;
7479            }
7480        }
7481        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7482        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7483        IActivityManager am = ActivityManagerNative.getDefault();
7484        if (am != null) {
7485            try {
7486                am.startService(null, intent, null, UserHandle.USER_OWNER);
7487            } catch (RemoteException e) {
7488            }
7489        }
7490    }
7491
7492    private final class AppDirObserver extends FileObserver {
7493        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7494            super(path, mask);
7495            mRootDir = path;
7496            mIsRom = isrom;
7497            mIsPrivileged = isPrivileged;
7498        }
7499
7500        public void onEvent(int event, String path) {
7501            String removedPackage = null;
7502            int removedAppId = -1;
7503            int[] removedUsers = null;
7504            String addedPackage = null;
7505            int addedAppId = -1;
7506            int[] addedUsers = null;
7507
7508            // TODO post a message to the handler to obtain serial ordering
7509            synchronized (mInstallLock) {
7510                String fullPathStr = null;
7511                File fullPath = null;
7512                if (path != null) {
7513                    fullPath = new File(mRootDir, path);
7514                    fullPathStr = fullPath.getPath();
7515                }
7516
7517                if (DEBUG_APP_DIR_OBSERVER)
7518                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7519
7520                if (!isApkFile(fullPath)) {
7521                    if (DEBUG_APP_DIR_OBSERVER)
7522                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7523                    return;
7524                }
7525
7526                // Ignore packages that are being installed or
7527                // have just been installed.
7528                if (ignoreCodePath(fullPathStr)) {
7529                    return;
7530                }
7531                PackageParser.Package p = null;
7532                PackageSetting ps = null;
7533                // reader
7534                synchronized (mPackages) {
7535                    p = mAppDirs.get(fullPathStr);
7536                    if (p != null) {
7537                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7538                        if (ps != null) {
7539                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7540                        } else {
7541                            removedUsers = sUserManager.getUserIds();
7542                        }
7543                    }
7544                    addedUsers = sUserManager.getUserIds();
7545                }
7546                if ((event&REMOVE_EVENTS) != 0) {
7547                    if (ps != null) {
7548                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7549                        removePackageLI(ps, true);
7550                        removedPackage = ps.name;
7551                        removedAppId = ps.appId;
7552                    }
7553                }
7554
7555                if ((event&ADD_EVENTS) != 0) {
7556                    if (p == null) {
7557                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7558                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7559                        if (mIsRom) {
7560                            flags |= PackageParser.PARSE_IS_SYSTEM
7561                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7562                            if (mIsPrivileged) {
7563                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7564                            }
7565                        }
7566                        p = scanPackageLI(fullPath, flags,
7567                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7568                                System.currentTimeMillis(), UserHandle.ALL, null);
7569                        if (p != null) {
7570                            /*
7571                             * TODO this seems dangerous as the package may have
7572                             * changed since we last acquired the mPackages
7573                             * lock.
7574                             */
7575                            // writer
7576                            synchronized (mPackages) {
7577                                updatePermissionsLPw(p.packageName, p,
7578                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7579                            }
7580                            addedPackage = p.applicationInfo.packageName;
7581                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7582                        }
7583                    }
7584                }
7585
7586                // reader
7587                synchronized (mPackages) {
7588                    mSettings.writeLPr();
7589                }
7590            }
7591
7592            if (removedPackage != null) {
7593                Bundle extras = new Bundle(1);
7594                extras.putInt(Intent.EXTRA_UID, removedAppId);
7595                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7596                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7597                        extras, null, null, removedUsers);
7598            }
7599            if (addedPackage != null) {
7600                Bundle extras = new Bundle(1);
7601                extras.putInt(Intent.EXTRA_UID, addedAppId);
7602                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7603                        extras, null, null, addedUsers);
7604            }
7605        }
7606
7607        private final String mRootDir;
7608        private final boolean mIsRom;
7609        private final boolean mIsPrivileged;
7610    }
7611
7612    @Override
7613    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7614            String installerPackageName, VerificationParams verificationParams,
7615            String packageAbiOverride) {
7616        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7617                null);
7618
7619        final File originFile = new File(originPath);
7620        final int uid = Binder.getCallingUid();
7621        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7622            try {
7623                if (observer != null) {
7624                    observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED);
7625                }
7626            } catch (RemoteException re) {
7627            }
7628            return;
7629        }
7630
7631        UserHandle user;
7632        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7633            user = UserHandle.ALL;
7634        } else {
7635            user = new UserHandle(UserHandle.getUserId(uid));
7636        }
7637
7638        final int filteredFlags;
7639        if (uid == Process.SHELL_UID || uid == 0) {
7640            if (DEBUG_INSTALL) {
7641                Slog.v(TAG, "Install from ADB");
7642            }
7643            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7644        } else {
7645            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7646        }
7647
7648        verificationParams.setInstallerUid(uid);
7649
7650        final Message msg = mHandler.obtainMessage(INIT_COPY);
7651        msg.obj = new InstallParams(originFile, false, observer, filteredFlags,
7652                installerPackageName, verificationParams, user, packageAbiOverride);
7653        mHandler.sendMessage(msg);
7654    }
7655
7656    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer,
7657            PackageInstallerParams params, String installerPackageName, int installerUid,
7658            UserHandle user) {
7659        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7660                params.referrerUri, installerUid, null);
7661
7662        final Message msg = mHandler.obtainMessage(INIT_COPY);
7663        msg.obj = new InstallParams(stageDir, true, observer, params.installFlags,
7664                installerPackageName, verifParams, user, params.abiOverride);
7665        mHandler.sendMessage(msg);
7666    }
7667
7668    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7669        Bundle extras = new Bundle(1);
7670        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7671
7672        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7673                packageName, extras, null, null, new int[] {userId});
7674        try {
7675            IActivityManager am = ActivityManagerNative.getDefault();
7676            final boolean isSystem =
7677                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7678            if (isSystem && am.isUserRunning(userId, false)) {
7679                // The just-installed/enabled app is bundled on the system, so presumed
7680                // to be able to run automatically without needing an explicit launch.
7681                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7682                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7683                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7684                        .setPackage(packageName);
7685                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7686                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7687            }
7688        } catch (RemoteException e) {
7689            // shouldn't happen
7690            Slog.w(TAG, "Unable to bootstrap installed package", e);
7691        }
7692    }
7693
7694    @Override
7695    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7696            int userId) {
7697        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7698        PackageSetting pkgSetting;
7699        final int uid = Binder.getCallingUid();
7700        if (UserHandle.getUserId(uid) != userId) {
7701            mContext.enforceCallingOrSelfPermission(
7702                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7703                    "setApplicationBlockedSetting for user " + userId);
7704        }
7705
7706        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7707            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7708            return false;
7709        }
7710
7711        long callingId = Binder.clearCallingIdentity();
7712        try {
7713            boolean sendAdded = false;
7714            boolean sendRemoved = false;
7715            // writer
7716            synchronized (mPackages) {
7717                pkgSetting = mSettings.mPackages.get(packageName);
7718                if (pkgSetting == null) {
7719                    return false;
7720                }
7721                if (pkgSetting.getBlocked(userId) != blocked) {
7722                    pkgSetting.setBlocked(blocked, userId);
7723                    mSettings.writePackageRestrictionsLPr(userId);
7724                    if (blocked) {
7725                        sendRemoved = true;
7726                    } else {
7727                        sendAdded = true;
7728                    }
7729                }
7730            }
7731            if (sendAdded) {
7732                sendPackageAddedForUser(packageName, pkgSetting, userId);
7733                return true;
7734            }
7735            if (sendRemoved) {
7736                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7737                        "blocking pkg");
7738                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7739            }
7740        } finally {
7741            Binder.restoreCallingIdentity(callingId);
7742        }
7743        return false;
7744    }
7745
7746    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7747            int userId) {
7748        final PackageRemovedInfo info = new PackageRemovedInfo();
7749        info.removedPackage = packageName;
7750        info.removedUsers = new int[] {userId};
7751        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7752        info.sendBroadcast(false, false, false);
7753    }
7754
7755    /**
7756     * Returns true if application is not found or there was an error. Otherwise it returns
7757     * the blocked state of the package for the given user.
7758     */
7759    @Override
7760    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7761        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7762        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7763                "getApplicationBlocked for user " + userId);
7764        PackageSetting pkgSetting;
7765        long callingId = Binder.clearCallingIdentity();
7766        try {
7767            // writer
7768            synchronized (mPackages) {
7769                pkgSetting = mSettings.mPackages.get(packageName);
7770                if (pkgSetting == null) {
7771                    return true;
7772                }
7773                return pkgSetting.getBlocked(userId);
7774            }
7775        } finally {
7776            Binder.restoreCallingIdentity(callingId);
7777        }
7778    }
7779
7780    /**
7781     * @hide
7782     */
7783    @Override
7784    public int installExistingPackageAsUser(String packageName, int userId) {
7785        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7786                null);
7787        PackageSetting pkgSetting;
7788        final int uid = Binder.getCallingUid();
7789        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7790        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7791            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7792        }
7793
7794        long callingId = Binder.clearCallingIdentity();
7795        try {
7796            boolean sendAdded = false;
7797            Bundle extras = new Bundle(1);
7798
7799            // writer
7800            synchronized (mPackages) {
7801                pkgSetting = mSettings.mPackages.get(packageName);
7802                if (pkgSetting == null) {
7803                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7804                }
7805                if (!pkgSetting.getInstalled(userId)) {
7806                    pkgSetting.setInstalled(true, userId);
7807                    pkgSetting.setBlocked(false, userId);
7808                    mSettings.writePackageRestrictionsLPr(userId);
7809                    sendAdded = true;
7810                }
7811            }
7812
7813            if (sendAdded) {
7814                sendPackageAddedForUser(packageName, pkgSetting, userId);
7815            }
7816        } finally {
7817            Binder.restoreCallingIdentity(callingId);
7818        }
7819
7820        return PackageManager.INSTALL_SUCCEEDED;
7821    }
7822
7823    boolean isUserRestricted(int userId, String restrictionKey) {
7824        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7825        if (restrictions.getBoolean(restrictionKey, false)) {
7826            Log.w(TAG, "User is restricted: " + restrictionKey);
7827            return true;
7828        }
7829        return false;
7830    }
7831
7832    @Override
7833    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7834        mContext.enforceCallingOrSelfPermission(
7835                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7836                "Only package verification agents can verify applications");
7837
7838        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7839        final PackageVerificationResponse response = new PackageVerificationResponse(
7840                verificationCode, Binder.getCallingUid());
7841        msg.arg1 = id;
7842        msg.obj = response;
7843        mHandler.sendMessage(msg);
7844    }
7845
7846    @Override
7847    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7848            long millisecondsToDelay) {
7849        mContext.enforceCallingOrSelfPermission(
7850                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7851                "Only package verification agents can extend verification timeouts");
7852
7853        final PackageVerificationState state = mPendingVerification.get(id);
7854        final PackageVerificationResponse response = new PackageVerificationResponse(
7855                verificationCodeAtTimeout, Binder.getCallingUid());
7856
7857        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7858            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7859        }
7860        if (millisecondsToDelay < 0) {
7861            millisecondsToDelay = 0;
7862        }
7863        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7864                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7865            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7866        }
7867
7868        if ((state != null) && !state.timeoutExtended()) {
7869            state.extendTimeout();
7870
7871            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7872            msg.arg1 = id;
7873            msg.obj = response;
7874            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7875        }
7876    }
7877
7878    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7879            int verificationCode, UserHandle user) {
7880        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7881        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7882        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7883        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7884        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7885
7886        mContext.sendBroadcastAsUser(intent, user,
7887                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7888    }
7889
7890    private ComponentName matchComponentForVerifier(String packageName,
7891            List<ResolveInfo> receivers) {
7892        ActivityInfo targetReceiver = null;
7893
7894        final int NR = receivers.size();
7895        for (int i = 0; i < NR; i++) {
7896            final ResolveInfo info = receivers.get(i);
7897            if (info.activityInfo == null) {
7898                continue;
7899            }
7900
7901            if (packageName.equals(info.activityInfo.packageName)) {
7902                targetReceiver = info.activityInfo;
7903                break;
7904            }
7905        }
7906
7907        if (targetReceiver == null) {
7908            return null;
7909        }
7910
7911        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7912    }
7913
7914    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7915            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7916        if (pkgInfo.verifiers.length == 0) {
7917            return null;
7918        }
7919
7920        final int N = pkgInfo.verifiers.length;
7921        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7922        for (int i = 0; i < N; i++) {
7923            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7924
7925            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7926                    receivers);
7927            if (comp == null) {
7928                continue;
7929            }
7930
7931            final int verifierUid = getUidForVerifier(verifierInfo);
7932            if (verifierUid == -1) {
7933                continue;
7934            }
7935
7936            if (DEBUG_VERIFY) {
7937                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7938                        + " with the correct signature");
7939            }
7940            sufficientVerifiers.add(comp);
7941            verificationState.addSufficientVerifier(verifierUid);
7942        }
7943
7944        return sufficientVerifiers;
7945    }
7946
7947    private int getUidForVerifier(VerifierInfo verifierInfo) {
7948        synchronized (mPackages) {
7949            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7950            if (pkg == null) {
7951                return -1;
7952            } else if (pkg.mSignatures.length != 1) {
7953                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7954                        + " has more than one signature; ignoring");
7955                return -1;
7956            }
7957
7958            /*
7959             * If the public key of the package's signature does not match
7960             * our expected public key, then this is a different package and
7961             * we should skip.
7962             */
7963
7964            final byte[] expectedPublicKey;
7965            try {
7966                final Signature verifierSig = pkg.mSignatures[0];
7967                final PublicKey publicKey = verifierSig.getPublicKey();
7968                expectedPublicKey = publicKey.getEncoded();
7969            } catch (CertificateException e) {
7970                return -1;
7971            }
7972
7973            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7974
7975            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7976                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7977                        + " does not have the expected public key; ignoring");
7978                return -1;
7979            }
7980
7981            return pkg.applicationInfo.uid;
7982        }
7983    }
7984
7985    @Override
7986    public void finishPackageInstall(int token) {
7987        enforceSystemOrRoot("Only the system is allowed to finish installs");
7988
7989        if (DEBUG_INSTALL) {
7990            Slog.v(TAG, "BM finishing package install for " + token);
7991        }
7992
7993        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7994        mHandler.sendMessage(msg);
7995    }
7996
7997    /**
7998     * Get the verification agent timeout.
7999     *
8000     * @return verification timeout in milliseconds
8001     */
8002    private long getVerificationTimeout() {
8003        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8004                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8005                DEFAULT_VERIFICATION_TIMEOUT);
8006    }
8007
8008    /**
8009     * Get the default verification agent response code.
8010     *
8011     * @return default verification response code
8012     */
8013    private int getDefaultVerificationResponse() {
8014        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8015                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8016                DEFAULT_VERIFICATION_RESPONSE);
8017    }
8018
8019    /**
8020     * Check whether or not package verification has been enabled.
8021     *
8022     * @return true if verification should be performed
8023     */
8024    private boolean isVerificationEnabled(int userId, int flags) {
8025        if (!DEFAULT_VERIFY_ENABLE) {
8026            return false;
8027        }
8028
8029        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8030
8031        // Check if installing from ADB
8032        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8033            // Do not run verification in a test harness environment
8034            if (ActivityManager.isRunningInTestHarness()) {
8035                return false;
8036            }
8037            if (ensureVerifyAppsEnabled) {
8038                return true;
8039            }
8040            // Check if the developer does not want package verification for ADB installs
8041            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8042                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8043                return false;
8044            }
8045        }
8046
8047        if (ensureVerifyAppsEnabled) {
8048            return true;
8049        }
8050
8051        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8052                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8053    }
8054
8055    /**
8056     * Get the "allow unknown sources" setting.
8057     *
8058     * @return the current "allow unknown sources" setting
8059     */
8060    private int getUnknownSourcesSettings() {
8061        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8062                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8063                -1);
8064    }
8065
8066    @Override
8067    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8068        final int uid = Binder.getCallingUid();
8069        // writer
8070        synchronized (mPackages) {
8071            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8072            if (targetPackageSetting == null) {
8073                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8074            }
8075
8076            PackageSetting installerPackageSetting;
8077            if (installerPackageName != null) {
8078                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8079                if (installerPackageSetting == null) {
8080                    throw new IllegalArgumentException("Unknown installer package: "
8081                            + installerPackageName);
8082                }
8083            } else {
8084                installerPackageSetting = null;
8085            }
8086
8087            Signature[] callerSignature;
8088            Object obj = mSettings.getUserIdLPr(uid);
8089            if (obj != null) {
8090                if (obj instanceof SharedUserSetting) {
8091                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8092                } else if (obj instanceof PackageSetting) {
8093                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8094                } else {
8095                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8096                }
8097            } else {
8098                throw new SecurityException("Unknown calling uid " + uid);
8099            }
8100
8101            // Verify: can't set installerPackageName to a package that is
8102            // not signed with the same cert as the caller.
8103            if (installerPackageSetting != null) {
8104                if (compareSignatures(callerSignature,
8105                        installerPackageSetting.signatures.mSignatures)
8106                        != PackageManager.SIGNATURE_MATCH) {
8107                    throw new SecurityException(
8108                            "Caller does not have same cert as new installer package "
8109                            + installerPackageName);
8110                }
8111            }
8112
8113            // Verify: if target already has an installer package, it must
8114            // be signed with the same cert as the caller.
8115            if (targetPackageSetting.installerPackageName != null) {
8116                PackageSetting setting = mSettings.mPackages.get(
8117                        targetPackageSetting.installerPackageName);
8118                // If the currently set package isn't valid, then it's always
8119                // okay to change it.
8120                if (setting != null) {
8121                    if (compareSignatures(callerSignature,
8122                            setting.signatures.mSignatures)
8123                            != PackageManager.SIGNATURE_MATCH) {
8124                        throw new SecurityException(
8125                                "Caller does not have same cert as old installer package "
8126                                + targetPackageSetting.installerPackageName);
8127                    }
8128                }
8129            }
8130
8131            // Okay!
8132            targetPackageSetting.installerPackageName = installerPackageName;
8133            scheduleWriteSettingsLocked();
8134        }
8135    }
8136
8137    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8138        // Queue up an async operation since the package installation may take a little while.
8139        mHandler.post(new Runnable() {
8140            public void run() {
8141                mHandler.removeCallbacks(this);
8142                 // Result object to be returned
8143                PackageInstalledInfo res = new PackageInstalledInfo();
8144                res.returnCode = currentStatus;
8145                res.uid = -1;
8146                res.pkg = null;
8147                res.removedInfo = new PackageRemovedInfo();
8148                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8149                    args.doPreInstall(res.returnCode);
8150                    synchronized (mInstallLock) {
8151                        installPackageLI(args, true, res);
8152                    }
8153                    args.doPostInstall(res.returnCode, res.uid);
8154                }
8155
8156                // A restore should be performed at this point if (a) the install
8157                // succeeded, (b) the operation is not an update, and (c) the new
8158                // package has a backupAgent defined.
8159                final boolean update = res.removedInfo.removedPackage != null;
8160                boolean doRestore = (!update
8161                        && res.pkg != null
8162                        && res.pkg.applicationInfo.backupAgentName != null);
8163
8164                // Set up the post-install work request bookkeeping.  This will be used
8165                // and cleaned up by the post-install event handling regardless of whether
8166                // there's a restore pass performed.  Token values are >= 1.
8167                int token;
8168                if (mNextInstallToken < 0) mNextInstallToken = 1;
8169                token = mNextInstallToken++;
8170
8171                PostInstallData data = new PostInstallData(args, res);
8172                mRunningInstalls.put(token, data);
8173                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8174
8175                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8176                    // Pass responsibility to the Backup Manager.  It will perform a
8177                    // restore if appropriate, then pass responsibility back to the
8178                    // Package Manager to run the post-install observer callbacks
8179                    // and broadcasts.
8180                    IBackupManager bm = IBackupManager.Stub.asInterface(
8181                            ServiceManager.getService(Context.BACKUP_SERVICE));
8182                    if (bm != null) {
8183                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8184                                + " to BM for possible restore");
8185                        try {
8186                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8187                        } catch (RemoteException e) {
8188                            // can't happen; the backup manager is local
8189                        } catch (Exception e) {
8190                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8191                            doRestore = false;
8192                        }
8193                    } else {
8194                        Slog.e(TAG, "Backup Manager not found!");
8195                        doRestore = false;
8196                    }
8197                }
8198
8199                if (!doRestore) {
8200                    // No restore possible, or the Backup Manager was mysteriously not
8201                    // available -- just fire the post-install work request directly.
8202                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8203                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8204                    mHandler.sendMessage(msg);
8205                }
8206            }
8207        });
8208    }
8209
8210    private abstract class HandlerParams {
8211        private static final int MAX_RETRIES = 4;
8212
8213        /**
8214         * Number of times startCopy() has been attempted and had a non-fatal
8215         * error.
8216         */
8217        private int mRetries = 0;
8218
8219        /** User handle for the user requesting the information or installation. */
8220        private final UserHandle mUser;
8221
8222        HandlerParams(UserHandle user) {
8223            mUser = user;
8224        }
8225
8226        UserHandle getUser() {
8227            return mUser;
8228        }
8229
8230        final boolean startCopy() {
8231            boolean res;
8232            try {
8233                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8234
8235                if (++mRetries > MAX_RETRIES) {
8236                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8237                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8238                    handleServiceError();
8239                    return false;
8240                } else {
8241                    handleStartCopy();
8242                    res = true;
8243                }
8244            } catch (RemoteException e) {
8245                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8246                mHandler.sendEmptyMessage(MCS_RECONNECT);
8247                res = false;
8248            }
8249            handleReturnCode();
8250            return res;
8251        }
8252
8253        final void serviceError() {
8254            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8255            handleServiceError();
8256            handleReturnCode();
8257        }
8258
8259        abstract void handleStartCopy() throws RemoteException;
8260        abstract void handleServiceError();
8261        abstract void handleReturnCode();
8262    }
8263
8264    class MeasureParams extends HandlerParams {
8265        private final PackageStats mStats;
8266        private boolean mSuccess;
8267
8268        private final IPackageStatsObserver mObserver;
8269
8270        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8271            super(new UserHandle(stats.userHandle));
8272            mObserver = observer;
8273            mStats = stats;
8274        }
8275
8276        @Override
8277        public String toString() {
8278            return "MeasureParams{"
8279                + Integer.toHexString(System.identityHashCode(this))
8280                + " " + mStats.packageName + "}";
8281        }
8282
8283        @Override
8284        void handleStartCopy() throws RemoteException {
8285            synchronized (mInstallLock) {
8286                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8287            }
8288
8289            if (mSuccess) {
8290                final boolean mounted;
8291                if (Environment.isExternalStorageEmulated()) {
8292                    mounted = true;
8293                } else {
8294                    final String status = Environment.getExternalStorageState();
8295                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8296                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8297                }
8298
8299                if (mounted) {
8300                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8301
8302                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8303                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8304
8305                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8306                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8307
8308                    // Always subtract cache size, since it's a subdirectory
8309                    mStats.externalDataSize -= mStats.externalCacheSize;
8310
8311                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8312                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8313
8314                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8315                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8316                }
8317            }
8318        }
8319
8320        @Override
8321        void handleReturnCode() {
8322            if (mObserver != null) {
8323                try {
8324                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8325                } catch (RemoteException e) {
8326                    Slog.i(TAG, "Observer no longer exists.");
8327                }
8328            }
8329        }
8330
8331        @Override
8332        void handleServiceError() {
8333            Slog.e(TAG, "Could not measure application " + mStats.packageName
8334                            + " external storage");
8335        }
8336    }
8337
8338    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8339            throws RemoteException {
8340        long result = 0;
8341        for (File path : paths) {
8342            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8343        }
8344        return result;
8345    }
8346
8347    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8348        for (File path : paths) {
8349            try {
8350                mcs.clearDirectory(path.getAbsolutePath());
8351            } catch (RemoteException e) {
8352            }
8353        }
8354    }
8355
8356    class InstallParams extends HandlerParams {
8357        /**
8358         * Location where install is coming from, before it has been
8359         * copied/renamed into place. This could be a single monolithic APK
8360         * file, or a cluster directory. This location may be untrusted.
8361         */
8362        final File originFile;
8363
8364        /**
8365         * Flag indicating that {@link #originFile} has already been staged,
8366         * meaning downstream users don't need to defensively copy the contents.
8367         */
8368        boolean originStaged;
8369
8370        final IPackageInstallObserver2 observer;
8371        int flags;
8372        final String installerPackageName;
8373        final VerificationParams verificationParams;
8374        private InstallArgs mArgs;
8375        private int mRet;
8376        final String packageAbiOverride;
8377        final String packageInstructionSetOverride;
8378
8379        InstallParams(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8380                int flags, String installerPackageName, VerificationParams verificationParams,
8381                UserHandle user, String packageAbiOverride) {
8382            super(user);
8383            this.originFile = Preconditions.checkNotNull(originFile);
8384            this.originStaged = originStaged;
8385            this.observer = observer;
8386            this.flags = flags;
8387            this.installerPackageName = installerPackageName;
8388            this.verificationParams = verificationParams;
8389            this.packageAbiOverride = packageAbiOverride;
8390            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8391                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8392        }
8393
8394        @Override
8395        public String toString() {
8396            return "InstallParams{"
8397                + Integer.toHexString(System.identityHashCode(this))
8398                + " " + originFile + "}";
8399        }
8400
8401        public ManifestDigest getManifestDigest() {
8402            if (verificationParams == null) {
8403                return null;
8404            }
8405            return verificationParams.getManifestDigest();
8406        }
8407
8408        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8409            String packageName = pkgLite.packageName;
8410            int installLocation = pkgLite.installLocation;
8411            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8412            // reader
8413            synchronized (mPackages) {
8414                PackageParser.Package pkg = mPackages.get(packageName);
8415                if (pkg != null) {
8416                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8417                        // Check for downgrading.
8418                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8419                            if (pkgLite.versionCode < pkg.mVersionCode) {
8420                                Slog.w(TAG, "Can't install update of " + packageName
8421                                        + " update version " + pkgLite.versionCode
8422                                        + " is older than installed version "
8423                                        + pkg.mVersionCode);
8424                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8425                            }
8426                        }
8427                        // Check for updated system application.
8428                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8429                            if (onSd) {
8430                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8431                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8432                            }
8433                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8434                        } else {
8435                            if (onSd) {
8436                                // Install flag overrides everything.
8437                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8438                            }
8439                            // If current upgrade specifies particular preference
8440                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8441                                // Application explicitly specified internal.
8442                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8443                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8444                                // App explictly prefers external. Let policy decide
8445                            } else {
8446                                // Prefer previous location
8447                                if (isExternal(pkg)) {
8448                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8449                                }
8450                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8451                            }
8452                        }
8453                    } else {
8454                        // Invalid install. Return error code
8455                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8456                    }
8457                }
8458            }
8459            // All the special cases have been taken care of.
8460            // Return result based on recommended install location.
8461            if (onSd) {
8462                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8463            }
8464            return pkgLite.recommendedInstallLocation;
8465        }
8466
8467        private long getMemoryLowThreshold() {
8468            final DeviceStorageMonitorInternal
8469                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8470            if (dsm == null) {
8471                return 0L;
8472            }
8473            return dsm.getMemoryLowThreshold();
8474        }
8475
8476        /*
8477         * Invoke remote method to get package information and install
8478         * location values. Override install location based on default
8479         * policy if needed and then create install arguments based
8480         * on the install location.
8481         */
8482        public void handleStartCopy() throws RemoteException {
8483            int ret = PackageManager.INSTALL_SUCCEEDED;
8484            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8485            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8486            PackageInfoLite pkgLite = null;
8487
8488            if (onInt && onSd) {
8489                // Check if both bits are set.
8490                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8491                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8492            } else {
8493                final long lowThreshold = getMemoryLowThreshold();
8494                if (lowThreshold == 0L) {
8495                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8496                }
8497
8498                // Remote call to find out default install location
8499                final String originPath = originFile.getAbsolutePath();
8500                pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags, lowThreshold,
8501                        packageAbiOverride);
8502
8503                /*
8504                 * If we have too little free space, try to free cache
8505                 * before giving up.
8506                 */
8507                if (pkgLite.recommendedInstallLocation
8508                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8509                    final long size = mContainerService.calculateInstalledSize(
8510                            originPath, isForwardLocked(), packageAbiOverride);
8511                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8512                        pkgLite = mContainerService.getMinimalPackageInfo(originPath, flags,
8513                                lowThreshold, packageAbiOverride);
8514                    }
8515                    /*
8516                     * The cache free must have deleted the file we
8517                     * downloaded to install.
8518                     *
8519                     * TODO: fix the "freeCache" call to not delete
8520                     *       the file we care about.
8521                     */
8522                    if (pkgLite.recommendedInstallLocation
8523                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8524                        pkgLite.recommendedInstallLocation
8525                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8526                    }
8527                }
8528            }
8529
8530            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8531                int loc = pkgLite.recommendedInstallLocation;
8532                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8533                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8534                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8535                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8536                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8537                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8538                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8539                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8540                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8541                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8542                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8543                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8544                } else {
8545                    // Override with defaults if needed.
8546                    loc = installLocationPolicy(pkgLite, flags);
8547                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8548                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8549                    } else if (!onSd && !onInt) {
8550                        // Override install location with flags
8551                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8552                            // Set the flag to install on external media.
8553                            flags |= PackageManager.INSTALL_EXTERNAL;
8554                            flags &= ~PackageManager.INSTALL_INTERNAL;
8555                        } else {
8556                            // Make sure the flag for installing on external
8557                            // media is unset
8558                            flags |= PackageManager.INSTALL_INTERNAL;
8559                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8560                        }
8561                    }
8562                }
8563            }
8564
8565            final InstallArgs args = createInstallArgs(this);
8566            mArgs = args;
8567
8568            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8569                 /*
8570                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8571                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8572                 */
8573                int userIdentifier = getUser().getIdentifier();
8574                if (userIdentifier == UserHandle.USER_ALL
8575                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8576                    userIdentifier = UserHandle.USER_OWNER;
8577                }
8578
8579                /*
8580                 * Determine if we have any installed package verifiers. If we
8581                 * do, then we'll defer to them to verify the packages.
8582                 */
8583                final int requiredUid = mRequiredVerifierPackage == null ? -1
8584                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8585                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8586                    // TODO: send verifier the install session instead of uri
8587                    final Intent verification = new Intent(
8588                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8589                    verification.setDataAndType(Uri.fromFile(originFile), PACKAGE_MIME_TYPE);
8590                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8591
8592                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8593                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8594                            0 /* TODO: Which userId? */);
8595
8596                    if (DEBUG_VERIFY) {
8597                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8598                                + verification.toString() + " with " + pkgLite.verifiers.length
8599                                + " optional verifiers");
8600                    }
8601
8602                    final int verificationId = mPendingVerificationToken++;
8603
8604                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8605
8606                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8607                            installerPackageName);
8608
8609                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8610
8611                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8612                            pkgLite.packageName);
8613
8614                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8615                            pkgLite.versionCode);
8616
8617                    if (verificationParams != null) {
8618                        if (verificationParams.getVerificationURI() != null) {
8619                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8620                                 verificationParams.getVerificationURI());
8621                        }
8622                        if (verificationParams.getOriginatingURI() != null) {
8623                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8624                                  verificationParams.getOriginatingURI());
8625                        }
8626                        if (verificationParams.getReferrer() != null) {
8627                            verification.putExtra(Intent.EXTRA_REFERRER,
8628                                  verificationParams.getReferrer());
8629                        }
8630                        if (verificationParams.getOriginatingUid() >= 0) {
8631                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8632                                  verificationParams.getOriginatingUid());
8633                        }
8634                        if (verificationParams.getInstallerUid() >= 0) {
8635                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8636                                  verificationParams.getInstallerUid());
8637                        }
8638                    }
8639
8640                    final PackageVerificationState verificationState = new PackageVerificationState(
8641                            requiredUid, args);
8642
8643                    mPendingVerification.append(verificationId, verificationState);
8644
8645                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8646                            receivers, verificationState);
8647
8648                    /*
8649                     * If any sufficient verifiers were listed in the package
8650                     * manifest, attempt to ask them.
8651                     */
8652                    if (sufficientVerifiers != null) {
8653                        final int N = sufficientVerifiers.size();
8654                        if (N == 0) {
8655                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8656                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8657                        } else {
8658                            for (int i = 0; i < N; i++) {
8659                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8660
8661                                final Intent sufficientIntent = new Intent(verification);
8662                                sufficientIntent.setComponent(verifierComponent);
8663
8664                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8665                            }
8666                        }
8667                    }
8668
8669                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8670                            mRequiredVerifierPackage, receivers);
8671                    if (ret == PackageManager.INSTALL_SUCCEEDED
8672                            && mRequiredVerifierPackage != null) {
8673                        /*
8674                         * Send the intent to the required verification agent,
8675                         * but only start the verification timeout after the
8676                         * target BroadcastReceivers have run.
8677                         */
8678                        verification.setComponent(requiredVerifierComponent);
8679                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8680                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8681                                new BroadcastReceiver() {
8682                                    @Override
8683                                    public void onReceive(Context context, Intent intent) {
8684                                        final Message msg = mHandler
8685                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8686                                        msg.arg1 = verificationId;
8687                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8688                                    }
8689                                }, null, 0, null, null);
8690
8691                        /*
8692                         * We don't want the copy to proceed until verification
8693                         * succeeds, so null out this field.
8694                         */
8695                        mArgs = null;
8696                    }
8697                } else {
8698                    /*
8699                     * No package verification is enabled, so immediately start
8700                     * the remote call to initiate copy using temporary file.
8701                     */
8702                    ret = args.copyApk(mContainerService, true);
8703                }
8704            }
8705
8706            mRet = ret;
8707        }
8708
8709        @Override
8710        void handleReturnCode() {
8711            // If mArgs is null, then MCS couldn't be reached. When it
8712            // reconnects, it will try again to install. At that point, this
8713            // will succeed.
8714            if (mArgs != null) {
8715                processPendingInstall(mArgs, mRet);
8716            }
8717        }
8718
8719        @Override
8720        void handleServiceError() {
8721            mArgs = createInstallArgs(this);
8722            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8723        }
8724
8725        public boolean isForwardLocked() {
8726            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8727        }
8728    }
8729
8730    /*
8731     * Utility class used in movePackage api.
8732     * srcArgs and targetArgs are not set for invalid flags and make
8733     * sure to do null checks when invoking methods on them.
8734     * We probably want to return ErrorPrams for both failed installs
8735     * and moves.
8736     */
8737    class MoveParams extends HandlerParams {
8738        final IPackageMoveObserver observer;
8739        final int flags;
8740        final String packageName;
8741        final InstallArgs srcArgs;
8742        final InstallArgs targetArgs;
8743        int uid;
8744        int mRet;
8745
8746        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8747                String packageName, String instructionSet, int uid, UserHandle user) {
8748            super(user);
8749            this.srcArgs = srcArgs;
8750            this.observer = observer;
8751            this.flags = flags;
8752            this.packageName = packageName;
8753            this.uid = uid;
8754            if (srcArgs != null) {
8755                final String codePath = srcArgs.getCodePath();
8756                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName,
8757                        instructionSet);
8758            } else {
8759                targetArgs = null;
8760            }
8761        }
8762
8763        @Override
8764        public String toString() {
8765            return "MoveParams{"
8766                + Integer.toHexString(System.identityHashCode(this))
8767                + " " + packageName + "}";
8768        }
8769
8770        public void handleStartCopy() throws RemoteException {
8771            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8772            // Check for storage space on target medium
8773            if (!targetArgs.checkFreeStorage(mContainerService)) {
8774                Log.w(TAG, "Insufficient storage to install");
8775                return;
8776            }
8777
8778            mRet = srcArgs.doPreCopy();
8779            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8780                return;
8781            }
8782
8783            mRet = targetArgs.copyApk(mContainerService, false);
8784            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8785                srcArgs.doPostCopy(uid);
8786                return;
8787            }
8788
8789            mRet = srcArgs.doPostCopy(uid);
8790            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8791                return;
8792            }
8793
8794            mRet = targetArgs.doPreInstall(mRet);
8795            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8796                return;
8797            }
8798
8799            if (DEBUG_SD_INSTALL) {
8800                StringBuilder builder = new StringBuilder();
8801                if (srcArgs != null) {
8802                    builder.append("src: ");
8803                    builder.append(srcArgs.getCodePath());
8804                }
8805                if (targetArgs != null) {
8806                    builder.append(" target : ");
8807                    builder.append(targetArgs.getCodePath());
8808                }
8809                Log.i(TAG, builder.toString());
8810            }
8811        }
8812
8813        @Override
8814        void handleReturnCode() {
8815            targetArgs.doPostInstall(mRet, uid);
8816            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8817            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8818                currentStatus = PackageManager.MOVE_SUCCEEDED;
8819            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8820                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8821            }
8822            processPendingMove(this, currentStatus);
8823        }
8824
8825        @Override
8826        void handleServiceError() {
8827            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8828        }
8829    }
8830
8831    /**
8832     * Used during creation of InstallArgs
8833     *
8834     * @param flags package installation flags
8835     * @return true if should be installed on external storage
8836     */
8837    private static boolean installOnSd(int flags) {
8838        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8839            return false;
8840        }
8841        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8842            return true;
8843        }
8844        return false;
8845    }
8846
8847    /**
8848     * Used during creation of InstallArgs
8849     *
8850     * @param flags package installation flags
8851     * @return true if should be installed as forward locked
8852     */
8853    private static boolean installForwardLocked(int flags) {
8854        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8855    }
8856
8857    private InstallArgs createInstallArgs(InstallParams params) {
8858        // TODO: extend to support incoming zero-copy locations
8859
8860        if (installOnSd(params.flags) || params.isForwardLocked()) {
8861            return new AsecInstallArgs(params);
8862        } else {
8863            return new FileInstallArgs(params);
8864        }
8865    }
8866
8867    /**
8868     * Create args that describe an existing installed package. Typically used
8869     * when cleaning up old installs, or used as a move source.
8870     */
8871    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
8872            String resourcePath, String nativeLibraryPath, String instructionSet) {
8873        final boolean isInAsec;
8874        if (installOnSd(flags)) {
8875            /* Apps on SD card are always in ASEC containers. */
8876            isInAsec = true;
8877        } else if (installForwardLocked(flags)
8878                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8879            /*
8880             * Forward-locked apps are only in ASEC containers if they're the
8881             * new style
8882             */
8883            isInAsec = true;
8884        } else {
8885            isInAsec = false;
8886        }
8887
8888        if (isInAsec) {
8889            return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath,
8890                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8891        } else {
8892            return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet);
8893        }
8894    }
8895
8896    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
8897            String instructionSet) {
8898        final File codeFile = new File(codePath);
8899        if (installOnSd(flags) || installForwardLocked(flags)) {
8900            String cid = getNextCodePath(codePath, pkgName, "/"
8901                    + AsecInstallArgs.RES_FILE_NAME);
8902            return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags),
8903                    installForwardLocked(flags));
8904        } else {
8905            return new FileInstallArgs(codeFile, instructionSet);
8906        }
8907    }
8908
8909    static abstract class InstallArgs {
8910        /** @see InstallParams#originFile */
8911        final File originFile;
8912        /** @see InstallParams#originStaged */
8913        final boolean originStaged;
8914
8915        // TODO: define inherit location
8916
8917        final IPackageInstallObserver2 observer;
8918        // Always refers to PackageManager flags only
8919        final int flags;
8920        final String installerPackageName;
8921        final ManifestDigest manifestDigest;
8922        final UserHandle user;
8923        final String instructionSet;
8924        final String abiOverride;
8925
8926        InstallArgs(File originFile, boolean originStaged, IPackageInstallObserver2 observer,
8927                int flags, String installerPackageName, ManifestDigest manifestDigest,
8928                UserHandle user, String instructionSet, String abiOverride) {
8929            this.originFile = originFile;
8930            this.originStaged = originStaged;
8931            this.flags = flags;
8932            this.observer = observer;
8933            this.installerPackageName = installerPackageName;
8934            this.manifestDigest = manifestDigest;
8935            this.user = user;
8936            this.instructionSet = instructionSet;
8937            this.abiOverride = abiOverride;
8938        }
8939
8940        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8941        abstract int doPreInstall(int status);
8942
8943        /**
8944         * Rename package into final resting place. All paths on the given
8945         * scanned package should be updated to reflect the rename.
8946         */
8947        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8948        abstract int doPostInstall(int status, int uid);
8949
8950        /** @see PackageSettingBase#codePathString */
8951        abstract String getCodePath();
8952        /** @see PackageSettingBase#resourcePathString */
8953        abstract String getResourcePath();
8954        /** @see PackageSettingBase#nativeLibraryPathString */
8955        abstract String getNativeLibraryPath();
8956
8957        // Need installer lock especially for dex file removal.
8958        abstract void cleanUpResourcesLI();
8959        abstract boolean doPostDeleteLI(boolean delete);
8960        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8961
8962        /**
8963         * Called before the source arguments are copied. This is used mostly
8964         * for MoveParams when it needs to read the source file to put it in the
8965         * destination.
8966         */
8967        int doPreCopy() {
8968            return PackageManager.INSTALL_SUCCEEDED;
8969        }
8970
8971        /**
8972         * Called after the source arguments are copied. This is used mostly for
8973         * MoveParams when it needs to read the source file to put it in the
8974         * destination.
8975         *
8976         * @return
8977         */
8978        int doPostCopy(int uid) {
8979            return PackageManager.INSTALL_SUCCEEDED;
8980        }
8981
8982        protected boolean isFwdLocked() {
8983            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8984        }
8985
8986        UserHandle getUser() {
8987            return user;
8988        }
8989    }
8990
8991    /**
8992     * Logic to handle installation of non-ASEC applications, including copying
8993     * and renaming logic.
8994     */
8995    class FileInstallArgs extends InstallArgs {
8996        private File codeFile;
8997        private File resourceFile;
8998        private File nativeLibraryFile;
8999
9000        // Example topology:
9001        // /data/app/com.example/base.apk
9002        // /data/app/com.example/split_foo.apk
9003        // /data/app/com.example/lib/arm/libfoo.so
9004        // /data/app/com.example/lib/arm64/libfoo.so
9005        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9006
9007        /** New install */
9008        FileInstallArgs(InstallParams params) {
9009            super(params.originFile, params.originStaged, params.observer, params.flags,
9010                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9011                    params.packageInstructionSetOverride, params.packageAbiOverride);
9012            if (isFwdLocked()) {
9013                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9014            }
9015        }
9016
9017        /** Existing install */
9018        FileInstallArgs(String codePath, String resourcePath, String nativeLibraryPath,
9019                String instructionSet) {
9020            super(null, false, null, 0, null, null, null, instructionSet, null);
9021            this.codeFile = (codePath != null) ? new File(codePath) : null;
9022            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9023            this.nativeLibraryFile = (nativeLibraryPath != null) ? new File(nativeLibraryPath) : null;
9024        }
9025
9026        /** New install from existing */
9027        FileInstallArgs(File originFile, String instructionSet) {
9028            super(originFile, false, null, 0, null, null, null, instructionSet, null);
9029        }
9030
9031        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9032            final long lowThreshold;
9033
9034            final DeviceStorageMonitorInternal
9035                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9036            if (dsm == null) {
9037                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9038                lowThreshold = 0L;
9039            } else {
9040                if (dsm.isMemoryLow()) {
9041                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9042                    return false;
9043                }
9044
9045                lowThreshold = dsm.getMemoryLowThreshold();
9046            }
9047
9048            return imcs.checkInternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9049                    lowThreshold);
9050        }
9051
9052        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9053            int ret = PackageManager.INSTALL_SUCCEEDED;
9054
9055            if (originStaged) {
9056                Slog.d(TAG, originFile + " already staged; skipping copy");
9057                codeFile = originFile;
9058                resourceFile = originFile;
9059            } else {
9060                try {
9061                    final File tempDir = mInstallerService.allocateSessionDir();
9062                    codeFile = tempDir;
9063                    resourceFile = tempDir;
9064                } catch (IOException e) {
9065                    Slog.w(TAG, "Failed to create copy file: " + e);
9066                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9067                }
9068
9069                final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9070                    @Override
9071                    public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9072                        if (!FileUtils.isValidExtFilename(name)) {
9073                            throw new IllegalArgumentException("Invalid filename: " + name);
9074                        }
9075                        try {
9076                            final File file = new File(codeFile, name);
9077                            final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9078                                    O_RDWR | O_CREAT, 0644);
9079                            Os.chmod(file.getAbsolutePath(), 0644);
9080                            return new ParcelFileDescriptor(fd);
9081                        } catch (ErrnoException e) {
9082                            throw new RemoteException("Failed to open: " + e.getMessage());
9083                        }
9084                    }
9085                };
9086
9087                ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9088                if (ret != PackageManager.INSTALL_SUCCEEDED) {
9089                    Slog.e(TAG, "Failed to copy package");
9090                    return ret;
9091                }
9092            }
9093
9094            String[] abiList = (abiOverride != null) ?
9095                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9096            NativeLibraryHelper.Handle handle = null;
9097            try {
9098                handle = NativeLibraryHelper.Handle.create(codeFile);
9099                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9100                        abiOverride == null &&
9101                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9102                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9103                }
9104
9105                // TODO: refactor to avoid double findSupportedAbi()
9106                final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9107                if (abiIndex < 0 && abiIndex != PackageManager.NO_NATIVE_LIBRARIES) {
9108                    return abiIndex;
9109                } else if (abiIndex >= 0) {
9110                    final File baseLibFile = new File(codeFile, LIB_DIR_NAME);
9111                    baseLibFile.mkdir();
9112                    Os.chmod(baseLibFile.getAbsolutePath(), 0755);
9113
9114                    final String abi = Build.SUPPORTED_ABIS[abiIndex];
9115                    final String instructionSet = VMRuntime.getInstructionSet(abi);
9116                    nativeLibraryFile = new File(baseLibFile, instructionSet);
9117                    nativeLibraryFile.mkdir();
9118                    Os.chmod(nativeLibraryFile.getAbsolutePath(), 0755);
9119
9120                    copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9121                }
9122            } catch (IOException | ErrnoException e) {
9123                Slog.e(TAG, "Copying native libraries failed", e);
9124                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9125            } finally {
9126                IoUtils.closeQuietly(handle);
9127            }
9128
9129            return ret;
9130        }
9131
9132        int doPreInstall(int status) {
9133            if (status != PackageManager.INSTALL_SUCCEEDED) {
9134                cleanUp();
9135            }
9136            return status;
9137        }
9138
9139        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9140            if (status != PackageManager.INSTALL_SUCCEEDED) {
9141                cleanUp();
9142                return false;
9143            } else {
9144                final File beforeCodeFile = codeFile;
9145                final File afterCodeFile = new File(mAppInstallDir,
9146                        getNextCodePath(oldCodePath, pkg.packageName, null));
9147
9148                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9149                if (!beforeCodeFile.renameTo(afterCodeFile)) {
9150                    return false;
9151                }
9152                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9153                    return false;
9154                }
9155
9156                // Reflect the rename internally
9157                codeFile = afterCodeFile;
9158                resourceFile = afterCodeFile;
9159                nativeLibraryFile = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9160                        nativeLibraryFile);
9161
9162                // Reflect the rename in scanned details
9163                pkg.codePath = afterCodeFile.getAbsolutePath();
9164                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9165                        pkg.baseCodePath);
9166                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9167                        pkg.splitCodePaths);
9168
9169                // Reflect the rename in app info
9170                pkg.applicationInfo.setCodePath(pkg.codePath);
9171                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9172                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9173                pkg.applicationInfo.setResourcePath(pkg.codePath);
9174                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9175                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9176                pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath();
9177
9178                return true;
9179            }
9180        }
9181
9182        int doPostInstall(int status, int uid) {
9183            if (status != PackageManager.INSTALL_SUCCEEDED) {
9184                cleanUp();
9185            }
9186            return status;
9187        }
9188
9189        @Override
9190        String getCodePath() {
9191            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9192        }
9193
9194        @Override
9195        String getResourcePath() {
9196            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9197        }
9198
9199        @Override
9200        String getNativeLibraryPath() {
9201            return (nativeLibraryFile != null) ? nativeLibraryFile.getAbsolutePath() : null;
9202        }
9203
9204        private boolean cleanUp() {
9205            if (codeFile == null || !codeFile.exists()) {
9206                return false;
9207            }
9208
9209            if (codeFile.isDirectory()) {
9210                FileUtils.deleteContents(codeFile);
9211            }
9212            codeFile.delete();
9213
9214            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9215                resourceFile.delete();
9216            }
9217
9218            if (nativeLibraryFile != null && !FileUtils.contains(codeFile, nativeLibraryFile)) {
9219                FileUtils.deleteContents(nativeLibraryFile);
9220                nativeLibraryFile.delete();
9221            }
9222
9223            return true;
9224        }
9225
9226        void cleanUpResourcesLI() {
9227            // Try enumerating all code paths before deleting
9228            List<String> allCodePaths = Collections.EMPTY_LIST;
9229            if (codeFile != null && codeFile.exists()) {
9230                try {
9231                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9232                    allCodePaths = pkg.getAllCodePaths();
9233                } catch (PackageParserException e) {
9234                    // Ignored; we tried our best
9235                }
9236            }
9237
9238            cleanUp();
9239
9240            if (!allCodePaths.isEmpty()) {
9241                if (instructionSet == null) {
9242                    throw new IllegalStateException("instructionSet == null");
9243                }
9244
9245                for (String codePath : allCodePaths) {
9246                    int retCode = mInstaller.rmdex(codePath, instructionSet);
9247                    if (retCode < 0) {
9248                        Slog.w(TAG, "Couldn't remove dex file for package: "
9249                                +  " at location " + codePath + ", retcode=" + retCode);
9250                        // we don't consider this to be a failure of the core package deletion
9251                    }
9252                }
9253            }
9254        }
9255
9256        boolean doPostDeleteLI(boolean delete) {
9257            // XXX err, shouldn't we respect the delete flag?
9258            cleanUpResourcesLI();
9259            return true;
9260        }
9261    }
9262
9263    private boolean isAsecExternal(String cid) {
9264        final String asecPath = PackageHelper.getSdFilesystem(cid);
9265        return !asecPath.startsWith(mAsecInternalPath);
9266    }
9267
9268    /**
9269     * Extract the MountService "container ID" from the full code path of an
9270     * .apk.
9271     */
9272    static String cidFromCodePath(String fullCodePath) {
9273        int eidx = fullCodePath.lastIndexOf("/");
9274        String subStr1 = fullCodePath.substring(0, eidx);
9275        int sidx = subStr1.lastIndexOf("/");
9276        return subStr1.substring(sidx+1, eidx);
9277    }
9278
9279    /**
9280     * Logic to handle installation of ASEC applications, including copying and
9281     * renaming logic.
9282     */
9283    class AsecInstallArgs extends InstallArgs {
9284        // TODO: teach about handling cluster directories
9285
9286        static final String RES_FILE_NAME = "pkg.apk";
9287        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9288
9289        String cid;
9290        String packagePath;
9291        String resourcePath;
9292        String libraryPath;
9293
9294        /** New install */
9295        AsecInstallArgs(InstallParams params) {
9296            super(params.originFile, params.originStaged, params.observer, params.flags,
9297                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9298                    params.packageInstructionSetOverride, params.packageAbiOverride);
9299        }
9300
9301        /** Existing install */
9302        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9303                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9304            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9305                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9306                    instructionSet, null);
9307            // Extract cid from fullCodePath
9308            int eidx = fullCodePath.lastIndexOf("/");
9309            String subStr1 = fullCodePath.substring(0, eidx);
9310            int sidx = subStr1.lastIndexOf("/");
9311            cid = subStr1.substring(sidx+1, eidx);
9312            setCachePath(subStr1);
9313        }
9314
9315        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9316            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9317                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9318                    instructionSet, null);
9319            this.cid = cid;
9320            setCachePath(PackageHelper.getSdDir(cid));
9321        }
9322
9323        /** New install from existing */
9324        AsecInstallArgs(File originPackageFile, String cid, String instructionSet,
9325                boolean isExternal, boolean isForwardLocked) {
9326            super(originPackageFile, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9327                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9328                    instructionSet, null);
9329            this.cid = cid;
9330        }
9331
9332        void createCopyFile() {
9333            cid = getTempContainerId();
9334        }
9335
9336        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9337            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9338                    abiOverride);
9339        }
9340
9341        private final boolean isExternal() {
9342            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9343        }
9344
9345        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9346            if (temp) {
9347                createCopyFile();
9348            } else {
9349                /*
9350                 * Pre-emptively destroy the container since it's destroyed if
9351                 * copying fails due to it existing anyway.
9352                 */
9353                PackageHelper.destroySdDir(cid);
9354            }
9355
9356            final String newCachePath = imcs.copyPackageToContainer(
9357                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9358                    isFwdLocked(), abiOverride);
9359
9360            if (newCachePath != null) {
9361                setCachePath(newCachePath);
9362                return PackageManager.INSTALL_SUCCEEDED;
9363            } else {
9364                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9365            }
9366        }
9367
9368        @Override
9369        String getCodePath() {
9370            return packagePath;
9371        }
9372
9373        @Override
9374        String getResourcePath() {
9375            return resourcePath;
9376        }
9377
9378        @Override
9379        String getNativeLibraryPath() {
9380            return libraryPath;
9381        }
9382
9383        int doPreInstall(int status) {
9384            if (status != PackageManager.INSTALL_SUCCEEDED) {
9385                // Destroy container
9386                PackageHelper.destroySdDir(cid);
9387            } else {
9388                boolean mounted = PackageHelper.isContainerMounted(cid);
9389                if (!mounted) {
9390                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9391                            Process.SYSTEM_UID);
9392                    if (newCachePath != null) {
9393                        setCachePath(newCachePath);
9394                    } else {
9395                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9396                    }
9397                }
9398            }
9399            return status;
9400        }
9401
9402        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9403            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9404            String newCachePath = null;
9405            if (PackageHelper.isContainerMounted(cid)) {
9406                // Unmount the container
9407                if (!PackageHelper.unMountSdDir(cid)) {
9408                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9409                    return false;
9410                }
9411            }
9412            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9413                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9414                        " which might be stale. Will try to clean up.");
9415                // Clean up the stale container and proceed to recreate.
9416                if (!PackageHelper.destroySdDir(newCacheId)) {
9417                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9418                    return false;
9419                }
9420                // Successfully cleaned up stale container. Try to rename again.
9421                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9422                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9423                            + " inspite of cleaning it up.");
9424                    return false;
9425                }
9426            }
9427            if (!PackageHelper.isContainerMounted(newCacheId)) {
9428                Slog.w(TAG, "Mounting container " + newCacheId);
9429                newCachePath = PackageHelper.mountSdDir(newCacheId,
9430                        getEncryptKey(), Process.SYSTEM_UID);
9431            } else {
9432                newCachePath = PackageHelper.getSdDir(newCacheId);
9433            }
9434            if (newCachePath == null) {
9435                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9436                return false;
9437            }
9438            Log.i(TAG, "Succesfully renamed " + cid +
9439                    " to " + newCacheId +
9440                    " at new path: " + newCachePath);
9441            cid = newCacheId;
9442            setCachePath(newCachePath);
9443
9444            // TODO: extend to support split APKs
9445            pkg.codePath = getCodePath();
9446            pkg.baseCodePath = getCodePath();
9447            pkg.splitCodePaths = null;
9448
9449            pkg.applicationInfo.setCodePath(getCodePath());
9450            pkg.applicationInfo.setBaseCodePath(getCodePath());
9451            pkg.applicationInfo.setSplitCodePaths(null);
9452            pkg.applicationInfo.setResourcePath(getResourcePath());
9453            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9454            pkg.applicationInfo.setSplitResourcePaths(null);
9455            pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath();
9456
9457            return true;
9458        }
9459
9460        private void setCachePath(String newCachePath) {
9461            File cachePath = new File(newCachePath);
9462            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9463            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9464
9465            if (isFwdLocked()) {
9466                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9467            } else {
9468                resourcePath = packagePath;
9469            }
9470        }
9471
9472        int doPostInstall(int status, int uid) {
9473            if (status != PackageManager.INSTALL_SUCCEEDED) {
9474                cleanUp();
9475            } else {
9476                final int groupOwner;
9477                final String protectedFile;
9478                if (isFwdLocked()) {
9479                    groupOwner = UserHandle.getSharedAppGid(uid);
9480                    protectedFile = RES_FILE_NAME;
9481                } else {
9482                    groupOwner = -1;
9483                    protectedFile = null;
9484                }
9485
9486                if (uid < Process.FIRST_APPLICATION_UID
9487                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9488                    Slog.e(TAG, "Failed to finalize " + cid);
9489                    PackageHelper.destroySdDir(cid);
9490                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9491                }
9492
9493                boolean mounted = PackageHelper.isContainerMounted(cid);
9494                if (!mounted) {
9495                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9496                }
9497            }
9498            return status;
9499        }
9500
9501        private void cleanUp() {
9502            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9503
9504            // Destroy secure container
9505            PackageHelper.destroySdDir(cid);
9506        }
9507
9508        void cleanUpResourcesLI() {
9509            String sourceFile = getCodePath();
9510            // Remove dex file
9511            if (instructionSet == null) {
9512                throw new IllegalStateException("instructionSet == null");
9513            }
9514            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9515            if (retCode < 0) {
9516                Slog.w(TAG, "Couldn't remove dex file for package: "
9517                        + " at location "
9518                        + sourceFile.toString() + ", retcode=" + retCode);
9519                // we don't consider this to be a failure of the core package deletion
9520            }
9521            cleanUp();
9522        }
9523
9524        boolean matchContainer(String app) {
9525            if (cid.startsWith(app)) {
9526                return true;
9527            }
9528            return false;
9529        }
9530
9531        String getPackageName() {
9532            return getAsecPackageName(cid);
9533        }
9534
9535        boolean doPostDeleteLI(boolean delete) {
9536            boolean ret = false;
9537            boolean mounted = PackageHelper.isContainerMounted(cid);
9538            if (mounted) {
9539                // Unmount first
9540                ret = PackageHelper.unMountSdDir(cid);
9541            }
9542            if (ret && delete) {
9543                cleanUpResourcesLI();
9544            }
9545            return ret;
9546        }
9547
9548        @Override
9549        int doPreCopy() {
9550            if (isFwdLocked()) {
9551                if (!PackageHelper.fixSdPermissions(cid,
9552                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9553                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9554                }
9555            }
9556
9557            return PackageManager.INSTALL_SUCCEEDED;
9558        }
9559
9560        @Override
9561        int doPostCopy(int uid) {
9562            if (isFwdLocked()) {
9563                if (uid < Process.FIRST_APPLICATION_UID
9564                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9565                                RES_FILE_NAME)) {
9566                    Slog.e(TAG, "Failed to finalize " + cid);
9567                    PackageHelper.destroySdDir(cid);
9568                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9569                }
9570            }
9571
9572            return PackageManager.INSTALL_SUCCEEDED;
9573        }
9574    }
9575
9576    static String getAsecPackageName(String packageCid) {
9577        int idx = packageCid.lastIndexOf("-");
9578        if (idx == -1) {
9579            return packageCid;
9580        }
9581        return packageCid.substring(0, idx);
9582    }
9583
9584    // Utility method used to create code paths based on package name and available index.
9585    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9586        String idxStr = "";
9587        int idx = 1;
9588        // Fall back to default value of idx=1 if prefix is not
9589        // part of oldCodePath
9590        if (oldCodePath != null) {
9591            String subStr = oldCodePath;
9592            // Drop the suffix right away
9593            if (suffix != null && subStr.endsWith(suffix)) {
9594                subStr = subStr.substring(0, subStr.length() - suffix.length());
9595            }
9596            // If oldCodePath already contains prefix find out the
9597            // ending index to either increment or decrement.
9598            int sidx = subStr.lastIndexOf(prefix);
9599            if (sidx != -1) {
9600                subStr = subStr.substring(sidx + prefix.length());
9601                if (subStr != null) {
9602                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9603                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9604                    }
9605                    try {
9606                        idx = Integer.parseInt(subStr);
9607                        if (idx <= 1) {
9608                            idx++;
9609                        } else {
9610                            idx--;
9611                        }
9612                    } catch(NumberFormatException e) {
9613                    }
9614                }
9615            }
9616        }
9617        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9618        return prefix + idxStr;
9619    }
9620
9621    // Utility method used to ignore ADD/REMOVE events
9622    // by directory observer.
9623    private static boolean ignoreCodePath(String fullPathStr) {
9624        String apkName = deriveCodePathName(fullPathStr);
9625        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9626        if (idx != -1 && ((idx+1) < apkName.length())) {
9627            // Make sure the package ends with a numeral
9628            String version = apkName.substring(idx+1);
9629            try {
9630                Integer.parseInt(version);
9631                return true;
9632            } catch (NumberFormatException e) {}
9633        }
9634        return false;
9635    }
9636
9637    // Utility method that returns the relative package path with respect
9638    // to the installation directory. Like say for /data/data/com.test-1.apk
9639    // string com.test-1 is returned.
9640    static String deriveCodePathName(String codePath) {
9641        if (codePath == null) {
9642            return null;
9643        }
9644        final File codeFile = new File(codePath);
9645        final String name = codeFile.getName();
9646        if (codeFile.isDirectory()) {
9647            return name;
9648        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9649            final int lastDot = name.lastIndexOf('.');
9650            return name.substring(0, lastDot);
9651        } else {
9652            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9653            return null;
9654        }
9655    }
9656
9657    class PackageInstalledInfo {
9658        String name;
9659        int uid;
9660        // The set of users that originally had this package installed.
9661        int[] origUsers;
9662        // The set of users that now have this package installed.
9663        int[] newUsers;
9664        PackageParser.Package pkg;
9665        int returnCode;
9666        PackageRemovedInfo removedInfo;
9667
9668        // In some error cases we want to convey more info back to the observer
9669        String origPackage;
9670        String origPermission;
9671    }
9672
9673    /*
9674     * Install a non-existing package.
9675     */
9676    private void installNewPackageLI(PackageParser.Package pkg,
9677            int parseFlags, int scanMode, UserHandle user,
9678            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9679        // Remember this for later, in case we need to rollback this install
9680        String pkgName = pkg.packageName;
9681
9682        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9683        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9684        synchronized(mPackages) {
9685            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9686                // A package with the same name is already installed, though
9687                // it has been renamed to an older name.  The package we
9688                // are trying to install should be installed as an update to
9689                // the existing one, but that has not been requested, so bail.
9690                Slog.w(TAG, "Attempt to re-install " + pkgName
9691                        + " without first uninstalling package running as "
9692                        + mSettings.mRenamedPackages.get(pkgName));
9693                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9694                return;
9695            }
9696            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9697                // Don't allow installation over an existing package with the same name.
9698                Slog.w(TAG, "Attempt to re-install " + pkgName
9699                        + " without first uninstalling.");
9700                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9701                return;
9702            }
9703        }
9704        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9705        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9706                System.currentTimeMillis(), user, abiOverride);
9707        if (newPackage == null) {
9708            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9709            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9710                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9711            }
9712        } else {
9713            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9714            // delete the partially installed application. the data directory will have to be
9715            // restored if it was already existing
9716            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9717                // remove package from internal structures.  Note that we want deletePackageX to
9718                // delete the package data and cache directories that it created in
9719                // scanPackageLocked, unless those directories existed before we even tried to
9720                // install.
9721                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9722                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9723                                res.removedInfo, true);
9724            }
9725        }
9726    }
9727
9728    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9729        // Upgrade keysets are being used.  Determine if new package has a superset of the
9730        // required keys.
9731        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9732        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9733        Set<Long> newSigningKeyIds = new ArraySet<Long>();
9734        for (PublicKey pk : newPkg.mSigningKeys) {
9735            newSigningKeyIds.add(ksms.getIdForPublicKey(pk));
9736        }
9737        //remove PUBLIC_KEY_NOT_FOUND, although not necessary
9738        newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND);
9739        for (int i = 0; i < upgradeKeySets.length; i++) {
9740            if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) {
9741                return true;
9742            }
9743        }
9744        return false;
9745    }
9746
9747    private void replacePackageLI(PackageParser.Package pkg,
9748            int parseFlags, int scanMode, UserHandle user,
9749            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9750        PackageParser.Package oldPackage;
9751        String pkgName = pkg.packageName;
9752        int[] allUsers;
9753        boolean[] perUserInstalled;
9754
9755        // First find the old package info and check signatures
9756        synchronized(mPackages) {
9757            oldPackage = mPackages.get(pkgName);
9758            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9759            PackageSetting ps = mSettings.mPackages.get(pkgName);
9760            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9761                // default to original signature matching
9762                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9763                    != PackageManager.SIGNATURE_MATCH) {
9764                    Slog.w(TAG, "New package has a different signature: " + pkgName);
9765                    res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9766                    return;
9767                }
9768            } else {
9769                if(!checkUpgradeKeySetLP(ps, pkg)) {
9770                    Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: "
9771                           + pkgName);
9772                    res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9773                    return;
9774                }
9775            }
9776
9777            // In case of rollback, remember per-user/profile install state
9778            allUsers = sUserManager.getUserIds();
9779            perUserInstalled = new boolean[allUsers.length];
9780            for (int i = 0; i < allUsers.length; i++) {
9781                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9782            }
9783        }
9784        boolean sysPkg = (isSystemApp(oldPackage));
9785        if (sysPkg) {
9786            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9787                    user, allUsers, perUserInstalled, installerPackageName, res,
9788                    abiOverride);
9789        } else {
9790            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9791                    user, allUsers, perUserInstalled, installerPackageName, res,
9792                    abiOverride);
9793        }
9794    }
9795
9796    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9797            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9798            int[] allUsers, boolean[] perUserInstalled,
9799            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9800        PackageParser.Package newPackage = null;
9801        String pkgName = deletedPackage.packageName;
9802        boolean deletedPkg = true;
9803        boolean updatedSettings = false;
9804
9805        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9806                + deletedPackage);
9807        long origUpdateTime;
9808        if (pkg.mExtras != null) {
9809            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9810        } else {
9811            origUpdateTime = 0;
9812        }
9813
9814        // First delete the existing package while retaining the data directory
9815        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9816                res.removedInfo, true)) {
9817            // If the existing package wasn't successfully deleted
9818            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9819            deletedPkg = false;
9820        } else {
9821            // Successfully deleted the old package. Now proceed with re-installation
9822            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9823            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9824                    System.currentTimeMillis(), user, abiOverride);
9825            if (newPackage == null) {
9826                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9827                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9828                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9829                }
9830            } else {
9831                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9832                updatedSettings = true;
9833            }
9834        }
9835
9836        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9837            // remove package from internal structures.  Note that we want deletePackageX to
9838            // delete the package data and cache directories that it created in
9839            // scanPackageLocked, unless those directories existed before we even tried to
9840            // install.
9841            if(updatedSettings) {
9842                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9843                deletePackageLI(
9844                        pkgName, null, true, allUsers, perUserInstalled,
9845                        PackageManager.DELETE_KEEP_DATA,
9846                                res.removedInfo, true);
9847            }
9848            // Since we failed to install the new package we need to restore the old
9849            // package that we deleted.
9850            if (deletedPkg) {
9851                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9852                File restoreFile = new File(deletedPackage.codePath);
9853                // Parse old package
9854                boolean oldOnSd = isExternal(deletedPackage);
9855                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9856                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9857                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9858                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9859                        | SCAN_UPDATE_TIME;
9860                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9861                        origUpdateTime, null, null) == null) {
9862                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9863                    return;
9864                }
9865                // Restore of old package succeeded. Update permissions.
9866                // writer
9867                synchronized (mPackages) {
9868                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9869                            UPDATE_PERMISSIONS_ALL);
9870                    // can downgrade to reader
9871                    mSettings.writeLPr();
9872                }
9873                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9874            }
9875        }
9876    }
9877
9878    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9879            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9880            int[] allUsers, boolean[] perUserInstalled,
9881            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9882        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9883                + ", old=" + deletedPackage);
9884        PackageParser.Package newPackage = null;
9885        boolean updatedSettings = false;
9886        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9887                PackageParser.PARSE_IS_SYSTEM;
9888        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9889            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9890        }
9891        String packageName = deletedPackage.packageName;
9892        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9893        if (packageName == null) {
9894            Slog.w(TAG, "Attempt to delete null packageName.");
9895            return;
9896        }
9897        PackageParser.Package oldPkg;
9898        PackageSetting oldPkgSetting;
9899        // reader
9900        synchronized (mPackages) {
9901            oldPkg = mPackages.get(packageName);
9902            oldPkgSetting = mSettings.mPackages.get(packageName);
9903            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9904                    (oldPkgSetting == null)) {
9905                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9906                return;
9907            }
9908        }
9909
9910        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9911
9912        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9913        res.removedInfo.removedPackage = packageName;
9914        // Remove existing system package
9915        removePackageLI(oldPkgSetting, true);
9916        // writer
9917        synchronized (mPackages) {
9918            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9919                // We didn't need to disable the .apk as a current system package,
9920                // which means we are replacing another update that is already
9921                // installed.  We need to make sure to delete the older one's .apk.
9922                res.removedInfo.args = createInstallArgsForExisting(0,
9923                        deletedPackage.applicationInfo.getCodePath(),
9924                        deletedPackage.applicationInfo.getResourcePath(),
9925                        deletedPackage.applicationInfo.nativeLibraryDir,
9926                        getAppInstructionSet(deletedPackage.applicationInfo));
9927            } else {
9928                res.removedInfo.args = null;
9929            }
9930        }
9931
9932        // Successfully disabled the old package. Now proceed with re-installation
9933        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9934        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9935        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
9936        if (newPackage == null) {
9937            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9938            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9939                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9940            }
9941        } else {
9942            if (newPackage.mExtras != null) {
9943                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9944                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9945                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9946
9947                // is the update attempting to change shared user? that isn't going to work...
9948                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9949                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9950                            + " to " + newPkgSetting.sharedUser);
9951                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9952                    updatedSettings = true;
9953                }
9954            }
9955
9956            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9957                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9958                updatedSettings = true;
9959            }
9960        }
9961
9962        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9963            // Re installation failed. Restore old information
9964            // Remove new pkg information
9965            if (newPackage != null) {
9966                removeInstalledPackageLI(newPackage, true);
9967            }
9968            // Add back the old system package
9969            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
9970            // Restore the old system information in Settings
9971            synchronized(mPackages) {
9972                if (updatedSettings) {
9973                    mSettings.enableSystemPackageLPw(packageName);
9974                    mSettings.setInstallerPackageName(packageName,
9975                            oldPkgSetting.installerPackageName);
9976                }
9977                mSettings.writeLPr();
9978            }
9979        }
9980    }
9981
9982    // Utility method used to move dex files during install.
9983    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
9984        // TODO: extend to move split APK dex files
9985        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9986            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
9987            int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
9988                                             instructionSet);
9989            if (retCode != 0) {
9990                /*
9991                 * Programs may be lazily run through dexopt, so the
9992                 * source may not exist. However, something seems to
9993                 * have gone wrong, so note that dexopt needs to be
9994                 * run again and remove the source file. In addition,
9995                 * remove the target to make sure there isn't a stale
9996                 * file from a previous version of the package.
9997                 */
9998                newPackage.mDexOptNeeded = true;
9999                mInstaller.rmdex(oldCodePath, instructionSet);
10000                mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
10001            }
10002        }
10003        return PackageManager.INSTALL_SUCCEEDED;
10004    }
10005
10006    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10007            int[] allUsers, boolean[] perUserInstalled,
10008            PackageInstalledInfo res) {
10009        String pkgName = newPackage.packageName;
10010        synchronized (mPackages) {
10011            //write settings. the installStatus will be incomplete at this stage.
10012            //note that the new package setting would have already been
10013            //added to mPackages. It hasn't been persisted yet.
10014            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10015            mSettings.writeLPr();
10016        }
10017
10018        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10019
10020        synchronized (mPackages) {
10021            updatePermissionsLPw(newPackage.packageName, newPackage,
10022                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10023                            ? UPDATE_PERMISSIONS_ALL : 0));
10024            // For system-bundled packages, we assume that installing an upgraded version
10025            // of the package implies that the user actually wants to run that new code,
10026            // so we enable the package.
10027            if (isSystemApp(newPackage)) {
10028                // NB: implicit assumption that system package upgrades apply to all users
10029                if (DEBUG_INSTALL) {
10030                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10031                }
10032                PackageSetting ps = mSettings.mPackages.get(pkgName);
10033                if (ps != null) {
10034                    if (res.origUsers != null) {
10035                        for (int userHandle : res.origUsers) {
10036                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10037                                    userHandle, installerPackageName);
10038                        }
10039                    }
10040                    // Also convey the prior install/uninstall state
10041                    if (allUsers != null && perUserInstalled != null) {
10042                        for (int i = 0; i < allUsers.length; i++) {
10043                            if (DEBUG_INSTALL) {
10044                                Slog.d(TAG, "    user " + allUsers[i]
10045                                        + " => " + perUserInstalled[i]);
10046                            }
10047                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10048                        }
10049                        // these install state changes will be persisted in the
10050                        // upcoming call to mSettings.writeLPr().
10051                    }
10052                }
10053            }
10054            res.name = pkgName;
10055            res.uid = newPackage.applicationInfo.uid;
10056            res.pkg = newPackage;
10057            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10058            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10059            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10060            //to update install status
10061            mSettings.writeLPr();
10062        }
10063    }
10064
10065    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10066        int pFlags = args.flags;
10067        String installerPackageName = args.installerPackageName;
10068        File tmpPackageFile = new File(args.getCodePath());
10069        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10070        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10071        boolean replace = false;
10072        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10073                | (newInstall ? SCAN_NEW_INSTALL : 0);
10074        // Result object to be returned
10075        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10076
10077        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10078        // Retrieve PackageSettings and parse package
10079        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10080                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10081                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10082        PackageParser pp = new PackageParser();
10083        pp.setSeparateProcesses(mSeparateProcesses);
10084        pp.setDisplayMetrics(mMetrics);
10085
10086        final PackageParser.Package pkg;
10087        try {
10088            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10089        } catch (PackageParserException e) {
10090            Slog.e(TAG, "Failed during install: " + e);
10091            res.returnCode = e.error;
10092            return;
10093        }
10094
10095        String pkgName = res.name = pkg.packageName;
10096        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10097            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10098                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10099                return;
10100            }
10101        }
10102
10103        try {
10104            pp.collectCertificates(pkg, parseFlags);
10105            pp.collectManifestDigest(pkg);
10106        } catch (PackageParserException e) {
10107            Slog.e(TAG, "Failed during install: " + e);
10108            res.returnCode = e.error;
10109            return;
10110        }
10111
10112        /* If the installer passed in a manifest digest, compare it now. */
10113        if (args.manifestDigest != null) {
10114            if (DEBUG_INSTALL) {
10115                final String parsedManifest = pkg.manifestDigest == null ? "null"
10116                        : pkg.manifestDigest.toString();
10117                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10118                        + parsedManifest);
10119            }
10120
10121            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10122                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10123                return;
10124            }
10125        } else if (DEBUG_INSTALL) {
10126            final String parsedManifest = pkg.manifestDigest == null
10127                    ? "null" : pkg.manifestDigest.toString();
10128            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10129        }
10130
10131        // Get rid of all references to package scan path via parser.
10132        pp = null;
10133        String oldCodePath = null;
10134        boolean systemApp = false;
10135        synchronized (mPackages) {
10136            // Check whether the newly-scanned package wants to define an already-defined perm
10137            int N = pkg.permissions.size();
10138            for (int i = N-1; i >= 0; i--) {
10139                PackageParser.Permission perm = pkg.permissions.get(i);
10140                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10141                if (bp != null) {
10142                    // If the defining package is signed with our cert, it's okay.  This
10143                    // also includes the "updating the same package" case, of course.
10144                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10145                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10146                        // If the owning package is the system itself, we log but allow
10147                        // install to proceed; we fail the install on all other permission
10148                        // redefinitions.
10149                        if (!bp.sourcePackage.equals("android")) {
10150                            Slog.w(TAG, "Package " + pkg.packageName
10151                                    + " attempting to redeclare permission " + perm.info.name
10152                                    + " already owned by " + bp.sourcePackage);
10153                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10154                            res.origPermission = perm.info.name;
10155                            res.origPackage = bp.sourcePackage;
10156                            return;
10157                        } else {
10158                            Slog.w(TAG, "Package " + pkg.packageName
10159                                    + " attempting to redeclare system permission "
10160                                    + perm.info.name + "; ignoring new declaration");
10161                            pkg.permissions.remove(i);
10162                        }
10163                    }
10164                }
10165            }
10166
10167            // Check if installing already existing package
10168            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10169                String oldName = mSettings.mRenamedPackages.get(pkgName);
10170                if (pkg.mOriginalPackages != null
10171                        && pkg.mOriginalPackages.contains(oldName)
10172                        && mPackages.containsKey(oldName)) {
10173                    // This package is derived from an original package,
10174                    // and this device has been updating from that original
10175                    // name.  We must continue using the original name, so
10176                    // rename the new package here.
10177                    pkg.setPackageName(oldName);
10178                    pkgName = pkg.packageName;
10179                    replace = true;
10180                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10181                            + oldName + " pkgName=" + pkgName);
10182                } else if (mPackages.containsKey(pkgName)) {
10183                    // This package, under its official name, already exists
10184                    // on the device; we should replace it.
10185                    replace = true;
10186                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10187                }
10188            }
10189            PackageSetting ps = mSettings.mPackages.get(pkgName);
10190            if (ps != null) {
10191                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10192                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10193                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10194                    systemApp = (ps.pkg.applicationInfo.flags &
10195                            ApplicationInfo.FLAG_SYSTEM) != 0;
10196                }
10197                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10198            }
10199        }
10200
10201        if (systemApp && onSd) {
10202            // Disable updates to system apps on sdcard
10203            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10204            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10205            return;
10206        }
10207
10208        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10209            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10210            return;
10211        }
10212
10213        if (replace) {
10214            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10215                    installerPackageName, res, args.abiOverride);
10216        } else {
10217            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10218                    installerPackageName, res, args.abiOverride);
10219        }
10220        synchronized (mPackages) {
10221            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10222            if (ps != null) {
10223                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10224            }
10225        }
10226    }
10227
10228    private static boolean isForwardLocked(PackageParser.Package pkg) {
10229        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10230    }
10231
10232
10233    private boolean isForwardLocked(PackageSetting ps) {
10234        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10235    }
10236
10237    private static boolean isExternal(PackageParser.Package pkg) {
10238        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10239    }
10240
10241    private static boolean isExternal(PackageSetting ps) {
10242        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10243    }
10244
10245    private static boolean isSystemApp(PackageParser.Package pkg) {
10246        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10247    }
10248
10249    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10250        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10251    }
10252
10253    private static boolean isSystemApp(ApplicationInfo info) {
10254        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10255    }
10256
10257    private static boolean isSystemApp(PackageSetting ps) {
10258        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10259    }
10260
10261    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10262        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10263    }
10264
10265    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10266        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10267    }
10268
10269    private int packageFlagsToInstallFlags(PackageSetting ps) {
10270        int installFlags = 0;
10271        if (isExternal(ps)) {
10272            installFlags |= PackageManager.INSTALL_EXTERNAL;
10273        }
10274        if (isForwardLocked(ps)) {
10275            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10276        }
10277        return installFlags;
10278    }
10279
10280    private void deleteTempPackageFiles() {
10281        final FilenameFilter filter = new FilenameFilter() {
10282            public boolean accept(File dir, String name) {
10283                return name.startsWith("vmdl") && name.endsWith(".tmp");
10284            }
10285        };
10286        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10287            file.delete();
10288        }
10289    }
10290
10291    @Override
10292    public void deletePackageAsUser(final String packageName,
10293                                    final IPackageDeleteObserver observer,
10294                                    final int userId, final int flags) {
10295        mContext.enforceCallingOrSelfPermission(
10296                android.Manifest.permission.DELETE_PACKAGES, null);
10297        final int uid = Binder.getCallingUid();
10298        if (UserHandle.getUserId(uid) != userId) {
10299            mContext.enforceCallingPermission(
10300                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10301                    "deletePackage for user " + userId);
10302        }
10303        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10304            try {
10305                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10306            } catch (RemoteException re) {
10307            }
10308            return;
10309        }
10310
10311        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10312        // Queue up an async operation since the package deletion may take a little while.
10313        mHandler.post(new Runnable() {
10314            public void run() {
10315                mHandler.removeCallbacks(this);
10316                final int returnCode = deletePackageX(packageName, userId, flags);
10317                if (observer != null) {
10318                    try {
10319                        observer.packageDeleted(packageName, returnCode);
10320                    } catch (RemoteException e) {
10321                        Log.i(TAG, "Observer no longer exists.");
10322                    } //end catch
10323                } //end if
10324            } //end run
10325        });
10326    }
10327
10328    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10329        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10330                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10331        try {
10332            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10333                    || dpm.isDeviceOwner(packageName))) {
10334                return true;
10335            }
10336        } catch (RemoteException e) {
10337        }
10338        return false;
10339    }
10340
10341    /**
10342     *  This method is an internal method that could be get invoked either
10343     *  to delete an installed package or to clean up a failed installation.
10344     *  After deleting an installed package, a broadcast is sent to notify any
10345     *  listeners that the package has been installed. For cleaning up a failed
10346     *  installation, the broadcast is not necessary since the package's
10347     *  installation wouldn't have sent the initial broadcast either
10348     *  The key steps in deleting a package are
10349     *  deleting the package information in internal structures like mPackages,
10350     *  deleting the packages base directories through installd
10351     *  updating mSettings to reflect current status
10352     *  persisting settings for later use
10353     *  sending a broadcast if necessary
10354     */
10355    private int deletePackageX(String packageName, int userId, int flags) {
10356        final PackageRemovedInfo info = new PackageRemovedInfo();
10357        final boolean res;
10358
10359        if (isPackageDeviceAdmin(packageName, userId)) {
10360            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10361            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10362        }
10363
10364        boolean removedForAllUsers = false;
10365        boolean systemUpdate = false;
10366
10367        // for the uninstall-updates case and restricted profiles, remember the per-
10368        // userhandle installed state
10369        int[] allUsers;
10370        boolean[] perUserInstalled;
10371        synchronized (mPackages) {
10372            PackageSetting ps = mSettings.mPackages.get(packageName);
10373            allUsers = sUserManager.getUserIds();
10374            perUserInstalled = new boolean[allUsers.length];
10375            for (int i = 0; i < allUsers.length; i++) {
10376                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10377            }
10378        }
10379
10380        synchronized (mInstallLock) {
10381            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10382            res = deletePackageLI(packageName,
10383                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10384                            ? UserHandle.ALL : new UserHandle(userId),
10385                    true, allUsers, perUserInstalled,
10386                    flags | REMOVE_CHATTY, info, true);
10387            systemUpdate = info.isRemovedPackageSystemUpdate;
10388            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10389                removedForAllUsers = true;
10390            }
10391            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10392                    + " removedForAllUsers=" + removedForAllUsers);
10393        }
10394
10395        if (res) {
10396            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10397
10398            // If the removed package was a system update, the old system package
10399            // was re-enabled; we need to broadcast this information
10400            if (systemUpdate) {
10401                Bundle extras = new Bundle(1);
10402                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10403                        ? info.removedAppId : info.uid);
10404                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10405
10406                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10407                        extras, null, null, null);
10408                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10409                        extras, null, null, null);
10410                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10411                        null, packageName, null, null);
10412            }
10413        }
10414        // Force a gc here.
10415        Runtime.getRuntime().gc();
10416        // Delete the resources here after sending the broadcast to let
10417        // other processes clean up before deleting resources.
10418        if (info.args != null) {
10419            synchronized (mInstallLock) {
10420                info.args.doPostDeleteLI(true);
10421            }
10422        }
10423
10424        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10425    }
10426
10427    static class PackageRemovedInfo {
10428        String removedPackage;
10429        int uid = -1;
10430        int removedAppId = -1;
10431        int[] removedUsers = null;
10432        boolean isRemovedPackageSystemUpdate = false;
10433        // Clean up resources deleted packages.
10434        InstallArgs args = null;
10435
10436        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10437            Bundle extras = new Bundle(1);
10438            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10439            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10440            if (replacing) {
10441                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10442            }
10443            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10444            if (removedPackage != null) {
10445                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10446                        extras, null, null, removedUsers);
10447                if (fullRemove && !replacing) {
10448                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10449                            extras, null, null, removedUsers);
10450                }
10451            }
10452            if (removedAppId >= 0) {
10453                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10454                        removedUsers);
10455            }
10456        }
10457    }
10458
10459    /*
10460     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10461     * flag is not set, the data directory is removed as well.
10462     * make sure this flag is set for partially installed apps. If not its meaningless to
10463     * delete a partially installed application.
10464     */
10465    private void removePackageDataLI(PackageSetting ps,
10466            int[] allUserHandles, boolean[] perUserInstalled,
10467            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10468        String packageName = ps.name;
10469        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10470        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10471        // Retrieve object to delete permissions for shared user later on
10472        final PackageSetting deletedPs;
10473        // reader
10474        synchronized (mPackages) {
10475            deletedPs = mSettings.mPackages.get(packageName);
10476            if (outInfo != null) {
10477                outInfo.removedPackage = packageName;
10478                outInfo.removedUsers = deletedPs != null
10479                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10480                        : null;
10481            }
10482        }
10483        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10484            removeDataDirsLI(packageName);
10485            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10486        }
10487        // writer
10488        synchronized (mPackages) {
10489            if (deletedPs != null) {
10490                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10491                    if (outInfo != null) {
10492                        mSettings.mKeySetManagerService.removeAppKeySetData(packageName);
10493                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10494                    }
10495                    if (deletedPs != null) {
10496                        updatePermissionsLPw(deletedPs.name, null, 0);
10497                        if (deletedPs.sharedUser != null) {
10498                            // remove permissions associated with package
10499                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10500                        }
10501                    }
10502                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10503                }
10504                // make sure to preserve per-user disabled state if this removal was just
10505                // a downgrade of a system app to the factory package
10506                if (allUserHandles != null && perUserInstalled != null) {
10507                    if (DEBUG_REMOVE) {
10508                        Slog.d(TAG, "Propagating install state across downgrade");
10509                    }
10510                    for (int i = 0; i < allUserHandles.length; i++) {
10511                        if (DEBUG_REMOVE) {
10512                            Slog.d(TAG, "    user " + allUserHandles[i]
10513                                    + " => " + perUserInstalled[i]);
10514                        }
10515                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10516                    }
10517                }
10518            }
10519            // can downgrade to reader
10520            if (writeSettings) {
10521                // Save settings now
10522                mSettings.writeLPr();
10523            }
10524        }
10525        if (outInfo != null) {
10526            // A user ID was deleted here. Go through all users and remove it
10527            // from KeyStore.
10528            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10529        }
10530    }
10531
10532    static boolean locationIsPrivileged(File path) {
10533        try {
10534            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10535                    .getCanonicalPath();
10536            return path.getCanonicalPath().startsWith(privilegedAppDir);
10537        } catch (IOException e) {
10538            Slog.e(TAG, "Unable to access code path " + path);
10539        }
10540        return false;
10541    }
10542
10543    /*
10544     * Tries to delete system package.
10545     */
10546    private boolean deleteSystemPackageLI(PackageSetting newPs,
10547            int[] allUserHandles, boolean[] perUserInstalled,
10548            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10549        final boolean applyUserRestrictions
10550                = (allUserHandles != null) && (perUserInstalled != null);
10551        PackageSetting disabledPs = null;
10552        // Confirm if the system package has been updated
10553        // An updated system app can be deleted. This will also have to restore
10554        // the system pkg from system partition
10555        // reader
10556        synchronized (mPackages) {
10557            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10558        }
10559        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10560                + " disabledPs=" + disabledPs);
10561        if (disabledPs == null) {
10562            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10563            return false;
10564        } else if (DEBUG_REMOVE) {
10565            Slog.d(TAG, "Deleting system pkg from data partition");
10566        }
10567        if (DEBUG_REMOVE) {
10568            if (applyUserRestrictions) {
10569                Slog.d(TAG, "Remembering install states:");
10570                for (int i = 0; i < allUserHandles.length; i++) {
10571                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10572                }
10573            }
10574        }
10575        // Delete the updated package
10576        outInfo.isRemovedPackageSystemUpdate = true;
10577        if (disabledPs.versionCode < newPs.versionCode) {
10578            // Delete data for downgrades
10579            flags &= ~PackageManager.DELETE_KEEP_DATA;
10580        } else {
10581            // Preserve data by setting flag
10582            flags |= PackageManager.DELETE_KEEP_DATA;
10583        }
10584        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10585                allUserHandles, perUserInstalled, outInfo, writeSettings);
10586        if (!ret) {
10587            return false;
10588        }
10589        // writer
10590        synchronized (mPackages) {
10591            // Reinstate the old system package
10592            mSettings.enableSystemPackageLPw(newPs.name);
10593            // Remove any native libraries from the upgraded package.
10594            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10595        }
10596        // Install the system package
10597        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10598        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10599        if (locationIsPrivileged(disabledPs.codePath)) {
10600            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10601        }
10602        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10603                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10604
10605        if (newPkg == null) {
10606            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10607                    + " with error:" + mLastScanError);
10608            return false;
10609        }
10610        // writer
10611        synchronized (mPackages) {
10612            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10613            setInternalAppNativeLibraryPath(newPkg, ps);
10614            updatePermissionsLPw(newPkg.packageName, newPkg,
10615                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10616            if (applyUserRestrictions) {
10617                if (DEBUG_REMOVE) {
10618                    Slog.d(TAG, "Propagating install state across reinstall");
10619                }
10620                for (int i = 0; i < allUserHandles.length; i++) {
10621                    if (DEBUG_REMOVE) {
10622                        Slog.d(TAG, "    user " + allUserHandles[i]
10623                                + " => " + perUserInstalled[i]);
10624                    }
10625                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10626                }
10627                // Regardless of writeSettings we need to ensure that this restriction
10628                // state propagation is persisted
10629                mSettings.writeAllUsersPackageRestrictionsLPr();
10630            }
10631            // can downgrade to reader here
10632            if (writeSettings) {
10633                mSettings.writeLPr();
10634            }
10635        }
10636        return true;
10637    }
10638
10639    private boolean deleteInstalledPackageLI(PackageSetting ps,
10640            boolean deleteCodeAndResources, int flags,
10641            int[] allUserHandles, boolean[] perUserInstalled,
10642            PackageRemovedInfo outInfo, boolean writeSettings) {
10643        if (outInfo != null) {
10644            outInfo.uid = ps.appId;
10645        }
10646
10647        // Delete package data from internal structures and also remove data if flag is set
10648        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10649
10650        // Delete application code and resources
10651        if (deleteCodeAndResources && (outInfo != null)) {
10652            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10653                    ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
10654                    getAppInstructionSetFromSettings(ps));
10655        }
10656        return true;
10657    }
10658
10659    @Override
10660    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10661            int userId) {
10662        mContext.enforceCallingOrSelfPermission(
10663                android.Manifest.permission.DELETE_PACKAGES, null);
10664        synchronized (mPackages) {
10665            PackageSetting ps = mSettings.mPackages.get(packageName);
10666            if (ps == null) {
10667                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10668                return false;
10669            }
10670            if (!ps.getInstalled(userId)) {
10671                // Can't block uninstall for an app that is not installed or enabled.
10672                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10673                return false;
10674            }
10675            ps.setBlockUninstall(blockUninstall, userId);
10676            mSettings.writePackageRestrictionsLPr(userId);
10677        }
10678        return true;
10679    }
10680
10681    @Override
10682    public boolean getBlockUninstallForUser(String packageName, int userId) {
10683        synchronized (mPackages) {
10684            PackageSetting ps = mSettings.mPackages.get(packageName);
10685            if (ps == null) {
10686                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10687                return false;
10688            }
10689            return ps.getBlockUninstall(userId);
10690        }
10691    }
10692
10693    /*
10694     * This method handles package deletion in general
10695     */
10696    private boolean deletePackageLI(String packageName, UserHandle user,
10697            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10698            int flags, PackageRemovedInfo outInfo,
10699            boolean writeSettings) {
10700        if (packageName == null) {
10701            Slog.w(TAG, "Attempt to delete null packageName.");
10702            return false;
10703        }
10704        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10705        PackageSetting ps;
10706        boolean dataOnly = false;
10707        int removeUser = -1;
10708        int appId = -1;
10709        synchronized (mPackages) {
10710            ps = mSettings.mPackages.get(packageName);
10711            if (ps == null) {
10712                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10713                return false;
10714            }
10715            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10716                    && user.getIdentifier() != UserHandle.USER_ALL) {
10717                // The caller is asking that the package only be deleted for a single
10718                // user.  To do this, we just mark its uninstalled state and delete
10719                // its data.  If this is a system app, we only allow this to happen if
10720                // they have set the special DELETE_SYSTEM_APP which requests different
10721                // semantics than normal for uninstalling system apps.
10722                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10723                ps.setUserState(user.getIdentifier(),
10724                        COMPONENT_ENABLED_STATE_DEFAULT,
10725                        false, //installed
10726                        true,  //stopped
10727                        true,  //notLaunched
10728                        false, //blocked
10729                        null, null, null,
10730                        false // blockUninstall
10731                        );
10732                if (!isSystemApp(ps)) {
10733                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10734                        // Other user still have this package installed, so all
10735                        // we need to do is clear this user's data and save that
10736                        // it is uninstalled.
10737                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10738                        removeUser = user.getIdentifier();
10739                        appId = ps.appId;
10740                        mSettings.writePackageRestrictionsLPr(removeUser);
10741                    } else {
10742                        // We need to set it back to 'installed' so the uninstall
10743                        // broadcasts will be sent correctly.
10744                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10745                        ps.setInstalled(true, user.getIdentifier());
10746                    }
10747                } else {
10748                    // This is a system app, so we assume that the
10749                    // other users still have this package installed, so all
10750                    // we need to do is clear this user's data and save that
10751                    // it is uninstalled.
10752                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10753                    removeUser = user.getIdentifier();
10754                    appId = ps.appId;
10755                    mSettings.writePackageRestrictionsLPr(removeUser);
10756                }
10757            }
10758        }
10759
10760        if (removeUser >= 0) {
10761            // From above, we determined that we are deleting this only
10762            // for a single user.  Continue the work here.
10763            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10764            if (outInfo != null) {
10765                outInfo.removedPackage = packageName;
10766                outInfo.removedAppId = appId;
10767                outInfo.removedUsers = new int[] {removeUser};
10768            }
10769            mInstaller.clearUserData(packageName, removeUser);
10770            removeKeystoreDataIfNeeded(removeUser, appId);
10771            schedulePackageCleaning(packageName, removeUser, false);
10772            return true;
10773        }
10774
10775        if (dataOnly) {
10776            // Delete application data first
10777            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10778            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10779            return true;
10780        }
10781
10782        boolean ret = false;
10783        if (isSystemApp(ps)) {
10784            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10785            // When an updated system application is deleted we delete the existing resources as well and
10786            // fall back to existing code in system partition
10787            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10788                    flags, outInfo, writeSettings);
10789        } else {
10790            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10791            // Kill application pre-emptively especially for apps on sd.
10792            killApplication(packageName, ps.appId, "uninstall pkg");
10793            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10794                    allUserHandles, perUserInstalled,
10795                    outInfo, writeSettings);
10796        }
10797
10798        return ret;
10799    }
10800
10801    private final class ClearStorageConnection implements ServiceConnection {
10802        IMediaContainerService mContainerService;
10803
10804        @Override
10805        public void onServiceConnected(ComponentName name, IBinder service) {
10806            synchronized (this) {
10807                mContainerService = IMediaContainerService.Stub.asInterface(service);
10808                notifyAll();
10809            }
10810        }
10811
10812        @Override
10813        public void onServiceDisconnected(ComponentName name) {
10814        }
10815    }
10816
10817    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10818        final boolean mounted;
10819        if (Environment.isExternalStorageEmulated()) {
10820            mounted = true;
10821        } else {
10822            final String status = Environment.getExternalStorageState();
10823
10824            mounted = status.equals(Environment.MEDIA_MOUNTED)
10825                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10826        }
10827
10828        if (!mounted) {
10829            return;
10830        }
10831
10832        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10833        int[] users;
10834        if (userId == UserHandle.USER_ALL) {
10835            users = sUserManager.getUserIds();
10836        } else {
10837            users = new int[] { userId };
10838        }
10839        final ClearStorageConnection conn = new ClearStorageConnection();
10840        if (mContext.bindServiceAsUser(
10841                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10842            try {
10843                for (int curUser : users) {
10844                    long timeout = SystemClock.uptimeMillis() + 5000;
10845                    synchronized (conn) {
10846                        long now = SystemClock.uptimeMillis();
10847                        while (conn.mContainerService == null && now < timeout) {
10848                            try {
10849                                conn.wait(timeout - now);
10850                            } catch (InterruptedException e) {
10851                            }
10852                        }
10853                    }
10854                    if (conn.mContainerService == null) {
10855                        return;
10856                    }
10857
10858                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10859                    clearDirectory(conn.mContainerService,
10860                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10861                    if (allData) {
10862                        clearDirectory(conn.mContainerService,
10863                                userEnv.buildExternalStorageAppDataDirs(packageName));
10864                        clearDirectory(conn.mContainerService,
10865                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10866                    }
10867                }
10868            } finally {
10869                mContext.unbindService(conn);
10870            }
10871        }
10872    }
10873
10874    @Override
10875    public void clearApplicationUserData(final String packageName,
10876            final IPackageDataObserver observer, final int userId) {
10877        mContext.enforceCallingOrSelfPermission(
10878                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10879        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10880        // Queue up an async operation since the package deletion may take a little while.
10881        mHandler.post(new Runnable() {
10882            public void run() {
10883                mHandler.removeCallbacks(this);
10884                final boolean succeeded;
10885                synchronized (mInstallLock) {
10886                    succeeded = clearApplicationUserDataLI(packageName, userId);
10887                }
10888                clearExternalStorageDataSync(packageName, userId, true);
10889                if (succeeded) {
10890                    // invoke DeviceStorageMonitor's update method to clear any notifications
10891                    DeviceStorageMonitorInternal
10892                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10893                    if (dsm != null) {
10894                        dsm.checkMemory();
10895                    }
10896                }
10897                if(observer != null) {
10898                    try {
10899                        observer.onRemoveCompleted(packageName, succeeded);
10900                    } catch (RemoteException e) {
10901                        Log.i(TAG, "Observer no longer exists.");
10902                    }
10903                } //end if observer
10904            } //end run
10905        });
10906    }
10907
10908    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10909        if (packageName == null) {
10910            Slog.w(TAG, "Attempt to delete null packageName.");
10911            return false;
10912        }
10913        PackageParser.Package p;
10914        boolean dataOnly = false;
10915        final int appId;
10916        synchronized (mPackages) {
10917            p = mPackages.get(packageName);
10918            if (p == null) {
10919                dataOnly = true;
10920                PackageSetting ps = mSettings.mPackages.get(packageName);
10921                if ((ps == null) || (ps.pkg == null)) {
10922                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10923                    return false;
10924                }
10925                p = ps.pkg;
10926            }
10927            if (!dataOnly) {
10928                // need to check this only for fully installed applications
10929                if (p == null) {
10930                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10931                    return false;
10932                }
10933                final ApplicationInfo applicationInfo = p.applicationInfo;
10934                if (applicationInfo == null) {
10935                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10936                    return false;
10937                }
10938            }
10939            if (p != null && p.applicationInfo != null) {
10940                appId = p.applicationInfo.uid;
10941            } else {
10942                appId = -1;
10943            }
10944        }
10945        int retCode = mInstaller.clearUserData(packageName, userId);
10946        if (retCode < 0) {
10947            Slog.w(TAG, "Couldn't remove cache files for package: "
10948                    + packageName);
10949            return false;
10950        }
10951        removeKeystoreDataIfNeeded(userId, appId);
10952        return true;
10953    }
10954
10955    /**
10956     * Remove entries from the keystore daemon. Will only remove it if the
10957     * {@code appId} is valid.
10958     */
10959    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10960        if (appId < 0) {
10961            return;
10962        }
10963
10964        final KeyStore keyStore = KeyStore.getInstance();
10965        if (keyStore != null) {
10966            if (userId == UserHandle.USER_ALL) {
10967                for (final int individual : sUserManager.getUserIds()) {
10968                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10969                }
10970            } else {
10971                keyStore.clearUid(UserHandle.getUid(userId, appId));
10972            }
10973        } else {
10974            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10975        }
10976    }
10977
10978    @Override
10979    public void deleteApplicationCacheFiles(final String packageName,
10980            final IPackageDataObserver observer) {
10981        mContext.enforceCallingOrSelfPermission(
10982                android.Manifest.permission.DELETE_CACHE_FILES, null);
10983        // Queue up an async operation since the package deletion may take a little while.
10984        final int userId = UserHandle.getCallingUserId();
10985        mHandler.post(new Runnable() {
10986            public void run() {
10987                mHandler.removeCallbacks(this);
10988                final boolean succeded;
10989                synchronized (mInstallLock) {
10990                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10991                }
10992                clearExternalStorageDataSync(packageName, userId, false);
10993                if(observer != null) {
10994                    try {
10995                        observer.onRemoveCompleted(packageName, succeded);
10996                    } catch (RemoteException e) {
10997                        Log.i(TAG, "Observer no longer exists.");
10998                    }
10999                } //end if observer
11000            } //end run
11001        });
11002    }
11003
11004    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11005        if (packageName == null) {
11006            Slog.w(TAG, "Attempt to delete null packageName.");
11007            return false;
11008        }
11009        PackageParser.Package p;
11010        synchronized (mPackages) {
11011            p = mPackages.get(packageName);
11012        }
11013        if (p == null) {
11014            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11015            return false;
11016        }
11017        final ApplicationInfo applicationInfo = p.applicationInfo;
11018        if (applicationInfo == null) {
11019            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11020            return false;
11021        }
11022        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11023        if (retCode < 0) {
11024            Slog.w(TAG, "Couldn't remove cache files for package: "
11025                       + packageName + " u" + userId);
11026            return false;
11027        }
11028        return true;
11029    }
11030
11031    @Override
11032    public void getPackageSizeInfo(final String packageName, int userHandle,
11033            final IPackageStatsObserver observer) {
11034        mContext.enforceCallingOrSelfPermission(
11035                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11036        if (packageName == null) {
11037            throw new IllegalArgumentException("Attempt to get size of null packageName");
11038        }
11039
11040        PackageStats stats = new PackageStats(packageName, userHandle);
11041
11042        /*
11043         * Queue up an async operation since the package measurement may take a
11044         * little while.
11045         */
11046        Message msg = mHandler.obtainMessage(INIT_COPY);
11047        msg.obj = new MeasureParams(stats, observer);
11048        mHandler.sendMessage(msg);
11049    }
11050
11051    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11052            PackageStats pStats) {
11053        if (packageName == null) {
11054            Slog.w(TAG, "Attempt to get size of null packageName.");
11055            return false;
11056        }
11057        PackageParser.Package p;
11058        boolean dataOnly = false;
11059        String libDirPath = null;
11060        String asecPath = null;
11061        PackageSetting ps = null;
11062        synchronized (mPackages) {
11063            p = mPackages.get(packageName);
11064            ps = mSettings.mPackages.get(packageName);
11065            if(p == null) {
11066                dataOnly = true;
11067                if((ps == null) || (ps.pkg == null)) {
11068                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11069                    return false;
11070                }
11071                p = ps.pkg;
11072            }
11073            if (ps != null) {
11074                libDirPath = ps.nativeLibraryPathString;
11075            }
11076            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11077                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11078                if (secureContainerId != null) {
11079                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11080                }
11081            }
11082        }
11083        String publicSrcDir = null;
11084        if(!dataOnly) {
11085            final ApplicationInfo applicationInfo = p.applicationInfo;
11086            if (applicationInfo == null) {
11087                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11088                return false;
11089            }
11090            if (isForwardLocked(p)) {
11091                publicSrcDir = applicationInfo.getBaseResourcePath();
11092            }
11093        }
11094        // TODO: extend to measure size of split APKs
11095        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath,
11096                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11097                pStats);
11098        if (res < 0) {
11099            return false;
11100        }
11101
11102        // Fix-up for forward-locked applications in ASEC containers.
11103        if (!isExternal(p)) {
11104            pStats.codeSize += pStats.externalCodeSize;
11105            pStats.externalCodeSize = 0L;
11106        }
11107
11108        return true;
11109    }
11110
11111
11112    @Override
11113    public void addPackageToPreferred(String packageName) {
11114        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11115    }
11116
11117    @Override
11118    public void removePackageFromPreferred(String packageName) {
11119        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11120    }
11121
11122    @Override
11123    public List<PackageInfo> getPreferredPackages(int flags) {
11124        return new ArrayList<PackageInfo>();
11125    }
11126
11127    private int getUidTargetSdkVersionLockedLPr(int uid) {
11128        Object obj = mSettings.getUserIdLPr(uid);
11129        if (obj instanceof SharedUserSetting) {
11130            final SharedUserSetting sus = (SharedUserSetting) obj;
11131            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11132            final Iterator<PackageSetting> it = sus.packages.iterator();
11133            while (it.hasNext()) {
11134                final PackageSetting ps = it.next();
11135                if (ps.pkg != null) {
11136                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11137                    if (v < vers) vers = v;
11138                }
11139            }
11140            return vers;
11141        } else if (obj instanceof PackageSetting) {
11142            final PackageSetting ps = (PackageSetting) obj;
11143            if (ps.pkg != null) {
11144                return ps.pkg.applicationInfo.targetSdkVersion;
11145            }
11146        }
11147        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11148    }
11149
11150    @Override
11151    public void addPreferredActivity(IntentFilter filter, int match,
11152            ComponentName[] set, ComponentName activity, int userId) {
11153        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11154    }
11155
11156    private void addPreferredActivityInternal(IntentFilter filter, int match,
11157            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11158        // writer
11159        int callingUid = Binder.getCallingUid();
11160        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11161        if (filter.countActions() == 0) {
11162            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11163            return;
11164        }
11165        synchronized (mPackages) {
11166            if (mContext.checkCallingOrSelfPermission(
11167                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11168                    != PackageManager.PERMISSION_GRANTED) {
11169                if (getUidTargetSdkVersionLockedLPr(callingUid)
11170                        < Build.VERSION_CODES.FROYO) {
11171                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11172                            + callingUid);
11173                    return;
11174                }
11175                mContext.enforceCallingOrSelfPermission(
11176                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11177            }
11178
11179            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11180            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11181            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11182                    new PreferredActivity(filter, match, set, activity, always));
11183            mSettings.writePackageRestrictionsLPr(userId);
11184        }
11185    }
11186
11187    @Override
11188    public void replacePreferredActivity(IntentFilter filter, int match,
11189            ComponentName[] set, ComponentName activity) {
11190        if (filter.countActions() != 1) {
11191            throw new IllegalArgumentException(
11192                    "replacePreferredActivity expects filter to have only 1 action.");
11193        }
11194        if (filter.countDataAuthorities() != 0
11195                || filter.countDataPaths() != 0
11196                || filter.countDataSchemes() > 1
11197                || filter.countDataTypes() != 0) {
11198            throw new IllegalArgumentException(
11199                    "replacePreferredActivity expects filter to have no data authorities, " +
11200                    "paths, or types; and at most one scheme.");
11201        }
11202        synchronized (mPackages) {
11203            if (mContext.checkCallingOrSelfPermission(
11204                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11205                    != PackageManager.PERMISSION_GRANTED) {
11206                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11207                        < Build.VERSION_CODES.FROYO) {
11208                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11209                            + Binder.getCallingUid());
11210                    return;
11211                }
11212                mContext.enforceCallingOrSelfPermission(
11213                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11214            }
11215
11216            final int callingUserId = UserHandle.getCallingUserId();
11217            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11218            if (pir != null) {
11219                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11220                if (filter.countDataSchemes() == 1) {
11221                    Uri.Builder builder = new Uri.Builder();
11222                    builder.scheme(filter.getDataScheme(0));
11223                    intent.setData(builder.build());
11224                }
11225                List<PreferredActivity> matches = pir.queryIntent(
11226                        intent, null, true, callingUserId);
11227                if (DEBUG_PREFERRED) {
11228                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11229                }
11230                for (int i = 0; i < matches.size(); i++) {
11231                    PreferredActivity pa = matches.get(i);
11232                    if (DEBUG_PREFERRED) {
11233                        Slog.i(TAG, "Removing preferred activity "
11234                                + pa.mPref.mComponent + ":");
11235                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11236                    }
11237                    pir.removeFilter(pa);
11238                }
11239            }
11240            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11241        }
11242    }
11243
11244    @Override
11245    public void clearPackagePreferredActivities(String packageName) {
11246        final int uid = Binder.getCallingUid();
11247        // writer
11248        synchronized (mPackages) {
11249            PackageParser.Package pkg = mPackages.get(packageName);
11250            if (pkg == null || pkg.applicationInfo.uid != uid) {
11251                if (mContext.checkCallingOrSelfPermission(
11252                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11253                        != PackageManager.PERMISSION_GRANTED) {
11254                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11255                            < Build.VERSION_CODES.FROYO) {
11256                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11257                                + Binder.getCallingUid());
11258                        return;
11259                    }
11260                    mContext.enforceCallingOrSelfPermission(
11261                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11262                }
11263            }
11264
11265            int user = UserHandle.getCallingUserId();
11266            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11267                mSettings.writePackageRestrictionsLPr(user);
11268                scheduleWriteSettingsLocked();
11269            }
11270        }
11271    }
11272
11273    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11274    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11275        ArrayList<PreferredActivity> removed = null;
11276        boolean changed = false;
11277        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11278            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11279            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11280            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11281                continue;
11282            }
11283            Iterator<PreferredActivity> it = pir.filterIterator();
11284            while (it.hasNext()) {
11285                PreferredActivity pa = it.next();
11286                // Mark entry for removal only if it matches the package name
11287                // and the entry is of type "always".
11288                if (packageName == null ||
11289                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11290                                && pa.mPref.mAlways)) {
11291                    if (removed == null) {
11292                        removed = new ArrayList<PreferredActivity>();
11293                    }
11294                    removed.add(pa);
11295                }
11296            }
11297            if (removed != null) {
11298                for (int j=0; j<removed.size(); j++) {
11299                    PreferredActivity pa = removed.get(j);
11300                    pir.removeFilter(pa);
11301                }
11302                changed = true;
11303            }
11304        }
11305        return changed;
11306    }
11307
11308    @Override
11309    public void resetPreferredActivities(int userId) {
11310        mContext.enforceCallingOrSelfPermission(
11311                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11312        // writer
11313        synchronized (mPackages) {
11314            int user = UserHandle.getCallingUserId();
11315            clearPackagePreferredActivitiesLPw(null, user);
11316            mSettings.readDefaultPreferredAppsLPw(this, user);
11317            mSettings.writePackageRestrictionsLPr(user);
11318            scheduleWriteSettingsLocked();
11319        }
11320    }
11321
11322    @Override
11323    public int getPreferredActivities(List<IntentFilter> outFilters,
11324            List<ComponentName> outActivities, String packageName) {
11325
11326        int num = 0;
11327        final int userId = UserHandle.getCallingUserId();
11328        // reader
11329        synchronized (mPackages) {
11330            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11331            if (pir != null) {
11332                final Iterator<PreferredActivity> it = pir.filterIterator();
11333                while (it.hasNext()) {
11334                    final PreferredActivity pa = it.next();
11335                    if (packageName == null
11336                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11337                                    && pa.mPref.mAlways)) {
11338                        if (outFilters != null) {
11339                            outFilters.add(new IntentFilter(pa));
11340                        }
11341                        if (outActivities != null) {
11342                            outActivities.add(pa.mPref.mComponent);
11343                        }
11344                    }
11345                }
11346            }
11347        }
11348
11349        return num;
11350    }
11351
11352    @Override
11353    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11354            int userId) {
11355        int callingUid = Binder.getCallingUid();
11356        if (callingUid != Process.SYSTEM_UID) {
11357            throw new SecurityException(
11358                    "addPersistentPreferredActivity can only be run by the system");
11359        }
11360        if (filter.countActions() == 0) {
11361            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11362            return;
11363        }
11364        synchronized (mPackages) {
11365            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11366                    " :");
11367            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11368            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11369                    new PersistentPreferredActivity(filter, activity));
11370            mSettings.writePackageRestrictionsLPr(userId);
11371        }
11372    }
11373
11374    @Override
11375    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11376        int callingUid = Binder.getCallingUid();
11377        if (callingUid != Process.SYSTEM_UID) {
11378            throw new SecurityException(
11379                    "clearPackagePersistentPreferredActivities can only be run by the system");
11380        }
11381        ArrayList<PersistentPreferredActivity> removed = null;
11382        boolean changed = false;
11383        synchronized (mPackages) {
11384            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11385                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11386                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11387                        .valueAt(i);
11388                if (userId != thisUserId) {
11389                    continue;
11390                }
11391                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11392                while (it.hasNext()) {
11393                    PersistentPreferredActivity ppa = it.next();
11394                    // Mark entry for removal only if it matches the package name.
11395                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11396                        if (removed == null) {
11397                            removed = new ArrayList<PersistentPreferredActivity>();
11398                        }
11399                        removed.add(ppa);
11400                    }
11401                }
11402                if (removed != null) {
11403                    for (int j=0; j<removed.size(); j++) {
11404                        PersistentPreferredActivity ppa = removed.get(j);
11405                        ppir.removeFilter(ppa);
11406                    }
11407                    changed = true;
11408                }
11409            }
11410
11411            if (changed) {
11412                mSettings.writePackageRestrictionsLPr(userId);
11413            }
11414        }
11415    }
11416
11417    @Override
11418    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11419            int targetUserId, int flags) {
11420        mContext.enforceCallingOrSelfPermission(
11421                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11422        if (intentFilter.countActions() == 0) {
11423            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11424            return;
11425        }
11426        synchronized (mPackages) {
11427            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11428                    targetUserId, flags);
11429            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11430            mSettings.writePackageRestrictionsLPr(sourceUserId);
11431        }
11432    }
11433
11434    public void addCrossProfileIntentsForPackage(String packageName,
11435            int sourceUserId, int targetUserId) {
11436        mContext.enforceCallingOrSelfPermission(
11437                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11438        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11439        mSettings.writePackageRestrictionsLPr(sourceUserId);
11440    }
11441
11442    public void removeCrossProfileIntentsForPackage(String packageName,
11443            int sourceUserId, int targetUserId) {
11444        mContext.enforceCallingOrSelfPermission(
11445                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11446        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11447        mSettings.writePackageRestrictionsLPr(sourceUserId);
11448    }
11449
11450    @Override
11451    public void clearCrossProfileIntentFilters(int sourceUserId) {
11452        mContext.enforceCallingOrSelfPermission(
11453                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11454        synchronized (mPackages) {
11455            CrossProfileIntentResolver resolver =
11456                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11457            HashSet<CrossProfileIntentFilter> set =
11458                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11459            for (CrossProfileIntentFilter filter : set) {
11460                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11461                    resolver.removeFilter(filter);
11462                }
11463            }
11464            mSettings.writePackageRestrictionsLPr(sourceUserId);
11465        }
11466    }
11467
11468    @Override
11469    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11470        Intent intent = new Intent(Intent.ACTION_MAIN);
11471        intent.addCategory(Intent.CATEGORY_HOME);
11472
11473        final int callingUserId = UserHandle.getCallingUserId();
11474        List<ResolveInfo> list = queryIntentActivities(intent, null,
11475                PackageManager.GET_META_DATA, callingUserId);
11476        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11477                true, false, false, callingUserId);
11478
11479        allHomeCandidates.clear();
11480        if (list != null) {
11481            for (ResolveInfo ri : list) {
11482                allHomeCandidates.add(ri);
11483            }
11484        }
11485        return (preferred == null || preferred.activityInfo == null)
11486                ? null
11487                : new ComponentName(preferred.activityInfo.packageName,
11488                        preferred.activityInfo.name);
11489    }
11490
11491    @Override
11492    public void setApplicationEnabledSetting(String appPackageName,
11493            int newState, int flags, int userId, String callingPackage) {
11494        if (!sUserManager.exists(userId)) return;
11495        if (callingPackage == null) {
11496            callingPackage = Integer.toString(Binder.getCallingUid());
11497        }
11498        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11499    }
11500
11501    @Override
11502    public void setComponentEnabledSetting(ComponentName componentName,
11503            int newState, int flags, int userId) {
11504        if (!sUserManager.exists(userId)) return;
11505        setEnabledSetting(componentName.getPackageName(),
11506                componentName.getClassName(), newState, flags, userId, null);
11507    }
11508
11509    private void setEnabledSetting(final String packageName, String className, int newState,
11510            final int flags, int userId, String callingPackage) {
11511        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11512              || newState == COMPONENT_ENABLED_STATE_ENABLED
11513              || newState == COMPONENT_ENABLED_STATE_DISABLED
11514              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11515              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11516            throw new IllegalArgumentException("Invalid new component state: "
11517                    + newState);
11518        }
11519        PackageSetting pkgSetting;
11520        final int uid = Binder.getCallingUid();
11521        final int permission = mContext.checkCallingOrSelfPermission(
11522                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11523        enforceCrossUserPermission(uid, userId, false, "set enabled");
11524        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11525        boolean sendNow = false;
11526        boolean isApp = (className == null);
11527        String componentName = isApp ? packageName : className;
11528        int packageUid = -1;
11529        ArrayList<String> components;
11530
11531        // writer
11532        synchronized (mPackages) {
11533            pkgSetting = mSettings.mPackages.get(packageName);
11534            if (pkgSetting == null) {
11535                if (className == null) {
11536                    throw new IllegalArgumentException(
11537                            "Unknown package: " + packageName);
11538                }
11539                throw new IllegalArgumentException(
11540                        "Unknown component: " + packageName
11541                        + "/" + className);
11542            }
11543            // Allow root and verify that userId is not being specified by a different user
11544            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11545                throw new SecurityException(
11546                        "Permission Denial: attempt to change component state from pid="
11547                        + Binder.getCallingPid()
11548                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11549            }
11550            if (className == null) {
11551                // We're dealing with an application/package level state change
11552                if (pkgSetting.getEnabled(userId) == newState) {
11553                    // Nothing to do
11554                    return;
11555                }
11556                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11557                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11558                    // Don't care about who enables an app.
11559                    callingPackage = null;
11560                }
11561                pkgSetting.setEnabled(newState, userId, callingPackage);
11562                // pkgSetting.pkg.mSetEnabled = newState;
11563            } else {
11564                // We're dealing with a component level state change
11565                // First, verify that this is a valid class name.
11566                PackageParser.Package pkg = pkgSetting.pkg;
11567                if (pkg == null || !pkg.hasComponentClassName(className)) {
11568                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11569                        throw new IllegalArgumentException("Component class " + className
11570                                + " does not exist in " + packageName);
11571                    } else {
11572                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11573                                + className + " does not exist in " + packageName);
11574                    }
11575                }
11576                switch (newState) {
11577                case COMPONENT_ENABLED_STATE_ENABLED:
11578                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11579                        return;
11580                    }
11581                    break;
11582                case COMPONENT_ENABLED_STATE_DISABLED:
11583                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11584                        return;
11585                    }
11586                    break;
11587                case COMPONENT_ENABLED_STATE_DEFAULT:
11588                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11589                        return;
11590                    }
11591                    break;
11592                default:
11593                    Slog.e(TAG, "Invalid new component state: " + newState);
11594                    return;
11595                }
11596            }
11597            mSettings.writePackageRestrictionsLPr(userId);
11598            components = mPendingBroadcasts.get(userId, packageName);
11599            final boolean newPackage = components == null;
11600            if (newPackage) {
11601                components = new ArrayList<String>();
11602            }
11603            if (!components.contains(componentName)) {
11604                components.add(componentName);
11605            }
11606            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11607                sendNow = true;
11608                // Purge entry from pending broadcast list if another one exists already
11609                // since we are sending one right away.
11610                mPendingBroadcasts.remove(userId, packageName);
11611            } else {
11612                if (newPackage) {
11613                    mPendingBroadcasts.put(userId, packageName, components);
11614                }
11615                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11616                    // Schedule a message
11617                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11618                }
11619            }
11620        }
11621
11622        long callingId = Binder.clearCallingIdentity();
11623        try {
11624            if (sendNow) {
11625                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11626                sendPackageChangedBroadcast(packageName,
11627                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11628            }
11629        } finally {
11630            Binder.restoreCallingIdentity(callingId);
11631        }
11632    }
11633
11634    private void sendPackageChangedBroadcast(String packageName,
11635            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11636        if (DEBUG_INSTALL)
11637            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11638                    + componentNames);
11639        Bundle extras = new Bundle(4);
11640        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11641        String nameList[] = new String[componentNames.size()];
11642        componentNames.toArray(nameList);
11643        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11644        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11645        extras.putInt(Intent.EXTRA_UID, packageUid);
11646        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11647                new int[] {UserHandle.getUserId(packageUid)});
11648    }
11649
11650    @Override
11651    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11652        if (!sUserManager.exists(userId)) return;
11653        final int uid = Binder.getCallingUid();
11654        final int permission = mContext.checkCallingOrSelfPermission(
11655                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11656        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11657        enforceCrossUserPermission(uid, userId, true, "stop package");
11658        // writer
11659        synchronized (mPackages) {
11660            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11661                    uid, userId)) {
11662                scheduleWritePackageRestrictionsLocked(userId);
11663            }
11664        }
11665    }
11666
11667    @Override
11668    public String getInstallerPackageName(String packageName) {
11669        // reader
11670        synchronized (mPackages) {
11671            return mSettings.getInstallerPackageNameLPr(packageName);
11672        }
11673    }
11674
11675    @Override
11676    public int getApplicationEnabledSetting(String packageName, int userId) {
11677        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11678        int uid = Binder.getCallingUid();
11679        enforceCrossUserPermission(uid, userId, false, "get enabled");
11680        // reader
11681        synchronized (mPackages) {
11682            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11683        }
11684    }
11685
11686    @Override
11687    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11688        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11689        int uid = Binder.getCallingUid();
11690        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11691        // reader
11692        synchronized (mPackages) {
11693            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11694        }
11695    }
11696
11697    @Override
11698    public void enterSafeMode() {
11699        enforceSystemOrRoot("Only the system can request entering safe mode");
11700
11701        if (!mSystemReady) {
11702            mSafeMode = true;
11703        }
11704    }
11705
11706    @Override
11707    public void systemReady() {
11708        mSystemReady = true;
11709
11710        // Read the compatibilty setting when the system is ready.
11711        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11712                mContext.getContentResolver(),
11713                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11714        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11715        if (DEBUG_SETTINGS) {
11716            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11717        }
11718
11719        synchronized (mPackages) {
11720            // Verify that all of the preferred activity components actually
11721            // exist.  It is possible for applications to be updated and at
11722            // that point remove a previously declared activity component that
11723            // had been set as a preferred activity.  We try to clean this up
11724            // the next time we encounter that preferred activity, but it is
11725            // possible for the user flow to never be able to return to that
11726            // situation so here we do a sanity check to make sure we haven't
11727            // left any junk around.
11728            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11729            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11730                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11731                removed.clear();
11732                for (PreferredActivity pa : pir.filterSet()) {
11733                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11734                        removed.add(pa);
11735                    }
11736                }
11737                if (removed.size() > 0) {
11738                    for (int r=0; r<removed.size(); r++) {
11739                        PreferredActivity pa = removed.get(r);
11740                        Slog.w(TAG, "Removing dangling preferred activity: "
11741                                + pa.mPref.mComponent);
11742                        pir.removeFilter(pa);
11743                    }
11744                    mSettings.writePackageRestrictionsLPr(
11745                            mSettings.mPreferredActivities.keyAt(i));
11746                }
11747            }
11748        }
11749        sUserManager.systemReady();
11750    }
11751
11752    @Override
11753    public boolean isSafeMode() {
11754        return mSafeMode;
11755    }
11756
11757    @Override
11758    public boolean hasSystemUidErrors() {
11759        return mHasSystemUidErrors;
11760    }
11761
11762    static String arrayToString(int[] array) {
11763        StringBuffer buf = new StringBuffer(128);
11764        buf.append('[');
11765        if (array != null) {
11766            for (int i=0; i<array.length; i++) {
11767                if (i > 0) buf.append(", ");
11768                buf.append(array[i]);
11769            }
11770        }
11771        buf.append(']');
11772        return buf.toString();
11773    }
11774
11775    static class DumpState {
11776        public static final int DUMP_LIBS = 1 << 0;
11777
11778        public static final int DUMP_FEATURES = 1 << 1;
11779
11780        public static final int DUMP_RESOLVERS = 1 << 2;
11781
11782        public static final int DUMP_PERMISSIONS = 1 << 3;
11783
11784        public static final int DUMP_PACKAGES = 1 << 4;
11785
11786        public static final int DUMP_SHARED_USERS = 1 << 5;
11787
11788        public static final int DUMP_MESSAGES = 1 << 6;
11789
11790        public static final int DUMP_PROVIDERS = 1 << 7;
11791
11792        public static final int DUMP_VERIFIERS = 1 << 8;
11793
11794        public static final int DUMP_PREFERRED = 1 << 9;
11795
11796        public static final int DUMP_PREFERRED_XML = 1 << 10;
11797
11798        public static final int DUMP_KEYSETS = 1 << 11;
11799
11800        public static final int DUMP_VERSION = 1 << 12;
11801
11802        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11803
11804        private int mTypes;
11805
11806        private int mOptions;
11807
11808        private boolean mTitlePrinted;
11809
11810        private SharedUserSetting mSharedUser;
11811
11812        public boolean isDumping(int type) {
11813            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11814                return true;
11815            }
11816
11817            return (mTypes & type) != 0;
11818        }
11819
11820        public void setDump(int type) {
11821            mTypes |= type;
11822        }
11823
11824        public boolean isOptionEnabled(int option) {
11825            return (mOptions & option) != 0;
11826        }
11827
11828        public void setOptionEnabled(int option) {
11829            mOptions |= option;
11830        }
11831
11832        public boolean onTitlePrinted() {
11833            final boolean printed = mTitlePrinted;
11834            mTitlePrinted = true;
11835            return printed;
11836        }
11837
11838        public boolean getTitlePrinted() {
11839            return mTitlePrinted;
11840        }
11841
11842        public void setTitlePrinted(boolean enabled) {
11843            mTitlePrinted = enabled;
11844        }
11845
11846        public SharedUserSetting getSharedUser() {
11847            return mSharedUser;
11848        }
11849
11850        public void setSharedUser(SharedUserSetting user) {
11851            mSharedUser = user;
11852        }
11853    }
11854
11855    @Override
11856    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11857        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11858                != PackageManager.PERMISSION_GRANTED) {
11859            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11860                    + Binder.getCallingPid()
11861                    + ", uid=" + Binder.getCallingUid()
11862                    + " without permission "
11863                    + android.Manifest.permission.DUMP);
11864            return;
11865        }
11866
11867        DumpState dumpState = new DumpState();
11868        boolean fullPreferred = false;
11869        boolean checkin = false;
11870
11871        String packageName = null;
11872
11873        int opti = 0;
11874        while (opti < args.length) {
11875            String opt = args[opti];
11876            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11877                break;
11878            }
11879            opti++;
11880            if ("-a".equals(opt)) {
11881                // Right now we only know how to print all.
11882            } else if ("-h".equals(opt)) {
11883                pw.println("Package manager dump options:");
11884                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11885                pw.println("    --checkin: dump for a checkin");
11886                pw.println("    -f: print details of intent filters");
11887                pw.println("    -h: print this help");
11888                pw.println("  cmd may be one of:");
11889                pw.println("    l[ibraries]: list known shared libraries");
11890                pw.println("    f[ibraries]: list device features");
11891                pw.println("    k[eysets]: print known keysets");
11892                pw.println("    r[esolvers]: dump intent resolvers");
11893                pw.println("    perm[issions]: dump permissions");
11894                pw.println("    pref[erred]: print preferred package settings");
11895                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11896                pw.println("    prov[iders]: dump content providers");
11897                pw.println("    p[ackages]: dump installed packages");
11898                pw.println("    s[hared-users]: dump shared user IDs");
11899                pw.println("    m[essages]: print collected runtime messages");
11900                pw.println("    v[erifiers]: print package verifier info");
11901                pw.println("    version: print database version info");
11902                pw.println("    write: write current settings now");
11903                pw.println("    <package.name>: info about given package");
11904                return;
11905            } else if ("--checkin".equals(opt)) {
11906                checkin = true;
11907            } else if ("-f".equals(opt)) {
11908                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11909            } else {
11910                pw.println("Unknown argument: " + opt + "; use -h for help");
11911            }
11912        }
11913
11914        // Is the caller requesting to dump a particular piece of data?
11915        if (opti < args.length) {
11916            String cmd = args[opti];
11917            opti++;
11918            // Is this a package name?
11919            if ("android".equals(cmd) || cmd.contains(".")) {
11920                packageName = cmd;
11921                // When dumping a single package, we always dump all of its
11922                // filter information since the amount of data will be reasonable.
11923                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11924            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11925                dumpState.setDump(DumpState.DUMP_LIBS);
11926            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11927                dumpState.setDump(DumpState.DUMP_FEATURES);
11928            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11929                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11930            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11931                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11932            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11933                dumpState.setDump(DumpState.DUMP_PREFERRED);
11934            } else if ("preferred-xml".equals(cmd)) {
11935                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11936                if (opti < args.length && "--full".equals(args[opti])) {
11937                    fullPreferred = true;
11938                    opti++;
11939                }
11940            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11941                dumpState.setDump(DumpState.DUMP_PACKAGES);
11942            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11943                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11944            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11945                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11946            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11947                dumpState.setDump(DumpState.DUMP_MESSAGES);
11948            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11949                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11950            } else if ("version".equals(cmd)) {
11951                dumpState.setDump(DumpState.DUMP_VERSION);
11952            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11953                dumpState.setDump(DumpState.DUMP_KEYSETS);
11954            } else if ("write".equals(cmd)) {
11955                synchronized (mPackages) {
11956                    mSettings.writeLPr();
11957                    pw.println("Settings written.");
11958                    return;
11959                }
11960            }
11961        }
11962
11963        if (checkin) {
11964            pw.println("vers,1");
11965        }
11966
11967        // reader
11968        synchronized (mPackages) {
11969            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
11970                if (!checkin) {
11971                    if (dumpState.onTitlePrinted())
11972                        pw.println();
11973                    pw.println("Database versions:");
11974                    pw.print("  SDK Version:");
11975                    pw.print(" internal=");
11976                    pw.print(mSettings.mInternalSdkPlatform);
11977                    pw.print(" external=");
11978                    pw.println(mSettings.mExternalSdkPlatform);
11979                    pw.print("  DB Version:");
11980                    pw.print(" internal=");
11981                    pw.print(mSettings.mInternalDatabaseVersion);
11982                    pw.print(" external=");
11983                    pw.println(mSettings.mExternalDatabaseVersion);
11984                }
11985            }
11986
11987            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11988                if (!checkin) {
11989                    if (dumpState.onTitlePrinted())
11990                        pw.println();
11991                    pw.println("Verifiers:");
11992                    pw.print("  Required: ");
11993                    pw.print(mRequiredVerifierPackage);
11994                    pw.print(" (uid=");
11995                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11996                    pw.println(")");
11997                } else if (mRequiredVerifierPackage != null) {
11998                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11999                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12000                }
12001            }
12002
12003            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12004                boolean printedHeader = false;
12005                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12006                while (it.hasNext()) {
12007                    String name = it.next();
12008                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12009                    if (!checkin) {
12010                        if (!printedHeader) {
12011                            if (dumpState.onTitlePrinted())
12012                                pw.println();
12013                            pw.println("Libraries:");
12014                            printedHeader = true;
12015                        }
12016                        pw.print("  ");
12017                    } else {
12018                        pw.print("lib,");
12019                    }
12020                    pw.print(name);
12021                    if (!checkin) {
12022                        pw.print(" -> ");
12023                    }
12024                    if (ent.path != null) {
12025                        if (!checkin) {
12026                            pw.print("(jar) ");
12027                            pw.print(ent.path);
12028                        } else {
12029                            pw.print(",jar,");
12030                            pw.print(ent.path);
12031                        }
12032                    } else {
12033                        if (!checkin) {
12034                            pw.print("(apk) ");
12035                            pw.print(ent.apk);
12036                        } else {
12037                            pw.print(",apk,");
12038                            pw.print(ent.apk);
12039                        }
12040                    }
12041                    pw.println();
12042                }
12043            }
12044
12045            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12046                if (dumpState.onTitlePrinted())
12047                    pw.println();
12048                if (!checkin) {
12049                    pw.println("Features:");
12050                }
12051                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12052                while (it.hasNext()) {
12053                    String name = it.next();
12054                    if (!checkin) {
12055                        pw.print("  ");
12056                    } else {
12057                        pw.print("feat,");
12058                    }
12059                    pw.println(name);
12060                }
12061            }
12062
12063            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12064                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12065                        : "Activity Resolver Table:", "  ", packageName,
12066                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12067                    dumpState.setTitlePrinted(true);
12068                }
12069                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12070                        : "Receiver Resolver Table:", "  ", packageName,
12071                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12072                    dumpState.setTitlePrinted(true);
12073                }
12074                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12075                        : "Service Resolver Table:", "  ", packageName,
12076                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12077                    dumpState.setTitlePrinted(true);
12078                }
12079                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12080                        : "Provider Resolver Table:", "  ", packageName,
12081                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12082                    dumpState.setTitlePrinted(true);
12083                }
12084            }
12085
12086            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12087                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12088                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12089                    int user = mSettings.mPreferredActivities.keyAt(i);
12090                    if (pir.dump(pw,
12091                            dumpState.getTitlePrinted()
12092                                ? "\nPreferred Activities User " + user + ":"
12093                                : "Preferred Activities User " + user + ":", "  ",
12094                            packageName, true)) {
12095                        dumpState.setTitlePrinted(true);
12096                    }
12097                }
12098            }
12099
12100            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12101                pw.flush();
12102                FileOutputStream fout = new FileOutputStream(fd);
12103                BufferedOutputStream str = new BufferedOutputStream(fout);
12104                XmlSerializer serializer = new FastXmlSerializer();
12105                try {
12106                    serializer.setOutput(str, "utf-8");
12107                    serializer.startDocument(null, true);
12108                    serializer.setFeature(
12109                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12110                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12111                    serializer.endDocument();
12112                    serializer.flush();
12113                } catch (IllegalArgumentException e) {
12114                    pw.println("Failed writing: " + e);
12115                } catch (IllegalStateException e) {
12116                    pw.println("Failed writing: " + e);
12117                } catch (IOException e) {
12118                    pw.println("Failed writing: " + e);
12119                }
12120            }
12121
12122            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12123                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12124            }
12125
12126            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12127                boolean printedSomething = false;
12128                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12129                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12130                        continue;
12131                    }
12132                    if (!printedSomething) {
12133                        if (dumpState.onTitlePrinted())
12134                            pw.println();
12135                        pw.println("Registered ContentProviders:");
12136                        printedSomething = true;
12137                    }
12138                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12139                    pw.print("    "); pw.println(p.toString());
12140                }
12141                printedSomething = false;
12142                for (Map.Entry<String, PackageParser.Provider> entry :
12143                        mProvidersByAuthority.entrySet()) {
12144                    PackageParser.Provider p = entry.getValue();
12145                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12146                        continue;
12147                    }
12148                    if (!printedSomething) {
12149                        if (dumpState.onTitlePrinted())
12150                            pw.println();
12151                        pw.println("ContentProvider Authorities:");
12152                        printedSomething = true;
12153                    }
12154                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12155                    pw.print("    "); pw.println(p.toString());
12156                    if (p.info != null && p.info.applicationInfo != null) {
12157                        final String appInfo = p.info.applicationInfo.toString();
12158                        pw.print("      applicationInfo="); pw.println(appInfo);
12159                    }
12160                }
12161            }
12162
12163            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12164                mSettings.mKeySetManagerService.dump(pw, packageName, dumpState);
12165            }
12166
12167            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12168                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12169            }
12170
12171            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12172                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12173            }
12174
12175            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12176                if (dumpState.onTitlePrinted())
12177                    pw.println();
12178                mSettings.dumpReadMessagesLPr(pw, dumpState);
12179
12180                pw.println();
12181                pw.println("Package warning messages:");
12182                final File fname = getSettingsProblemFile();
12183                FileInputStream in = null;
12184                try {
12185                    in = new FileInputStream(fname);
12186                    final int avail = in.available();
12187                    final byte[] data = new byte[avail];
12188                    in.read(data);
12189                    pw.print(new String(data));
12190                } catch (FileNotFoundException e) {
12191                } catch (IOException e) {
12192                } finally {
12193                    if (in != null) {
12194                        try {
12195                            in.close();
12196                        } catch (IOException e) {
12197                        }
12198                    }
12199                }
12200            }
12201        }
12202    }
12203
12204    // ------- apps on sdcard specific code -------
12205    static final boolean DEBUG_SD_INSTALL = false;
12206
12207    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12208
12209    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12210
12211    private boolean mMediaMounted = false;
12212
12213    private String getEncryptKey() {
12214        try {
12215            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12216                    SD_ENCRYPTION_KEYSTORE_NAME);
12217            if (sdEncKey == null) {
12218                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12219                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12220                if (sdEncKey == null) {
12221                    Slog.e(TAG, "Failed to create encryption keys");
12222                    return null;
12223                }
12224            }
12225            return sdEncKey;
12226        } catch (NoSuchAlgorithmException nsae) {
12227            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12228            return null;
12229        } catch (IOException ioe) {
12230            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12231            return null;
12232        }
12233
12234    }
12235
12236    /* package */static String getTempContainerId() {
12237        int tmpIdx = 1;
12238        String list[] = PackageHelper.getSecureContainerList();
12239        if (list != null) {
12240            for (final String name : list) {
12241                // Ignore null and non-temporary container entries
12242                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12243                    continue;
12244                }
12245
12246                String subStr = name.substring(mTempContainerPrefix.length());
12247                try {
12248                    int cid = Integer.parseInt(subStr);
12249                    if (cid >= tmpIdx) {
12250                        tmpIdx = cid + 1;
12251                    }
12252                } catch (NumberFormatException e) {
12253                }
12254            }
12255        }
12256        return mTempContainerPrefix + tmpIdx;
12257    }
12258
12259    /*
12260     * Update media status on PackageManager.
12261     */
12262    @Override
12263    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12264        int callingUid = Binder.getCallingUid();
12265        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12266            throw new SecurityException("Media status can only be updated by the system");
12267        }
12268        // reader; this apparently protects mMediaMounted, but should probably
12269        // be a different lock in that case.
12270        synchronized (mPackages) {
12271            Log.i(TAG, "Updating external media status from "
12272                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12273                    + (mediaStatus ? "mounted" : "unmounted"));
12274            if (DEBUG_SD_INSTALL)
12275                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12276                        + ", mMediaMounted=" + mMediaMounted);
12277            if (mediaStatus == mMediaMounted) {
12278                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12279                        : 0, -1);
12280                mHandler.sendMessage(msg);
12281                return;
12282            }
12283            mMediaMounted = mediaStatus;
12284        }
12285        // Queue up an async operation since the package installation may take a
12286        // little while.
12287        mHandler.post(new Runnable() {
12288            public void run() {
12289                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12290            }
12291        });
12292    }
12293
12294    /**
12295     * Called by MountService when the initial ASECs to scan are available.
12296     * Should block until all the ASEC containers are finished being scanned.
12297     */
12298    public void scanAvailableAsecs() {
12299        updateExternalMediaStatusInner(true, false, false);
12300        if (mShouldRestoreconData) {
12301            SELinuxMMAC.setRestoreconDone();
12302            mShouldRestoreconData = false;
12303        }
12304    }
12305
12306    /*
12307     * Collect information of applications on external media, map them against
12308     * existing containers and update information based on current mount status.
12309     * Please note that we always have to report status if reportStatus has been
12310     * set to true especially when unloading packages.
12311     */
12312    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12313            boolean externalStorage) {
12314        // Collection of uids
12315        int uidArr[] = null;
12316        // Collection of stale containers
12317        HashSet<String> removeCids = new HashSet<String>();
12318        // Collection of packages on external media with valid containers.
12319        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12320        // Get list of secure containers.
12321        final String list[] = PackageHelper.getSecureContainerList();
12322        if (list == null || list.length == 0) {
12323            Log.i(TAG, "No secure containers on sdcard");
12324        } else {
12325            // Process list of secure containers and categorize them
12326            // as active or stale based on their package internal state.
12327            int uidList[] = new int[list.length];
12328            int num = 0;
12329            // reader
12330            synchronized (mPackages) {
12331                for (String cid : list) {
12332                    if (DEBUG_SD_INSTALL)
12333                        Log.i(TAG, "Processing container " + cid);
12334                    String pkgName = getAsecPackageName(cid);
12335                    if (pkgName == null) {
12336                        if (DEBUG_SD_INSTALL)
12337                            Log.i(TAG, "Container : " + cid + " stale");
12338                        removeCids.add(cid);
12339                        continue;
12340                    }
12341                    if (DEBUG_SD_INSTALL)
12342                        Log.i(TAG, "Looking for pkg : " + pkgName);
12343
12344                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12345                    if (ps == null) {
12346                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12347                        removeCids.add(cid);
12348                        continue;
12349                    }
12350
12351                    /*
12352                     * Skip packages that are not external if we're unmounting
12353                     * external storage.
12354                     */
12355                    if (externalStorage && !isMounted && !isExternal(ps)) {
12356                        continue;
12357                    }
12358
12359                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12360                            getAppInstructionSetFromSettings(ps),
12361                            isForwardLocked(ps));
12362                    // The package status is changed only if the code path
12363                    // matches between settings and the container id.
12364                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12365                        if (DEBUG_SD_INSTALL) {
12366                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12367                                    + " at code path: " + ps.codePathString);
12368                        }
12369
12370                        // We do have a valid package installed on sdcard
12371                        processCids.put(args, ps.codePathString);
12372                        final int uid = ps.appId;
12373                        if (uid != -1) {
12374                            uidList[num++] = uid;
12375                        }
12376                    } else {
12377                        Log.i(TAG, "Deleting stale container for " + cid);
12378                        removeCids.add(cid);
12379                    }
12380                }
12381            }
12382
12383            if (num > 0) {
12384                // Sort uid list
12385                Arrays.sort(uidList, 0, num);
12386                // Throw away duplicates
12387                uidArr = new int[num];
12388                uidArr[0] = uidList[0];
12389                int di = 0;
12390                for (int i = 1; i < num; i++) {
12391                    if (uidList[i - 1] != uidList[i]) {
12392                        uidArr[di++] = uidList[i];
12393                    }
12394                }
12395            }
12396        }
12397        // Process packages with valid entries.
12398        if (isMounted) {
12399            if (DEBUG_SD_INSTALL)
12400                Log.i(TAG, "Loading packages");
12401            loadMediaPackages(processCids, uidArr, removeCids);
12402            startCleaningPackages();
12403        } else {
12404            if (DEBUG_SD_INSTALL)
12405                Log.i(TAG, "Unloading packages");
12406            unloadMediaPackages(processCids, uidArr, reportStatus);
12407        }
12408    }
12409
12410   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12411           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12412        int size = pkgList.size();
12413        if (size > 0) {
12414            // Send broadcasts here
12415            Bundle extras = new Bundle();
12416            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12417                    .toArray(new String[size]));
12418            if (uidArr != null) {
12419                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12420            }
12421            if (replacing) {
12422                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12423            }
12424            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12425                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12426            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12427        }
12428    }
12429
12430   /*
12431     * Look at potentially valid container ids from processCids If package
12432     * information doesn't match the one on record or package scanning fails,
12433     * the cid is added to list of removeCids. We currently don't delete stale
12434     * containers.
12435     */
12436   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12437            HashSet<String> removeCids) {
12438        ArrayList<String> pkgList = new ArrayList<String>();
12439        Set<AsecInstallArgs> keys = processCids.keySet();
12440        boolean doGc = false;
12441        for (AsecInstallArgs args : keys) {
12442            String codePath = processCids.get(args);
12443            if (DEBUG_SD_INSTALL)
12444                Log.i(TAG, "Loading container : " + args.cid);
12445            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12446            try {
12447                // Make sure there are no container errors first.
12448                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12449                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12450                            + " when installing from sdcard");
12451                    continue;
12452                }
12453                // Check code path here.
12454                if (codePath == null || !codePath.equals(args.getCodePath())) {
12455                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12456                            + " does not match one in settings " + codePath);
12457                    continue;
12458                }
12459                // Parse package
12460                int parseFlags = mDefParseFlags;
12461                if (args.isExternal()) {
12462                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12463                }
12464                if (args.isFwdLocked()) {
12465                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12466                }
12467
12468                doGc = true;
12469                synchronized (mInstallLock) {
12470                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12471                            0, 0, null, null);
12472                    // Scan the package
12473                    if (pkg != null) {
12474                        /*
12475                         * TODO why is the lock being held? doPostInstall is
12476                         * called in other places without the lock. This needs
12477                         * to be straightened out.
12478                         */
12479                        // writer
12480                        synchronized (mPackages) {
12481                            retCode = PackageManager.INSTALL_SUCCEEDED;
12482                            pkgList.add(pkg.packageName);
12483                            // Post process args
12484                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12485                                    pkg.applicationInfo.uid);
12486                        }
12487                    } else {
12488                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12489                    }
12490                }
12491
12492            } finally {
12493                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12494                    // Don't destroy container here. Wait till gc clears things
12495                    // up.
12496                    removeCids.add(args.cid);
12497                }
12498            }
12499        }
12500        // writer
12501        synchronized (mPackages) {
12502            // If the platform SDK has changed since the last time we booted,
12503            // we need to re-grant app permission to catch any new ones that
12504            // appear. This is really a hack, and means that apps can in some
12505            // cases get permissions that the user didn't initially explicitly
12506            // allow... it would be nice to have some better way to handle
12507            // this situation.
12508            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12509            if (regrantPermissions)
12510                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12511                        + mSdkVersion + "; regranting permissions for external storage");
12512            mSettings.mExternalSdkPlatform = mSdkVersion;
12513
12514            // Make sure group IDs have been assigned, and any permission
12515            // changes in other apps are accounted for
12516            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12517                    | (regrantPermissions
12518                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12519                            : 0));
12520
12521            mSettings.updateExternalDatabaseVersion();
12522
12523            // can downgrade to reader
12524            // Persist settings
12525            mSettings.writeLPr();
12526        }
12527        // Send a broadcast to let everyone know we are done processing
12528        if (pkgList.size() > 0) {
12529            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12530        }
12531        // Force gc to avoid any stale parser references that we might have.
12532        if (doGc) {
12533            Runtime.getRuntime().gc();
12534        }
12535        // List stale containers and destroy stale temporary containers.
12536        if (removeCids != null) {
12537            for (String cid : removeCids) {
12538                if (cid.startsWith(mTempContainerPrefix)) {
12539                    Log.i(TAG, "Destroying stale temporary container " + cid);
12540                    PackageHelper.destroySdDir(cid);
12541                } else {
12542                    Log.w(TAG, "Container " + cid + " is stale");
12543               }
12544           }
12545        }
12546    }
12547
12548   /*
12549     * Utility method to unload a list of specified containers
12550     */
12551    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12552        // Just unmount all valid containers.
12553        for (AsecInstallArgs arg : cidArgs) {
12554            synchronized (mInstallLock) {
12555                arg.doPostDeleteLI(false);
12556           }
12557       }
12558   }
12559
12560    /*
12561     * Unload packages mounted on external media. This involves deleting package
12562     * data from internal structures, sending broadcasts about diabled packages,
12563     * gc'ing to free up references, unmounting all secure containers
12564     * corresponding to packages on external media, and posting a
12565     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12566     * that we always have to post this message if status has been requested no
12567     * matter what.
12568     */
12569    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12570            final boolean reportStatus) {
12571        if (DEBUG_SD_INSTALL)
12572            Log.i(TAG, "unloading media packages");
12573        ArrayList<String> pkgList = new ArrayList<String>();
12574        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12575        final Set<AsecInstallArgs> keys = processCids.keySet();
12576        for (AsecInstallArgs args : keys) {
12577            String pkgName = args.getPackageName();
12578            if (DEBUG_SD_INSTALL)
12579                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12580            // Delete package internally
12581            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12582            synchronized (mInstallLock) {
12583                boolean res = deletePackageLI(pkgName, null, false, null, null,
12584                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12585                if (res) {
12586                    pkgList.add(pkgName);
12587                } else {
12588                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12589                    failedList.add(args);
12590                }
12591            }
12592        }
12593
12594        // reader
12595        synchronized (mPackages) {
12596            // We didn't update the settings after removing each package;
12597            // write them now for all packages.
12598            mSettings.writeLPr();
12599        }
12600
12601        // We have to absolutely send UPDATED_MEDIA_STATUS only
12602        // after confirming that all the receivers processed the ordered
12603        // broadcast when packages get disabled, force a gc to clean things up.
12604        // and unload all the containers.
12605        if (pkgList.size() > 0) {
12606            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12607                    new IIntentReceiver.Stub() {
12608                public void performReceive(Intent intent, int resultCode, String data,
12609                        Bundle extras, boolean ordered, boolean sticky,
12610                        int sendingUser) throws RemoteException {
12611                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12612                            reportStatus ? 1 : 0, 1, keys);
12613                    mHandler.sendMessage(msg);
12614                }
12615            });
12616        } else {
12617            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12618                    keys);
12619            mHandler.sendMessage(msg);
12620        }
12621    }
12622
12623    /** Binder call */
12624    @Override
12625    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12626            final int flags) {
12627        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12628        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12629        int returnCode = PackageManager.MOVE_SUCCEEDED;
12630        int currFlags = 0;
12631        int newFlags = 0;
12632        // reader
12633        synchronized (mPackages) {
12634            PackageParser.Package pkg = mPackages.get(packageName);
12635            if (pkg == null) {
12636                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12637            } else {
12638                // Disable moving fwd locked apps and system packages
12639                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12640                    Slog.w(TAG, "Cannot move system application");
12641                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12642                } else if (pkg.mOperationPending) {
12643                    Slog.w(TAG, "Attempt to move package which has pending operations");
12644                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12645                } else {
12646                    // Find install location first
12647                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12648                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12649                        Slog.w(TAG, "Ambigous flags specified for move location.");
12650                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12651                    } else {
12652                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12653                                : PackageManager.INSTALL_INTERNAL;
12654                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12655                                : PackageManager.INSTALL_INTERNAL;
12656
12657                        if (newFlags == currFlags) {
12658                            Slog.w(TAG, "No move required. Trying to move to same location");
12659                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12660                        } else {
12661                            if (isForwardLocked(pkg)) {
12662                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12663                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12664                            }
12665                        }
12666                    }
12667                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12668                        pkg.mOperationPending = true;
12669                    }
12670                }
12671            }
12672
12673            /*
12674             * TODO this next block probably shouldn't be inside the lock. We
12675             * can't guarantee these won't change after this is fired off
12676             * anyway.
12677             */
12678            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12679                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user),
12680                        returnCode);
12681            } else {
12682                Message msg = mHandler.obtainMessage(INIT_COPY);
12683                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12684                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12685                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
12686                        pkg.applicationInfo.nativeLibraryDir, instructionSet);
12687                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12688                        instructionSet, pkg.applicationInfo.uid, user);
12689                msg.obj = mp;
12690                mHandler.sendMessage(msg);
12691            }
12692        }
12693    }
12694
12695    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12696        // Queue up an async operation since the package deletion may take a
12697        // little while.
12698        mHandler.post(new Runnable() {
12699            public void run() {
12700                // TODO fix this; this does nothing.
12701                mHandler.removeCallbacks(this);
12702                int returnCode = currentStatus;
12703                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12704                    int uidArr[] = null;
12705                    ArrayList<String> pkgList = null;
12706                    synchronized (mPackages) {
12707                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12708                        if (pkg == null) {
12709                            Slog.w(TAG, " Package " + mp.packageName
12710                                    + " doesn't exist. Aborting move");
12711                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12712                        } else if (!mp.srcArgs.getCodePath().equals(
12713                                pkg.applicationInfo.getCodePath())) {
12714                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12715                                    + mp.srcArgs.getCodePath() + " to "
12716                                    + pkg.applicationInfo.getCodePath()
12717                                    + " Aborting move and returning error");
12718                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12719                        } else {
12720                            uidArr = new int[] {
12721                                pkg.applicationInfo.uid
12722                            };
12723                            pkgList = new ArrayList<String>();
12724                            pkgList.add(mp.packageName);
12725                        }
12726                    }
12727                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12728                        // Send resources unavailable broadcast
12729                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12730                        // Update package code and resource paths
12731                        synchronized (mInstallLock) {
12732                            synchronized (mPackages) {
12733                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12734                                // Recheck for package again.
12735                                if (pkg == null) {
12736                                    Slog.w(TAG, " Package " + mp.packageName
12737                                            + " doesn't exist. Aborting move");
12738                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12739                                } else if (!mp.srcArgs.getCodePath().equals(
12740                                        pkg.applicationInfo.getCodePath())) {
12741                                    Slog.w(TAG, "Package " + mp.packageName
12742                                            + " code path changed from " + mp.srcArgs.getCodePath()
12743                                            + " to " + pkg.applicationInfo.getCodePath()
12744                                            + " Aborting move and returning error");
12745                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12746                                } else {
12747                                    final String oldCodePath = pkg.codePath;
12748                                    final String newCodePath = mp.targetArgs.getCodePath();
12749                                    final String newResPath = mp.targetArgs.getResourcePath();
12750                                    final String newNativePath = mp.targetArgs
12751                                            .getNativeLibraryPath();
12752
12753                                    final File newNativeDir = new File(newNativePath);
12754
12755                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12756                                        NativeLibraryHelper.Handle handle = null;
12757                                        try {
12758                                            handle = NativeLibraryHelper.Handle.create(
12759                                                    new File(newCodePath));
12760                                            final int abi = NativeLibraryHelper.findSupportedAbi(
12761                                                    handle, Build.SUPPORTED_ABIS);
12762                                            if (abi >= 0) {
12763                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12764                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12765                                            }
12766                                        } catch (IOException ioe) {
12767                                            Slog.w(TAG, "Unable to extract native libs for package :"
12768                                                    + mp.packageName, ioe);
12769                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12770                                        } finally {
12771                                            IoUtils.closeQuietly(handle);
12772                                        }
12773                                    }
12774                                    final int[] users = sUserManager.getUserIds();
12775                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12776                                        for (int user : users) {
12777                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12778                                                    newNativePath, user) < 0) {
12779                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12780                                            }
12781                                        }
12782                                    }
12783
12784                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12785                                        pkg.codePath = newCodePath;
12786                                        pkg.baseCodePath = newCodePath;
12787                                        // Move dex files around
12788                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
12789                                            // Moving of dex files failed. Set
12790                                            // error code and abort move.
12791                                            pkg.codePath = oldCodePath;
12792                                            pkg.baseCodePath = oldCodePath;
12793                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12794                                        }
12795                                    }
12796
12797                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12798                                        pkg.applicationInfo.setCodePath(newCodePath);
12799                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
12800                                        pkg.applicationInfo.setSplitCodePaths(null);
12801                                        pkg.applicationInfo.setResourcePath(newResPath);
12802                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
12803                                        pkg.applicationInfo.setSplitResourcePaths(null);
12804                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12805
12806                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12807                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
12808                                        ps.codePathString = ps.codePath.getPath();
12809                                        ps.resourcePath = new File(
12810                                                pkg.applicationInfo.getResourcePath());
12811                                        ps.resourcePathString = ps.resourcePath.getPath();
12812                                        ps.nativeLibraryPathString = newNativePath;
12813                                        // Set the application info flag
12814                                        // correctly.
12815                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12816                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12817                                        } else {
12818                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12819                                        }
12820                                        ps.setFlags(pkg.applicationInfo.flags);
12821                                        mAppDirs.remove(oldCodePath);
12822                                        mAppDirs.put(newCodePath, pkg);
12823                                        // Persist settings
12824                                        mSettings.writeLPr();
12825                                    }
12826                                }
12827                            }
12828                        }
12829                        // Send resources available broadcast
12830                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12831                    }
12832                }
12833                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12834                    // Clean up failed installation
12835                    if (mp.targetArgs != null) {
12836                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12837                                -1);
12838                    }
12839                } else {
12840                    // Force a gc to clear things up.
12841                    Runtime.getRuntime().gc();
12842                    // Delete older code
12843                    synchronized (mInstallLock) {
12844                        mp.srcArgs.doPostDeleteLI(true);
12845                    }
12846                }
12847
12848                // Allow more operations on this file if we didn't fail because
12849                // an operation was already pending for this package.
12850                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12851                    synchronized (mPackages) {
12852                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12853                        if (pkg != null) {
12854                            pkg.mOperationPending = false;
12855                       }
12856                   }
12857                }
12858
12859                IPackageMoveObserver observer = mp.observer;
12860                if (observer != null) {
12861                    try {
12862                        observer.packageMoved(mp.packageName, returnCode);
12863                    } catch (RemoteException e) {
12864                        Log.i(TAG, "Observer no longer exists.");
12865                    }
12866                }
12867            }
12868        });
12869    }
12870
12871    @Override
12872    public boolean setInstallLocation(int loc) {
12873        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12874                null);
12875        if (getInstallLocation() == loc) {
12876            return true;
12877        }
12878        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12879                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12880            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12881                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12882            return true;
12883        }
12884        return false;
12885   }
12886
12887    @Override
12888    public int getInstallLocation() {
12889        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12890                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12891                PackageHelper.APP_INSTALL_AUTO);
12892    }
12893
12894    /** Called by UserManagerService */
12895    void cleanUpUserLILPw(int userHandle) {
12896        mDirtyUsers.remove(userHandle);
12897        mSettings.removeUserLPw(userHandle);
12898        mPendingBroadcasts.remove(userHandle);
12899        if (mInstaller != null) {
12900            // Technically, we shouldn't be doing this with the package lock
12901            // held.  However, this is very rare, and there is already so much
12902            // other disk I/O going on, that we'll let it slide for now.
12903            mInstaller.removeUserDataDirs(userHandle);
12904        }
12905        mUserNeedsBadging.delete(userHandle);
12906    }
12907
12908    /** Called by UserManagerService */
12909    void createNewUserLILPw(int userHandle, File path) {
12910        if (mInstaller != null) {
12911            mInstaller.createUserConfig(userHandle);
12912            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12913        }
12914    }
12915
12916    @Override
12917    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12918        mContext.enforceCallingOrSelfPermission(
12919                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12920                "Only package verification agents can read the verifier device identity");
12921
12922        synchronized (mPackages) {
12923            return mSettings.getVerifierDeviceIdentityLPw();
12924        }
12925    }
12926
12927    @Override
12928    public void setPermissionEnforced(String permission, boolean enforced) {
12929        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12930        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12931            synchronized (mPackages) {
12932                if (mSettings.mReadExternalStorageEnforced == null
12933                        || mSettings.mReadExternalStorageEnforced != enforced) {
12934                    mSettings.mReadExternalStorageEnforced = enforced;
12935                    mSettings.writeLPr();
12936                }
12937            }
12938            // kill any non-foreground processes so we restart them and
12939            // grant/revoke the GID.
12940            final IActivityManager am = ActivityManagerNative.getDefault();
12941            if (am != null) {
12942                final long token = Binder.clearCallingIdentity();
12943                try {
12944                    am.killProcessesBelowForeground("setPermissionEnforcement");
12945                } catch (RemoteException e) {
12946                } finally {
12947                    Binder.restoreCallingIdentity(token);
12948                }
12949            }
12950        } else {
12951            throw new IllegalArgumentException("No selective enforcement for " + permission);
12952        }
12953    }
12954
12955    @Override
12956    @Deprecated
12957    public boolean isPermissionEnforced(String permission) {
12958        return true;
12959    }
12960
12961    @Override
12962    public boolean isStorageLow() {
12963        final long token = Binder.clearCallingIdentity();
12964        try {
12965            final DeviceStorageMonitorInternal
12966                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12967            if (dsm != null) {
12968                return dsm.isMemoryLow();
12969            } else {
12970                return false;
12971            }
12972        } finally {
12973            Binder.restoreCallingIdentity(token);
12974        }
12975    }
12976
12977    @Override
12978    public IPackageInstaller getPackageInstaller() {
12979        return mInstallerService;
12980    }
12981
12982    private boolean userNeedsBadging(int userId) {
12983        int index = mUserNeedsBadging.indexOfKey(userId);
12984        if (index < 0) {
12985            final UserInfo userInfo;
12986            final long token = Binder.clearCallingIdentity();
12987            try {
12988                userInfo = sUserManager.getUserInfo(userId);
12989            } finally {
12990                Binder.restoreCallingIdentity(token);
12991            }
12992            final boolean b;
12993            if (userInfo != null && userInfo.isManagedProfile()) {
12994                b = true;
12995            } else {
12996                b = false;
12997            }
12998            mUserNeedsBadging.put(userId, b);
12999            return b;
13000        }
13001        return mUserNeedsBadging.valueAt(index);
13002    }
13003}
13004