PackageManagerService.java revision 513a074de68a4772a9900e90f38e74ff92c15e7c
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    /** Directory where third-party apps are staged before install */
381    final File mAppStagingDir;
382
383    private final Random mTempFileRandom = new Random();
384
385    // ----------------------------------------------------------------
386
387    // Lock for state used when installing and doing other long running
388    // operations.  Methods that must be called with this lock held have
389    // the suffix "LI".
390    final Object mInstallLock = new Object();
391
392    // These are the directories in the 3rd party applications installed dir
393    // that we have currently loaded packages from.  Keys are the application's
394    // installed zip file (absolute codePath), and values are Package.
395    final HashMap<String, PackageParser.Package> mAppDirs =
396            new HashMap<String, PackageParser.Package>();
397
398    // Information for the parser to write more useful error messages.
399    int mLastScanError;
400
401    // ----------------------------------------------------------------
402
403    // Keys are String (package name), values are Package.  This also serves
404    // as the lock for the global state.  Methods that must be called with
405    // this lock held have the prefix "LP".
406    final HashMap<String, PackageParser.Package> mPackages =
407            new HashMap<String, PackageParser.Package>();
408
409    // Tracks available target package names -> overlay package paths.
410    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
411        new HashMap<String, HashMap<String, PackageParser.Package>>();
412
413    final Settings mSettings;
414    boolean mRestoredSettings;
415
416    // System configuration read by SystemConfig.
417    final int[] mGlobalGids;
418    final SparseArray<HashSet<String>> mSystemPermissions;
419    final HashMap<String, FeatureInfo> mAvailableFeatures;
420
421    // If mac_permissions.xml was found for seinfo labeling.
422    boolean mFoundPolicyFile;
423
424    // If a recursive restorecon of /data/data/<pkg> is needed.
425    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
426
427    public static final class SharedLibraryEntry {
428        public final String path;
429        public final String apk;
430
431        SharedLibraryEntry(String _path, String _apk) {
432            path = _path;
433            apk = _apk;
434        }
435    }
436
437    // Currently known shared libraries.
438    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
439            new HashMap<String, SharedLibraryEntry>();
440
441    // All available activities, for your resolving pleasure.
442    final ActivityIntentResolver mActivities =
443            new ActivityIntentResolver();
444
445    // All available receivers, for your resolving pleasure.
446    final ActivityIntentResolver mReceivers =
447            new ActivityIntentResolver();
448
449    // All available services, for your resolving pleasure.
450    final ServiceIntentResolver mServices = new ServiceIntentResolver();
451
452    // All available providers, for your resolving pleasure.
453    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
454
455    // Mapping from provider base names (first directory in content URI codePath)
456    // to the provider information.
457    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
458            new HashMap<String, PackageParser.Provider>();
459
460    // Mapping from instrumentation class names to info about them.
461    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
462            new HashMap<ComponentName, PackageParser.Instrumentation>();
463
464    // Mapping from permission names to info about them.
465    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
466            new HashMap<String, PackageParser.PermissionGroup>();
467
468    // Packages whose data we have transfered into another package, thus
469    // should no longer exist.
470    final HashSet<String> mTransferedPackages = new HashSet<String>();
471
472    // Broadcast actions that are only available to the system.
473    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
474
475    /** List of packages waiting for verification. */
476    final SparseArray<PackageVerificationState> mPendingVerification
477            = new SparseArray<PackageVerificationState>();
478
479    final PackageInstallerService mInstallerService;
480
481    HashSet<PackageParser.Package> mDeferredDexOpt = null;
482
483    // Cache of users who need badging.
484    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
485
486    /** Token for keys in mPendingVerification. */
487    private int mPendingVerificationToken = 0;
488
489    boolean mSystemReady;
490    boolean mSafeMode;
491    boolean mHasSystemUidErrors;
492
493    ApplicationInfo mAndroidApplication;
494    final ActivityInfo mResolveActivity = new ActivityInfo();
495    final ResolveInfo mResolveInfo = new ResolveInfo();
496    ComponentName mResolveComponentName;
497    PackageParser.Package mPlatformPackage;
498    ComponentName mCustomResolverComponentName;
499
500    boolean mResolverReplaced = false;
501
502    // Set of pending broadcasts for aggregating enable/disable of components.
503    static class PendingPackageBroadcasts {
504        // for each user id, a map of <package name -> components within that package>
505        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
506
507        public PendingPackageBroadcasts() {
508            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
509        }
510
511        public ArrayList<String> get(int userId, String packageName) {
512            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
513            return packages.get(packageName);
514        }
515
516        public void put(int userId, String packageName, ArrayList<String> components) {
517            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
518            packages.put(packageName, components);
519        }
520
521        public void remove(int userId, String packageName) {
522            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
523            if (packages != null) {
524                packages.remove(packageName);
525            }
526        }
527
528        public void remove(int userId) {
529            mUidMap.remove(userId);
530        }
531
532        public int userIdCount() {
533            return mUidMap.size();
534        }
535
536        public int userIdAt(int n) {
537            return mUidMap.keyAt(n);
538        }
539
540        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
541            return mUidMap.get(userId);
542        }
543
544        public int size() {
545            // total number of pending broadcast entries across all userIds
546            int num = 0;
547            for (int i = 0; i< mUidMap.size(); i++) {
548                num += mUidMap.valueAt(i).size();
549            }
550            return num;
551        }
552
553        public void clear() {
554            mUidMap.clear();
555        }
556
557        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
558            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
559            if (map == null) {
560                map = new HashMap<String, ArrayList<String>>();
561                mUidMap.put(userId, map);
562            }
563            return map;
564        }
565    }
566    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
567
568    // Service Connection to remote media container service to copy
569    // package uri's from external media onto secure containers
570    // or internal storage.
571    private IMediaContainerService mContainerService = null;
572
573    static final int SEND_PENDING_BROADCAST = 1;
574    static final int MCS_BOUND = 3;
575    static final int END_COPY = 4;
576    static final int INIT_COPY = 5;
577    static final int MCS_UNBIND = 6;
578    static final int START_CLEANING_PACKAGE = 7;
579    static final int FIND_INSTALL_LOC = 8;
580    static final int POST_INSTALL = 9;
581    static final int MCS_RECONNECT = 10;
582    static final int MCS_GIVE_UP = 11;
583    static final int UPDATED_MEDIA_STATUS = 12;
584    static final int WRITE_SETTINGS = 13;
585    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
586    static final int PACKAGE_VERIFIED = 15;
587    static final int CHECK_PENDING_VERIFICATION = 16;
588
589    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
590
591    // Delay time in millisecs
592    static final int BROADCAST_DELAY = 10 * 1000;
593
594    static UserManagerService sUserManager;
595
596    // Stores a list of users whose package restrictions file needs to be updated
597    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
598
599    final private DefaultContainerConnection mDefContainerConn =
600            new DefaultContainerConnection();
601    class DefaultContainerConnection implements ServiceConnection {
602        public void onServiceConnected(ComponentName name, IBinder service) {
603            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
604            IMediaContainerService imcs =
605                IMediaContainerService.Stub.asInterface(service);
606            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
607        }
608
609        public void onServiceDisconnected(ComponentName name) {
610            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
611        }
612    };
613
614    // Recordkeeping of restore-after-install operations that are currently in flight
615    // between the Package Manager and the Backup Manager
616    class PostInstallData {
617        public InstallArgs args;
618        public PackageInstalledInfo res;
619
620        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
621            args = _a;
622            res = _r;
623        }
624    };
625    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
626    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
627
628    private final String mRequiredVerifierPackage;
629
630    private final PackageUsage mPackageUsage = new PackageUsage();
631
632    private class PackageUsage {
633        private static final int WRITE_INTERVAL
634            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
635
636        private final Object mFileLock = new Object();
637        private final AtomicLong mLastWritten = new AtomicLong(0);
638        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
639
640        private boolean mIsHistoricalPackageUsageAvailable = true;
641
642        boolean isHistoricalPackageUsageAvailable() {
643            return mIsHistoricalPackageUsageAvailable;
644        }
645
646        void write(boolean force) {
647            if (force) {
648                writeInternal();
649                return;
650            }
651            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
652                && !DEBUG_DEXOPT) {
653                return;
654            }
655            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
656                new Thread("PackageUsage_DiskWriter") {
657                    @Override
658                    public void run() {
659                        try {
660                            writeInternal();
661                        } finally {
662                            mBackgroundWriteRunning.set(false);
663                        }
664                    }
665                }.start();
666            }
667        }
668
669        private void writeInternal() {
670            synchronized (mPackages) {
671                synchronized (mFileLock) {
672                    AtomicFile file = getFile();
673                    FileOutputStream f = null;
674                    try {
675                        f = file.startWrite();
676                        BufferedOutputStream out = new BufferedOutputStream(f);
677                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
678                        StringBuilder sb = new StringBuilder();
679                        for (PackageParser.Package pkg : mPackages.values()) {
680                            if (pkg.mLastPackageUsageTimeInMills == 0) {
681                                continue;
682                            }
683                            sb.setLength(0);
684                            sb.append(pkg.packageName);
685                            sb.append(' ');
686                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
687                            sb.append('\n');
688                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
689                        }
690                        out.flush();
691                        file.finishWrite(f);
692                    } catch (IOException e) {
693                        if (f != null) {
694                            file.failWrite(f);
695                        }
696                        Log.e(TAG, "Failed to write package usage times", e);
697                    }
698                }
699            }
700            mLastWritten.set(SystemClock.elapsedRealtime());
701        }
702
703        void readLP() {
704            synchronized (mFileLock) {
705                AtomicFile file = getFile();
706                BufferedInputStream in = null;
707                try {
708                    in = new BufferedInputStream(file.openRead());
709                    StringBuffer sb = new StringBuffer();
710                    while (true) {
711                        String packageName = readToken(in, sb, ' ');
712                        if (packageName == null) {
713                            break;
714                        }
715                        String timeInMillisString = readToken(in, sb, '\n');
716                        if (timeInMillisString == null) {
717                            throw new IOException("Failed to find last usage time for package "
718                                                  + packageName);
719                        }
720                        PackageParser.Package pkg = mPackages.get(packageName);
721                        if (pkg == null) {
722                            continue;
723                        }
724                        long timeInMillis;
725                        try {
726                            timeInMillis = Long.parseLong(timeInMillisString.toString());
727                        } catch (NumberFormatException e) {
728                            throw new IOException("Failed to parse " + timeInMillisString
729                                                  + " as a long.", e);
730                        }
731                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
732                    }
733                } catch (FileNotFoundException expected) {
734                    mIsHistoricalPackageUsageAvailable = false;
735                } catch (IOException e) {
736                    Log.w(TAG, "Failed to read package usage times", e);
737                } finally {
738                    IoUtils.closeQuietly(in);
739                }
740            }
741            mLastWritten.set(SystemClock.elapsedRealtime());
742        }
743
744        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
745                throws IOException {
746            sb.setLength(0);
747            while (true) {
748                int ch = in.read();
749                if (ch == -1) {
750                    if (sb.length() == 0) {
751                        return null;
752                    }
753                    throw new IOException("Unexpected EOF");
754                }
755                if (ch == endOfToken) {
756                    return sb.toString();
757                }
758                sb.append((char)ch);
759            }
760        }
761
762        private AtomicFile getFile() {
763            File dataDir = Environment.getDataDirectory();
764            File systemDir = new File(dataDir, "system");
765            File fname = new File(systemDir, "package-usage.list");
766            return new AtomicFile(fname);
767        }
768    }
769
770    class PackageHandler extends Handler {
771        private boolean mBound = false;
772        final ArrayList<HandlerParams> mPendingInstalls =
773            new ArrayList<HandlerParams>();
774
775        private boolean connectToService() {
776            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
777                    " DefaultContainerService");
778            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
779            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
780            if (mContext.bindServiceAsUser(service, mDefContainerConn,
781                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
782                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
783                mBound = true;
784                return true;
785            }
786            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
787            return false;
788        }
789
790        private void disconnectService() {
791            mContainerService = null;
792            mBound = false;
793            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
794            mContext.unbindService(mDefContainerConn);
795            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
796        }
797
798        PackageHandler(Looper looper) {
799            super(looper);
800        }
801
802        public void handleMessage(Message msg) {
803            try {
804                doHandleMessage(msg);
805            } finally {
806                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
807            }
808        }
809
810        void doHandleMessage(Message msg) {
811            switch (msg.what) {
812                case INIT_COPY: {
813                    HandlerParams params = (HandlerParams) msg.obj;
814                    int idx = mPendingInstalls.size();
815                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
816                    // If a bind was already initiated we dont really
817                    // need to do anything. The pending install
818                    // will be processed later on.
819                    if (!mBound) {
820                        // If this is the only one pending we might
821                        // have to bind to the service again.
822                        if (!connectToService()) {
823                            Slog.e(TAG, "Failed to bind to media container service");
824                            params.serviceError();
825                            return;
826                        } else {
827                            // Once we bind to the service, the first
828                            // pending request will be processed.
829                            mPendingInstalls.add(idx, params);
830                        }
831                    } else {
832                        mPendingInstalls.add(idx, params);
833                        // Already bound to the service. Just make
834                        // sure we trigger off processing the first request.
835                        if (idx == 0) {
836                            mHandler.sendEmptyMessage(MCS_BOUND);
837                        }
838                    }
839                    break;
840                }
841                case MCS_BOUND: {
842                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
843                    if (msg.obj != null) {
844                        mContainerService = (IMediaContainerService) msg.obj;
845                    }
846                    if (mContainerService == null) {
847                        // Something seriously wrong. Bail out
848                        Slog.e(TAG, "Cannot bind to media container service");
849                        for (HandlerParams params : mPendingInstalls) {
850                            // Indicate service bind error
851                            params.serviceError();
852                        }
853                        mPendingInstalls.clear();
854                    } else if (mPendingInstalls.size() > 0) {
855                        HandlerParams params = mPendingInstalls.get(0);
856                        if (params != null) {
857                            if (params.startCopy()) {
858                                // We are done...  look for more work or to
859                                // go idle.
860                                if (DEBUG_SD_INSTALL) Log.i(TAG,
861                                        "Checking for more work or unbind...");
862                                // Delete pending install
863                                if (mPendingInstalls.size() > 0) {
864                                    mPendingInstalls.remove(0);
865                                }
866                                if (mPendingInstalls.size() == 0) {
867                                    if (mBound) {
868                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
869                                                "Posting delayed MCS_UNBIND");
870                                        removeMessages(MCS_UNBIND);
871                                        Message ubmsg = obtainMessage(MCS_UNBIND);
872                                        // Unbind after a little delay, to avoid
873                                        // continual thrashing.
874                                        sendMessageDelayed(ubmsg, 10000);
875                                    }
876                                } else {
877                                    // There are more pending requests in queue.
878                                    // Just post MCS_BOUND message to trigger processing
879                                    // of next pending install.
880                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
881                                            "Posting MCS_BOUND for next work");
882                                    mHandler.sendEmptyMessage(MCS_BOUND);
883                                }
884                            }
885                        }
886                    } else {
887                        // Should never happen ideally.
888                        Slog.w(TAG, "Empty queue");
889                    }
890                    break;
891                }
892                case MCS_RECONNECT: {
893                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
894                    if (mPendingInstalls.size() > 0) {
895                        if (mBound) {
896                            disconnectService();
897                        }
898                        if (!connectToService()) {
899                            Slog.e(TAG, "Failed to bind to media container service");
900                            for (HandlerParams params : mPendingInstalls) {
901                                // Indicate service bind error
902                                params.serviceError();
903                            }
904                            mPendingInstalls.clear();
905                        }
906                    }
907                    break;
908                }
909                case MCS_UNBIND: {
910                    // If there is no actual work left, then time to unbind.
911                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
912
913                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
914                        if (mBound) {
915                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
916
917                            disconnectService();
918                        }
919                    } else if (mPendingInstalls.size() > 0) {
920                        // There are more pending requests in queue.
921                        // Just post MCS_BOUND message to trigger processing
922                        // of next pending install.
923                        mHandler.sendEmptyMessage(MCS_BOUND);
924                    }
925
926                    break;
927                }
928                case MCS_GIVE_UP: {
929                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
930                    mPendingInstalls.remove(0);
931                    break;
932                }
933                case SEND_PENDING_BROADCAST: {
934                    String packages[];
935                    ArrayList<String> components[];
936                    int size = 0;
937                    int uids[];
938                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
939                    synchronized (mPackages) {
940                        if (mPendingBroadcasts == null) {
941                            return;
942                        }
943                        size = mPendingBroadcasts.size();
944                        if (size <= 0) {
945                            // Nothing to be done. Just return
946                            return;
947                        }
948                        packages = new String[size];
949                        components = new ArrayList[size];
950                        uids = new int[size];
951                        int i = 0;  // filling out the above arrays
952
953                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
954                            int packageUserId = mPendingBroadcasts.userIdAt(n);
955                            Iterator<Map.Entry<String, ArrayList<String>>> it
956                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
957                                            .entrySet().iterator();
958                            while (it.hasNext() && i < size) {
959                                Map.Entry<String, ArrayList<String>> ent = it.next();
960                                packages[i] = ent.getKey();
961                                components[i] = ent.getValue();
962                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
963                                uids[i] = (ps != null)
964                                        ? UserHandle.getUid(packageUserId, ps.appId)
965                                        : -1;
966                                i++;
967                            }
968                        }
969                        size = i;
970                        mPendingBroadcasts.clear();
971                    }
972                    // Send broadcasts
973                    for (int i = 0; i < size; i++) {
974                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
975                    }
976                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
977                    break;
978                }
979                case START_CLEANING_PACKAGE: {
980                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
981                    final String packageName = (String)msg.obj;
982                    final int userId = msg.arg1;
983                    final boolean andCode = msg.arg2 != 0;
984                    synchronized (mPackages) {
985                        if (userId == UserHandle.USER_ALL) {
986                            int[] users = sUserManager.getUserIds();
987                            for (int user : users) {
988                                mSettings.addPackageToCleanLPw(
989                                        new PackageCleanItem(user, packageName, andCode));
990                            }
991                        } else {
992                            mSettings.addPackageToCleanLPw(
993                                    new PackageCleanItem(userId, packageName, andCode));
994                        }
995                    }
996                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
997                    startCleaningPackages();
998                } break;
999                case POST_INSTALL: {
1000                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
1001                    PostInstallData data = mRunningInstalls.get(msg.arg1);
1002                    mRunningInstalls.delete(msg.arg1);
1003                    boolean deleteOld = false;
1004
1005                    if (data != null) {
1006                        InstallArgs args = data.args;
1007                        PackageInstalledInfo res = data.res;
1008
1009                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
1010                            res.removedInfo.sendBroadcast(false, true, false);
1011                            Bundle extras = new Bundle(1);
1012                            extras.putInt(Intent.EXTRA_UID, res.uid);
1013                            // Determine the set of users who are adding this
1014                            // package for the first time vs. those who are seeing
1015                            // an update.
1016                            int[] firstUsers;
1017                            int[] updateUsers = new int[0];
1018                            if (res.origUsers == null || res.origUsers.length == 0) {
1019                                firstUsers = res.newUsers;
1020                            } else {
1021                                firstUsers = new int[0];
1022                                for (int i=0; i<res.newUsers.length; i++) {
1023                                    int user = res.newUsers[i];
1024                                    boolean isNew = true;
1025                                    for (int j=0; j<res.origUsers.length; j++) {
1026                                        if (res.origUsers[j] == user) {
1027                                            isNew = false;
1028                                            break;
1029                                        }
1030                                    }
1031                                    if (isNew) {
1032                                        int[] newFirst = new int[firstUsers.length+1];
1033                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1034                                                firstUsers.length);
1035                                        newFirst[firstUsers.length] = user;
1036                                        firstUsers = newFirst;
1037                                    } else {
1038                                        int[] newUpdate = new int[updateUsers.length+1];
1039                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1040                                                updateUsers.length);
1041                                        newUpdate[updateUsers.length] = user;
1042                                        updateUsers = newUpdate;
1043                                    }
1044                                }
1045                            }
1046                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1047                                    res.pkg.applicationInfo.packageName,
1048                                    extras, null, null, firstUsers);
1049                            final boolean update = res.removedInfo.removedPackage != null;
1050                            if (update) {
1051                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1052                            }
1053                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1054                                    res.pkg.applicationInfo.packageName,
1055                                    extras, null, null, updateUsers);
1056                            if (update) {
1057                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1058                                        res.pkg.applicationInfo.packageName,
1059                                        extras, null, null, updateUsers);
1060                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1061                                        null, null,
1062                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1063
1064                                // treat asec-hosted packages like removable media on upgrade
1065                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1066                                    if (DEBUG_INSTALL) {
1067                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1068                                                + " is ASEC-hosted -> AVAILABLE");
1069                                    }
1070                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1071                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1072                                    pkgList.add(res.pkg.applicationInfo.packageName);
1073                                    sendResourcesChangedBroadcast(true, true,
1074                                            pkgList,uidArray, null);
1075                                }
1076                            }
1077                            if (res.removedInfo.args != null) {
1078                                // Remove the replaced package's older resources safely now
1079                                deleteOld = true;
1080                            }
1081
1082                            // Log current value of "unknown sources" setting
1083                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1084                                getUnknownSourcesSettings());
1085                        }
1086                        // Force a gc to clear up things
1087                        Runtime.getRuntime().gc();
1088                        // We delete after a gc for applications  on sdcard.
1089                        if (deleteOld) {
1090                            synchronized (mInstallLock) {
1091                                res.removedInfo.args.doPostDeleteLI(true);
1092                            }
1093                        }
1094                        if (args.observer != null) {
1095                            try {
1096                                Bundle extras = extrasForInstallResult(res);
1097                                args.observer.packageInstalled(res.name, extras, res.returnCode);
1098                            } catch (RemoteException e) {
1099                                Slog.i(TAG, "Observer no longer exists.");
1100                            }
1101                        }
1102                    } else {
1103                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1104                    }
1105                } break;
1106                case UPDATED_MEDIA_STATUS: {
1107                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1108                    boolean reportStatus = msg.arg1 == 1;
1109                    boolean doGc = msg.arg2 == 1;
1110                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1111                    if (doGc) {
1112                        // Force a gc to clear up stale containers.
1113                        Runtime.getRuntime().gc();
1114                    }
1115                    if (msg.obj != null) {
1116                        @SuppressWarnings("unchecked")
1117                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1118                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1119                        // Unload containers
1120                        unloadAllContainers(args);
1121                    }
1122                    if (reportStatus) {
1123                        try {
1124                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1125                            PackageHelper.getMountService().finishMediaUpdate();
1126                        } catch (RemoteException e) {
1127                            Log.e(TAG, "MountService not running?");
1128                        }
1129                    }
1130                } break;
1131                case WRITE_SETTINGS: {
1132                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1133                    synchronized (mPackages) {
1134                        removeMessages(WRITE_SETTINGS);
1135                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1136                        mSettings.writeLPr();
1137                        mDirtyUsers.clear();
1138                    }
1139                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1140                } break;
1141                case WRITE_PACKAGE_RESTRICTIONS: {
1142                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1143                    synchronized (mPackages) {
1144                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1145                        for (int userId : mDirtyUsers) {
1146                            mSettings.writePackageRestrictionsLPr(userId);
1147                        }
1148                        mDirtyUsers.clear();
1149                    }
1150                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1151                } break;
1152                case CHECK_PENDING_VERIFICATION: {
1153                    final int verificationId = msg.arg1;
1154                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1155
1156                    if ((state != null) && !state.timeoutExtended()) {
1157                        final InstallArgs args = state.getInstallArgs();
1158                        final Uri originUri = Uri.fromFile(args.originFile);
1159
1160                        Slog.i(TAG, "Verification timed out for " + originUri);
1161                        mPendingVerification.remove(verificationId);
1162
1163                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1164
1165                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1166                            Slog.i(TAG, "Continuing with installation of " + originUri);
1167                            state.setVerifierResponse(Binder.getCallingUid(),
1168                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1169                            broadcastPackageVerified(verificationId, originUri,
1170                                    PackageManager.VERIFICATION_ALLOW,
1171                                    state.getInstallArgs().getUser());
1172                            try {
1173                                ret = args.copyApk(mContainerService, true);
1174                            } catch (RemoteException e) {
1175                                Slog.e(TAG, "Could not contact the ContainerService");
1176                            }
1177                        } else {
1178                            broadcastPackageVerified(verificationId, originUri,
1179                                    PackageManager.VERIFICATION_REJECT,
1180                                    state.getInstallArgs().getUser());
1181                        }
1182
1183                        processPendingInstall(args, ret);
1184                        mHandler.sendEmptyMessage(MCS_UNBIND);
1185                    }
1186                    break;
1187                }
1188                case PACKAGE_VERIFIED: {
1189                    final int verificationId = msg.arg1;
1190
1191                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1192                    if (state == null) {
1193                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1194                        break;
1195                    }
1196
1197                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1198
1199                    state.setVerifierResponse(response.callerUid, response.code);
1200
1201                    if (state.isVerificationComplete()) {
1202                        mPendingVerification.remove(verificationId);
1203
1204                        final InstallArgs args = state.getInstallArgs();
1205                        final Uri originUri = Uri.fromFile(args.originFile);
1206
1207                        int ret;
1208                        if (state.isInstallAllowed()) {
1209                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1210                            broadcastPackageVerified(verificationId, originUri,
1211                                    response.code, state.getInstallArgs().getUser());
1212                            try {
1213                                ret = args.copyApk(mContainerService, true);
1214                            } catch (RemoteException e) {
1215                                Slog.e(TAG, "Could not contact the ContainerService");
1216                            }
1217                        } else {
1218                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1219                        }
1220
1221                        processPendingInstall(args, ret);
1222
1223                        mHandler.sendEmptyMessage(MCS_UNBIND);
1224                    }
1225
1226                    break;
1227                }
1228            }
1229        }
1230    }
1231
1232    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1233        Bundle extras = null;
1234        switch (res.returnCode) {
1235            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1236                extras = new Bundle();
1237                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1238                        res.origPermission);
1239                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1240                        res.origPackage);
1241                break;
1242            }
1243        }
1244        return extras;
1245    }
1246
1247    void scheduleWriteSettingsLocked() {
1248        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1249            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1250        }
1251    }
1252
1253    void scheduleWritePackageRestrictionsLocked(int userId) {
1254        if (!sUserManager.exists(userId)) return;
1255        mDirtyUsers.add(userId);
1256        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1257            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1258        }
1259    }
1260
1261    public static final PackageManagerService main(Context context, Installer installer,
1262            boolean factoryTest, boolean onlyCore) {
1263        PackageManagerService m = new PackageManagerService(context, installer,
1264                factoryTest, onlyCore);
1265        ServiceManager.addService("package", m);
1266        return m;
1267    }
1268
1269    static String[] splitString(String str, char sep) {
1270        int count = 1;
1271        int i = 0;
1272        while ((i=str.indexOf(sep, i)) >= 0) {
1273            count++;
1274            i++;
1275        }
1276
1277        String[] res = new String[count];
1278        i=0;
1279        count = 0;
1280        int lastI=0;
1281        while ((i=str.indexOf(sep, i)) >= 0) {
1282            res[count] = str.substring(lastI, i);
1283            count++;
1284            i++;
1285            lastI = i;
1286        }
1287        res[count] = str.substring(lastI, str.length());
1288        return res;
1289    }
1290
1291    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1292        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1293                Context.DISPLAY_SERVICE);
1294        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1295    }
1296
1297    public PackageManagerService(Context context, Installer installer,
1298            boolean factoryTest, boolean onlyCore) {
1299        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1300                SystemClock.uptimeMillis());
1301
1302        if (mSdkVersion <= 0) {
1303            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1304        }
1305
1306        mContext = context;
1307        mFactoryTest = factoryTest;
1308        mOnlyCore = onlyCore;
1309        mMetrics = new DisplayMetrics();
1310        mSettings = new Settings(context);
1311        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1314                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1315        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1316                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1317        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1318                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1319        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1320                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1321        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1322                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1323
1324        String separateProcesses = SystemProperties.get("debug.separate_processes");
1325        if (separateProcesses != null && separateProcesses.length() > 0) {
1326            if ("*".equals(separateProcesses)) {
1327                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1328                mSeparateProcesses = null;
1329                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1330            } else {
1331                mDefParseFlags = 0;
1332                mSeparateProcesses = separateProcesses.split(",");
1333                Slog.w(TAG, "Running with debug.separate_processes: "
1334                        + separateProcesses);
1335            }
1336        } else {
1337            mDefParseFlags = 0;
1338            mSeparateProcesses = null;
1339        }
1340
1341        mInstaller = installer;
1342
1343        getDefaultDisplayMetrics(context, mMetrics);
1344
1345        SystemConfig systemConfig = SystemConfig.getInstance();
1346        mGlobalGids = systemConfig.getGlobalGids();
1347        mSystemPermissions = systemConfig.getSystemPermissions();
1348        mAvailableFeatures = systemConfig.getAvailableFeatures();
1349
1350        synchronized (mInstallLock) {
1351        // writer
1352        synchronized (mPackages) {
1353            mHandlerThread = new ServiceThread(TAG,
1354                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1355            mHandlerThread.start();
1356            mHandler = new PackageHandler(mHandlerThread.getLooper());
1357            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1358
1359            File dataDir = Environment.getDataDirectory();
1360            mAppDataDir = new File(dataDir, "data");
1361            mAppInstallDir = new File(dataDir, "app");
1362            mAppLibInstallDir = new File(dataDir, "app-lib");
1363            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1364            mUserAppDataDir = new File(dataDir, "user");
1365            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1366            mAppStagingDir = new File(dataDir, "app-staging");
1367
1368            sUserManager = new UserManagerService(context, this,
1369                    mInstallLock, mPackages);
1370
1371            // Propagate permission configuration in to package manager.
1372            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1373                    = systemConfig.getPermissions();
1374            for (int i=0; i<permConfig.size(); i++) {
1375                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1376                BasePermission bp = mSettings.mPermissions.get(perm.name);
1377                if (bp == null) {
1378                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1379                    mSettings.mPermissions.put(perm.name, bp);
1380                }
1381                if (perm.gids != null) {
1382                    bp.gids = appendInts(bp.gids, perm.gids);
1383                }
1384            }
1385
1386            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1387            for (int i=0; i<libConfig.size(); i++) {
1388                mSharedLibraries.put(libConfig.keyAt(i),
1389                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1390            }
1391
1392            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1393
1394            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1395                    mSdkVersion, mOnlyCore);
1396
1397            String customResolverActivity = Resources.getSystem().getString(
1398                    R.string.config_customResolverActivity);
1399            if (TextUtils.isEmpty(customResolverActivity)) {
1400                customResolverActivity = null;
1401            } else {
1402                mCustomResolverComponentName = ComponentName.unflattenFromString(
1403                        customResolverActivity);
1404            }
1405
1406            long startTime = SystemClock.uptimeMillis();
1407
1408            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1409                    startTime);
1410
1411            // Set flag to monitor and not change apk file paths when
1412            // scanning install directories.
1413            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1414
1415            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1416
1417            /**
1418             * Add everything in the in the boot class path to the
1419             * list of process files because dexopt will have been run
1420             * if necessary during zygote startup.
1421             */
1422            String bootClassPath = System.getProperty("java.boot.class.path");
1423            if (bootClassPath != null) {
1424                String[] paths = splitString(bootClassPath, ':');
1425                for (int i=0; i<paths.length; i++) {
1426                    alreadyDexOpted.add(paths[i]);
1427                }
1428            } else {
1429                Slog.w(TAG, "No BOOTCLASSPATH found!");
1430            }
1431
1432            boolean didDexOptLibraryOrTool = false;
1433
1434            final List<String> instructionSets = getAllInstructionSets();
1435
1436            /**
1437             * Ensure all external libraries have had dexopt run on them.
1438             */
1439            if (mSharedLibraries.size() > 0) {
1440                // NOTE: For now, we're compiling these system "shared libraries"
1441                // (and framework jars) into all available architectures. It's possible
1442                // to compile them only when we come across an app that uses them (there's
1443                // already logic for that in scanPackageLI) but that adds some complexity.
1444                for (String instructionSet : instructionSets) {
1445                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1446                        final String lib = libEntry.path;
1447                        if (lib == null) {
1448                            continue;
1449                        }
1450
1451                        try {
1452                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1453                                alreadyDexOpted.add(lib);
1454
1455                                // The list of "shared libraries" we have at this point is
1456                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1457                                didDexOptLibraryOrTool = true;
1458                            }
1459                        } catch (FileNotFoundException e) {
1460                            Slog.w(TAG, "Library not found: " + lib);
1461                        } catch (IOException e) {
1462                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1463                                    + e.getMessage());
1464                        }
1465                    }
1466                }
1467            }
1468
1469            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1470
1471            // Gross hack for now: we know this file doesn't contain any
1472            // code, so don't dexopt it to avoid the resulting log spew.
1473            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1474
1475            // Gross hack for now: we know this file is only part of
1476            // the boot class path for art, so don't dexopt it to
1477            // avoid the resulting log spew.
1478            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1479
1480            /**
1481             * And there are a number of commands implemented in Java, which
1482             * we currently need to do the dexopt on so that they can be
1483             * run from a non-root shell.
1484             */
1485            String[] frameworkFiles = frameworkDir.list();
1486            if (frameworkFiles != null) {
1487                // TODO: We could compile these only for the most preferred ABI. We should
1488                // first double check that the dex files for these commands are not referenced
1489                // by other system apps.
1490                for (String instructionSet : instructionSets) {
1491                    for (int i=0; i<frameworkFiles.length; i++) {
1492                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1493                        String path = libPath.getPath();
1494                        // Skip the file if we already did it.
1495                        if (alreadyDexOpted.contains(path)) {
1496                            continue;
1497                        }
1498                        // Skip the file if it is not a type we want to dexopt.
1499                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1500                            continue;
1501                        }
1502                        try {
1503                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1504                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1505                                didDexOptLibraryOrTool = true;
1506                            }
1507                        } catch (FileNotFoundException e) {
1508                            Slog.w(TAG, "Jar not found: " + path);
1509                        } catch (IOException e) {
1510                            Slog.w(TAG, "Exception reading jar: " + path, e);
1511                        }
1512                    }
1513                }
1514            }
1515
1516            if (didDexOptLibraryOrTool) {
1517                // If we dexopted a library or tool, then something on the system has
1518                // changed. Consider this significant, and wipe away all other
1519                // existing dexopt files to ensure we don't leave any dangling around.
1520                //
1521                // TODO: This should be revisited because it isn't as good an indicator
1522                // as it used to be. It used to include the boot classpath but at some point
1523                // DexFile.isDexOptNeeded started returning false for the boot
1524                // class path files in all cases. It is very possible in a
1525                // small maintenance release update that the library and tool
1526                // jars may be unchanged but APK could be removed resulting in
1527                // unused dalvik-cache files.
1528                for (String instructionSet : instructionSets) {
1529                    mInstaller.pruneDexCache(instructionSet);
1530                }
1531
1532                // Additionally, delete all dex files from the root directory
1533                // since there shouldn't be any there anyway, unless we're upgrading
1534                // from an older OS version or a build that contained the "old" style
1535                // flat scheme.
1536                mInstaller.pruneDexCache(".");
1537            }
1538
1539            // Collect vendor overlay packages.
1540            // (Do this before scanning any apps.)
1541            // For security and version matching reason, only consider
1542            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1543            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1544            mVendorOverlayInstallObserver = new AppDirObserver(
1545                    vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1546            mVendorOverlayInstallObserver.startWatching();
1547            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1548                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1549
1550            // Find base frameworks (resource packages without code).
1551            mFrameworkInstallObserver = new AppDirObserver(
1552                    frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1553            mFrameworkInstallObserver.startWatching();
1554            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1555                    | PackageParser.PARSE_IS_SYSTEM_DIR
1556                    | PackageParser.PARSE_IS_PRIVILEGED,
1557                    scanMode | SCAN_NO_DEX, 0);
1558
1559            // Collected privileged system packages.
1560            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1561            mPrivilegedInstallObserver = new AppDirObserver(
1562                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1563            mPrivilegedInstallObserver.startWatching();
1564            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1565                    | PackageParser.PARSE_IS_SYSTEM_DIR
1566                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1567
1568            // Collect ordinary system packages.
1569            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1570            mSystemInstallObserver = new AppDirObserver(
1571                    systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1572            mSystemInstallObserver.startWatching();
1573            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1574                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1575
1576            // Collect all vendor packages.
1577            File vendorAppDir = new File("/vendor/app");
1578            try {
1579                vendorAppDir = vendorAppDir.getCanonicalFile();
1580            } catch (IOException e) {
1581                // failed to look up canonical path, continue with original one
1582            }
1583            mVendorInstallObserver = new AppDirObserver(
1584                    vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1585            mVendorInstallObserver.startWatching();
1586            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1587                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1588
1589            // Collect all OEM packages.
1590            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1591            mOemInstallObserver = new AppDirObserver(
1592                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1593            mOemInstallObserver.startWatching();
1594            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1595                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1596
1597            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1598            mInstaller.moveFiles();
1599
1600            // Prune any system packages that no longer exist.
1601            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1602            if (!mOnlyCore) {
1603                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1604                while (psit.hasNext()) {
1605                    PackageSetting ps = psit.next();
1606
1607                    /*
1608                     * If this is not a system app, it can't be a
1609                     * disable system app.
1610                     */
1611                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1612                        continue;
1613                    }
1614
1615                    /*
1616                     * If the package is scanned, it's not erased.
1617                     */
1618                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1619                    if (scannedPkg != null) {
1620                        /*
1621                         * If the system app is both scanned and in the
1622                         * disabled packages list, then it must have been
1623                         * added via OTA. Remove it from the currently
1624                         * scanned package so the previously user-installed
1625                         * application can be scanned.
1626                         */
1627                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1628                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1629                                    + "; removing system app");
1630                            removePackageLI(ps, true);
1631                        }
1632
1633                        continue;
1634                    }
1635
1636                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1637                        psit.remove();
1638                        String msg = "System package " + ps.name
1639                                + " no longer exists; wiping its data";
1640                        reportSettingsProblem(Log.WARN, msg);
1641                        removeDataDirsLI(ps.name);
1642                    } else {
1643                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1644                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1645                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1646                        }
1647                    }
1648                }
1649            }
1650
1651            //look for any incomplete package installations
1652            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1653            //clean up list
1654            for(int i = 0; i < deletePkgsList.size(); i++) {
1655                //clean up here
1656                cleanupInstallFailedPackage(deletePkgsList.get(i));
1657            }
1658            //delete tmp files
1659            deleteTempPackageFiles();
1660
1661            // Remove any shared userIDs that have no associated packages
1662            mSettings.pruneSharedUsersLPw();
1663
1664            if (!mOnlyCore) {
1665                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1666                        SystemClock.uptimeMillis());
1667                mAppInstallObserver = new AppDirObserver(
1668                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1669                mAppInstallObserver.startWatching();
1670                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1671
1672                mDrmAppInstallObserver = new AppDirObserver(
1673                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1674                mDrmAppInstallObserver.startWatching();
1675                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1676                        scanMode, 0);
1677
1678                /**
1679                 * Remove disable package settings for any updated system
1680                 * apps that were removed via an OTA. If they're not a
1681                 * previously-updated app, remove them completely.
1682                 * Otherwise, just revoke their system-level permissions.
1683                 */
1684                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1685                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1686                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1687
1688                    String msg;
1689                    if (deletedPkg == null) {
1690                        msg = "Updated system package " + deletedAppName
1691                                + " no longer exists; wiping its data";
1692                        removeDataDirsLI(deletedAppName);
1693                    } else {
1694                        msg = "Updated system app + " + deletedAppName
1695                                + " no longer present; removing system privileges for "
1696                                + deletedAppName;
1697
1698                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1699
1700                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1701                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1702                    }
1703                    reportSettingsProblem(Log.WARN, msg);
1704                }
1705            } else {
1706                mAppInstallObserver = null;
1707                mDrmAppInstallObserver = null;
1708            }
1709
1710            // Now that we know all of the shared libraries, update all clients to have
1711            // the correct library paths.
1712            updateAllSharedLibrariesLPw();
1713
1714            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1715                // NOTE: We ignore potential failures here during a system scan (like
1716                // the rest of the commands above) because there's precious little we
1717                // can do about it. A settings error is reported, though.
1718                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1719                        false /* force dexopt */, false /* defer dexopt */);
1720            }
1721
1722            // Now that we know all the packages we are keeping,
1723            // read and update their last usage times.
1724            mPackageUsage.readLP();
1725
1726            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1727                    SystemClock.uptimeMillis());
1728            Slog.i(TAG, "Time to scan packages: "
1729                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1730                    + " seconds");
1731
1732            // If the platform SDK has changed since the last time we booted,
1733            // we need to re-grant app permission to catch any new ones that
1734            // appear.  This is really a hack, and means that apps can in some
1735            // cases get permissions that the user didn't initially explicitly
1736            // allow...  it would be nice to have some better way to handle
1737            // this situation.
1738            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1739                    != mSdkVersion;
1740            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1741                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1742                    + "; regranting permissions for internal storage");
1743            mSettings.mInternalSdkPlatform = mSdkVersion;
1744
1745            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1746                    | (regrantPermissions
1747                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1748                            : 0));
1749
1750            // If this is the first boot, and it is a normal boot, then
1751            // we need to initialize the default preferred apps.
1752            if (!mRestoredSettings && !onlyCore) {
1753                mSettings.readDefaultPreferredAppsLPw(this, 0);
1754            }
1755
1756            // All the changes are done during package scanning.
1757            mSettings.updateInternalDatabaseVersion();
1758
1759            // can downgrade to reader
1760            mSettings.writeLPr();
1761
1762            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1763                    SystemClock.uptimeMillis());
1764
1765
1766            mRequiredVerifierPackage = getRequiredVerifierLPr();
1767        } // synchronized (mPackages)
1768        } // synchronized (mInstallLock)
1769
1770        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1771
1772        // Now after opening every single application zip, make sure they
1773        // are all flushed.  Not really needed, but keeps things nice and
1774        // tidy.
1775        Runtime.getRuntime().gc();
1776    }
1777
1778    @Override
1779    public boolean isFirstBoot() {
1780        return !mRestoredSettings;
1781    }
1782
1783    @Override
1784    public boolean isOnlyCoreApps() {
1785        return mOnlyCore;
1786    }
1787
1788    private String getRequiredVerifierLPr() {
1789        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1790        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1791                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1792
1793        String requiredVerifier = null;
1794
1795        final int N = receivers.size();
1796        for (int i = 0; i < N; i++) {
1797            final ResolveInfo info = receivers.get(i);
1798
1799            if (info.activityInfo == null) {
1800                continue;
1801            }
1802
1803            final String packageName = info.activityInfo.packageName;
1804
1805            final PackageSetting ps = mSettings.mPackages.get(packageName);
1806            if (ps == null) {
1807                continue;
1808            }
1809
1810            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1811            if (!gp.grantedPermissions
1812                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1813                continue;
1814            }
1815
1816            if (requiredVerifier != null) {
1817                throw new RuntimeException("There can be only one required verifier");
1818            }
1819
1820            requiredVerifier = packageName;
1821        }
1822
1823        return requiredVerifier;
1824    }
1825
1826    @Override
1827    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1828            throws RemoteException {
1829        try {
1830            return super.onTransact(code, data, reply, flags);
1831        } catch (RuntimeException e) {
1832            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1833                Slog.wtf(TAG, "Package Manager Crash", e);
1834            }
1835            throw e;
1836        }
1837    }
1838
1839    void cleanupInstallFailedPackage(PackageSetting ps) {
1840        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1841        removeDataDirsLI(ps.name);
1842
1843        // TODO: try cleaning up codePath directory contents first, since it
1844        // might be a cluster
1845
1846        if (ps.codePath != null) {
1847            if (!ps.codePath.delete()) {
1848                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1849            }
1850        }
1851        if (ps.resourcePath != null) {
1852            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1853                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1854            }
1855        }
1856        mSettings.removePackageLPw(ps.name);
1857    }
1858
1859    static int[] appendInts(int[] cur, int[] add) {
1860        if (add == null) return cur;
1861        if (cur == null) return add;
1862        final int N = add.length;
1863        for (int i=0; i<N; i++) {
1864            cur = appendInt(cur, add[i]);
1865        }
1866        return cur;
1867    }
1868
1869    static int[] removeInts(int[] cur, int[] rem) {
1870        if (rem == null) return cur;
1871        if (cur == null) return cur;
1872        final int N = rem.length;
1873        for (int i=0; i<N; i++) {
1874            cur = removeInt(cur, rem[i]);
1875        }
1876        return cur;
1877    }
1878
1879    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1880        if (!sUserManager.exists(userId)) return null;
1881        final PackageSetting ps = (PackageSetting) p.mExtras;
1882        if (ps == null) {
1883            return null;
1884        }
1885        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1886        final PackageUserState state = ps.readUserState(userId);
1887        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1888                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1889                state, userId);
1890    }
1891
1892    @Override
1893    public boolean isPackageAvailable(String packageName, int userId) {
1894        if (!sUserManager.exists(userId)) return false;
1895        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1896        synchronized (mPackages) {
1897            PackageParser.Package p = mPackages.get(packageName);
1898            if (p != null) {
1899                final PackageSetting ps = (PackageSetting) p.mExtras;
1900                if (ps != null) {
1901                    final PackageUserState state = ps.readUserState(userId);
1902                    if (state != null) {
1903                        return PackageParser.isAvailable(state);
1904                    }
1905                }
1906            }
1907        }
1908        return false;
1909    }
1910
1911    @Override
1912    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1913        if (!sUserManager.exists(userId)) return null;
1914        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1915        // reader
1916        synchronized (mPackages) {
1917            PackageParser.Package p = mPackages.get(packageName);
1918            if (DEBUG_PACKAGE_INFO)
1919                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1920            if (p != null) {
1921                return generatePackageInfo(p, flags, userId);
1922            }
1923            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1924                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1925            }
1926        }
1927        return null;
1928    }
1929
1930    @Override
1931    public String[] currentToCanonicalPackageNames(String[] names) {
1932        String[] out = new String[names.length];
1933        // reader
1934        synchronized (mPackages) {
1935            for (int i=names.length-1; i>=0; i--) {
1936                PackageSetting ps = mSettings.mPackages.get(names[i]);
1937                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1938            }
1939        }
1940        return out;
1941    }
1942
1943    @Override
1944    public String[] canonicalToCurrentPackageNames(String[] names) {
1945        String[] out = new String[names.length];
1946        // reader
1947        synchronized (mPackages) {
1948            for (int i=names.length-1; i>=0; i--) {
1949                String cur = mSettings.mRenamedPackages.get(names[i]);
1950                out[i] = cur != null ? cur : names[i];
1951            }
1952        }
1953        return out;
1954    }
1955
1956    @Override
1957    public int getPackageUid(String packageName, int userId) {
1958        if (!sUserManager.exists(userId)) return -1;
1959        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1960        // reader
1961        synchronized (mPackages) {
1962            PackageParser.Package p = mPackages.get(packageName);
1963            if(p != null) {
1964                return UserHandle.getUid(userId, p.applicationInfo.uid);
1965            }
1966            PackageSetting ps = mSettings.mPackages.get(packageName);
1967            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1968                return -1;
1969            }
1970            p = ps.pkg;
1971            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1972        }
1973    }
1974
1975    @Override
1976    public int[] getPackageGids(String packageName) {
1977        // reader
1978        synchronized (mPackages) {
1979            PackageParser.Package p = mPackages.get(packageName);
1980            if (DEBUG_PACKAGE_INFO)
1981                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1982            if (p != null) {
1983                final PackageSetting ps = (PackageSetting)p.mExtras;
1984                return ps.getGids();
1985            }
1986        }
1987        // stupid thing to indicate an error.
1988        return new int[0];
1989    }
1990
1991    static final PermissionInfo generatePermissionInfo(
1992            BasePermission bp, int flags) {
1993        if (bp.perm != null) {
1994            return PackageParser.generatePermissionInfo(bp.perm, flags);
1995        }
1996        PermissionInfo pi = new PermissionInfo();
1997        pi.name = bp.name;
1998        pi.packageName = bp.sourcePackage;
1999        pi.nonLocalizedLabel = bp.name;
2000        pi.protectionLevel = bp.protectionLevel;
2001        return pi;
2002    }
2003
2004    @Override
2005    public PermissionInfo getPermissionInfo(String name, int flags) {
2006        // reader
2007        synchronized (mPackages) {
2008            final BasePermission p = mSettings.mPermissions.get(name);
2009            if (p != null) {
2010                return generatePermissionInfo(p, flags);
2011            }
2012            return null;
2013        }
2014    }
2015
2016    @Override
2017    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2018        // reader
2019        synchronized (mPackages) {
2020            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2021            for (BasePermission p : mSettings.mPermissions.values()) {
2022                if (group == null) {
2023                    if (p.perm == null || p.perm.info.group == null) {
2024                        out.add(generatePermissionInfo(p, flags));
2025                    }
2026                } else {
2027                    if (p.perm != null && group.equals(p.perm.info.group)) {
2028                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2029                    }
2030                }
2031            }
2032
2033            if (out.size() > 0) {
2034                return out;
2035            }
2036            return mPermissionGroups.containsKey(group) ? out : null;
2037        }
2038    }
2039
2040    @Override
2041    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2042        // reader
2043        synchronized (mPackages) {
2044            return PackageParser.generatePermissionGroupInfo(
2045                    mPermissionGroups.get(name), flags);
2046        }
2047    }
2048
2049    @Override
2050    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2051        // reader
2052        synchronized (mPackages) {
2053            final int N = mPermissionGroups.size();
2054            ArrayList<PermissionGroupInfo> out
2055                    = new ArrayList<PermissionGroupInfo>(N);
2056            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2057                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2058            }
2059            return out;
2060        }
2061    }
2062
2063    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2064            int userId) {
2065        if (!sUserManager.exists(userId)) return null;
2066        PackageSetting ps = mSettings.mPackages.get(packageName);
2067        if (ps != null) {
2068            if (ps.pkg == null) {
2069                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2070                        flags, userId);
2071                if (pInfo != null) {
2072                    return pInfo.applicationInfo;
2073                }
2074                return null;
2075            }
2076            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2077                    ps.readUserState(userId), userId);
2078        }
2079        return null;
2080    }
2081
2082    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2083            int userId) {
2084        if (!sUserManager.exists(userId)) return null;
2085        PackageSetting ps = mSettings.mPackages.get(packageName);
2086        if (ps != null) {
2087            PackageParser.Package pkg = ps.pkg;
2088            if (pkg == null) {
2089                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2090                    return null;
2091                }
2092                // Only data remains, so we aren't worried about code paths
2093                pkg = new PackageParser.Package(packageName);
2094                pkg.applicationInfo.packageName = packageName;
2095                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2096                pkg.applicationInfo.dataDir =
2097                        getDataPathForPackage(packageName, 0).getPath();
2098                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2099            }
2100            return generatePackageInfo(pkg, flags, userId);
2101        }
2102        return null;
2103    }
2104
2105    @Override
2106    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2107        if (!sUserManager.exists(userId)) return null;
2108        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2109        // writer
2110        synchronized (mPackages) {
2111            PackageParser.Package p = mPackages.get(packageName);
2112            if (DEBUG_PACKAGE_INFO) Log.v(
2113                    TAG, "getApplicationInfo " + packageName
2114                    + ": " + p);
2115            if (p != null) {
2116                PackageSetting ps = mSettings.mPackages.get(packageName);
2117                if (ps == null) return null;
2118                // Note: isEnabledLP() does not apply here - always return info
2119                return PackageParser.generateApplicationInfo(
2120                        p, flags, ps.readUserState(userId), userId);
2121            }
2122            if ("android".equals(packageName)||"system".equals(packageName)) {
2123                return mAndroidApplication;
2124            }
2125            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2126                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2127            }
2128        }
2129        return null;
2130    }
2131
2132
2133    @Override
2134    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2135        mContext.enforceCallingOrSelfPermission(
2136                android.Manifest.permission.CLEAR_APP_CACHE, null);
2137        // Queue up an async operation since clearing cache may take a little while.
2138        mHandler.post(new Runnable() {
2139            public void run() {
2140                mHandler.removeCallbacks(this);
2141                int retCode = -1;
2142                synchronized (mInstallLock) {
2143                    retCode = mInstaller.freeCache(freeStorageSize);
2144                    if (retCode < 0) {
2145                        Slog.w(TAG, "Couldn't clear application caches");
2146                    }
2147                }
2148                if (observer != null) {
2149                    try {
2150                        observer.onRemoveCompleted(null, (retCode >= 0));
2151                    } catch (RemoteException e) {
2152                        Slog.w(TAG, "RemoveException when invoking call back");
2153                    }
2154                }
2155            }
2156        });
2157    }
2158
2159    @Override
2160    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2161        mContext.enforceCallingOrSelfPermission(
2162                android.Manifest.permission.CLEAR_APP_CACHE, null);
2163        // Queue up an async operation since clearing cache may take a little while.
2164        mHandler.post(new Runnable() {
2165            public void run() {
2166                mHandler.removeCallbacks(this);
2167                int retCode = -1;
2168                synchronized (mInstallLock) {
2169                    retCode = mInstaller.freeCache(freeStorageSize);
2170                    if (retCode < 0) {
2171                        Slog.w(TAG, "Couldn't clear application caches");
2172                    }
2173                }
2174                if(pi != null) {
2175                    try {
2176                        // Callback via pending intent
2177                        int code = (retCode >= 0) ? 1 : 0;
2178                        pi.sendIntent(null, code, null,
2179                                null, null);
2180                    } catch (SendIntentException e1) {
2181                        Slog.i(TAG, "Failed to send pending intent");
2182                    }
2183                }
2184            }
2185        });
2186    }
2187
2188    void freeStorage(long freeStorageSize) throws IOException {
2189        synchronized (mInstallLock) {
2190            if (mInstaller.freeCache(freeStorageSize) < 0) {
2191                throw new IOException("Failed to free enough space");
2192            }
2193        }
2194    }
2195
2196    @Override
2197    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2198        if (!sUserManager.exists(userId)) return null;
2199        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2200        synchronized (mPackages) {
2201            PackageParser.Activity a = mActivities.mActivities.get(component);
2202
2203            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2204            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2205                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2206                if (ps == null) return null;
2207                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2208                        userId);
2209            }
2210            if (mResolveComponentName.equals(component)) {
2211                return mResolveActivity;
2212            }
2213        }
2214        return null;
2215    }
2216
2217    @Override
2218    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2219            String resolvedType) {
2220        synchronized (mPackages) {
2221            PackageParser.Activity a = mActivities.mActivities.get(component);
2222            if (a == null) {
2223                return false;
2224            }
2225            for (int i=0; i<a.intents.size(); i++) {
2226                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2227                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2228                    return true;
2229                }
2230            }
2231            return false;
2232        }
2233    }
2234
2235    @Override
2236    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2237        if (!sUserManager.exists(userId)) return null;
2238        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2239        synchronized (mPackages) {
2240            PackageParser.Activity a = mReceivers.mActivities.get(component);
2241            if (DEBUG_PACKAGE_INFO) Log.v(
2242                TAG, "getReceiverInfo " + component + ": " + a);
2243            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2244                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2245                if (ps == null) return null;
2246                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2247                        userId);
2248            }
2249        }
2250        return null;
2251    }
2252
2253    @Override
2254    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2255        if (!sUserManager.exists(userId)) return null;
2256        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2257        synchronized (mPackages) {
2258            PackageParser.Service s = mServices.mServices.get(component);
2259            if (DEBUG_PACKAGE_INFO) Log.v(
2260                TAG, "getServiceInfo " + component + ": " + s);
2261            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2262                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2263                if (ps == null) return null;
2264                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2265                        userId);
2266            }
2267        }
2268        return null;
2269    }
2270
2271    @Override
2272    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2273        if (!sUserManager.exists(userId)) return null;
2274        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2275        synchronized (mPackages) {
2276            PackageParser.Provider p = mProviders.mProviders.get(component);
2277            if (DEBUG_PACKAGE_INFO) Log.v(
2278                TAG, "getProviderInfo " + component + ": " + p);
2279            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2280                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2281                if (ps == null) return null;
2282                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2283                        userId);
2284            }
2285        }
2286        return null;
2287    }
2288
2289    @Override
2290    public String[] getSystemSharedLibraryNames() {
2291        Set<String> libSet;
2292        synchronized (mPackages) {
2293            libSet = mSharedLibraries.keySet();
2294            int size = libSet.size();
2295            if (size > 0) {
2296                String[] libs = new String[size];
2297                libSet.toArray(libs);
2298                return libs;
2299            }
2300        }
2301        return null;
2302    }
2303
2304    @Override
2305    public FeatureInfo[] getSystemAvailableFeatures() {
2306        Collection<FeatureInfo> featSet;
2307        synchronized (mPackages) {
2308            featSet = mAvailableFeatures.values();
2309            int size = featSet.size();
2310            if (size > 0) {
2311                FeatureInfo[] features = new FeatureInfo[size+1];
2312                featSet.toArray(features);
2313                FeatureInfo fi = new FeatureInfo();
2314                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2315                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2316                features[size] = fi;
2317                return features;
2318            }
2319        }
2320        return null;
2321    }
2322
2323    @Override
2324    public boolean hasSystemFeature(String name) {
2325        synchronized (mPackages) {
2326            return mAvailableFeatures.containsKey(name);
2327        }
2328    }
2329
2330    private void checkValidCaller(int uid, int userId) {
2331        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2332            return;
2333
2334        throw new SecurityException("Caller uid=" + uid
2335                + " is not privileged to communicate with user=" + userId);
2336    }
2337
2338    @Override
2339    public int checkPermission(String permName, String pkgName) {
2340        synchronized (mPackages) {
2341            PackageParser.Package p = mPackages.get(pkgName);
2342            if (p != null && p.mExtras != null) {
2343                PackageSetting ps = (PackageSetting)p.mExtras;
2344                if (ps.sharedUser != null) {
2345                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2346                        return PackageManager.PERMISSION_GRANTED;
2347                    }
2348                } else if (ps.grantedPermissions.contains(permName)) {
2349                    return PackageManager.PERMISSION_GRANTED;
2350                }
2351            }
2352        }
2353        return PackageManager.PERMISSION_DENIED;
2354    }
2355
2356    @Override
2357    public int checkUidPermission(String permName, int uid) {
2358        synchronized (mPackages) {
2359            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2360            if (obj != null) {
2361                GrantedPermissions gp = (GrantedPermissions)obj;
2362                if (gp.grantedPermissions.contains(permName)) {
2363                    return PackageManager.PERMISSION_GRANTED;
2364                }
2365            } else {
2366                HashSet<String> perms = mSystemPermissions.get(uid);
2367                if (perms != null && perms.contains(permName)) {
2368                    return PackageManager.PERMISSION_GRANTED;
2369                }
2370            }
2371        }
2372        return PackageManager.PERMISSION_DENIED;
2373    }
2374
2375    /**
2376     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2377     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2378     * @param message the message to log on security exception
2379     */
2380    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2381            String message) {
2382        if (userId < 0) {
2383            throw new IllegalArgumentException("Invalid userId " + userId);
2384        }
2385        if (userId == UserHandle.getUserId(callingUid)) return;
2386        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2387            if (requireFullPermission) {
2388                mContext.enforceCallingOrSelfPermission(
2389                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2390            } else {
2391                try {
2392                    mContext.enforceCallingOrSelfPermission(
2393                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2394                } catch (SecurityException se) {
2395                    mContext.enforceCallingOrSelfPermission(
2396                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2397                }
2398            }
2399        }
2400    }
2401
2402    private BasePermission findPermissionTreeLP(String permName) {
2403        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2404            if (permName.startsWith(bp.name) &&
2405                    permName.length() > bp.name.length() &&
2406                    permName.charAt(bp.name.length()) == '.') {
2407                return bp;
2408            }
2409        }
2410        return null;
2411    }
2412
2413    private BasePermission checkPermissionTreeLP(String permName) {
2414        if (permName != null) {
2415            BasePermission bp = findPermissionTreeLP(permName);
2416            if (bp != null) {
2417                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2418                    return bp;
2419                }
2420                throw new SecurityException("Calling uid "
2421                        + Binder.getCallingUid()
2422                        + " is not allowed to add to permission tree "
2423                        + bp.name + " owned by uid " + bp.uid);
2424            }
2425        }
2426        throw new SecurityException("No permission tree found for " + permName);
2427    }
2428
2429    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2430        if (s1 == null) {
2431            return s2 == null;
2432        }
2433        if (s2 == null) {
2434            return false;
2435        }
2436        if (s1.getClass() != s2.getClass()) {
2437            return false;
2438        }
2439        return s1.equals(s2);
2440    }
2441
2442    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2443        if (pi1.icon != pi2.icon) return false;
2444        if (pi1.logo != pi2.logo) return false;
2445        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2446        if (!compareStrings(pi1.name, pi2.name)) return false;
2447        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2448        // We'll take care of setting this one.
2449        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2450        // These are not currently stored in settings.
2451        //if (!compareStrings(pi1.group, pi2.group)) return false;
2452        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2453        //if (pi1.labelRes != pi2.labelRes) return false;
2454        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2455        return true;
2456    }
2457
2458    int permissionInfoFootprint(PermissionInfo info) {
2459        int size = info.name.length();
2460        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2461        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2462        return size;
2463    }
2464
2465    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2466        int size = 0;
2467        for (BasePermission perm : mSettings.mPermissions.values()) {
2468            if (perm.uid == tree.uid) {
2469                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2470            }
2471        }
2472        return size;
2473    }
2474
2475    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2476        // We calculate the max size of permissions defined by this uid and throw
2477        // if that plus the size of 'info' would exceed our stated maximum.
2478        if (tree.uid != Process.SYSTEM_UID) {
2479            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2480            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2481                throw new SecurityException("Permission tree size cap exceeded");
2482            }
2483        }
2484    }
2485
2486    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2487        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2488            throw new SecurityException("Label must be specified in permission");
2489        }
2490        BasePermission tree = checkPermissionTreeLP(info.name);
2491        BasePermission bp = mSettings.mPermissions.get(info.name);
2492        boolean added = bp == null;
2493        boolean changed = true;
2494        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2495        if (added) {
2496            enforcePermissionCapLocked(info, tree);
2497            bp = new BasePermission(info.name, tree.sourcePackage,
2498                    BasePermission.TYPE_DYNAMIC);
2499        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2500            throw new SecurityException(
2501                    "Not allowed to modify non-dynamic permission "
2502                    + info.name);
2503        } else {
2504            if (bp.protectionLevel == fixedLevel
2505                    && bp.perm.owner.equals(tree.perm.owner)
2506                    && bp.uid == tree.uid
2507                    && comparePermissionInfos(bp.perm.info, info)) {
2508                changed = false;
2509            }
2510        }
2511        bp.protectionLevel = fixedLevel;
2512        info = new PermissionInfo(info);
2513        info.protectionLevel = fixedLevel;
2514        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2515        bp.perm.info.packageName = tree.perm.info.packageName;
2516        bp.uid = tree.uid;
2517        if (added) {
2518            mSettings.mPermissions.put(info.name, bp);
2519        }
2520        if (changed) {
2521            if (!async) {
2522                mSettings.writeLPr();
2523            } else {
2524                scheduleWriteSettingsLocked();
2525            }
2526        }
2527        return added;
2528    }
2529
2530    @Override
2531    public boolean addPermission(PermissionInfo info) {
2532        synchronized (mPackages) {
2533            return addPermissionLocked(info, false);
2534        }
2535    }
2536
2537    @Override
2538    public boolean addPermissionAsync(PermissionInfo info) {
2539        synchronized (mPackages) {
2540            return addPermissionLocked(info, true);
2541        }
2542    }
2543
2544    @Override
2545    public void removePermission(String name) {
2546        synchronized (mPackages) {
2547            checkPermissionTreeLP(name);
2548            BasePermission bp = mSettings.mPermissions.get(name);
2549            if (bp != null) {
2550                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2551                    throw new SecurityException(
2552                            "Not allowed to modify non-dynamic permission "
2553                            + name);
2554                }
2555                mSettings.mPermissions.remove(name);
2556                mSettings.writeLPr();
2557            }
2558        }
2559    }
2560
2561    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2562        int index = pkg.requestedPermissions.indexOf(bp.name);
2563        if (index == -1) {
2564            throw new SecurityException("Package " + pkg.packageName
2565                    + " has not requested permission " + bp.name);
2566        }
2567        boolean isNormal =
2568                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2569                        == PermissionInfo.PROTECTION_NORMAL);
2570        boolean isDangerous =
2571                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2572                        == PermissionInfo.PROTECTION_DANGEROUS);
2573        boolean isDevelopment =
2574                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2575
2576        if (!isNormal && !isDangerous && !isDevelopment) {
2577            throw new SecurityException("Permission " + bp.name
2578                    + " is not a changeable permission type");
2579        }
2580
2581        if (isNormal || isDangerous) {
2582            if (pkg.requestedPermissionsRequired.get(index)) {
2583                throw new SecurityException("Can't change " + bp.name
2584                        + ". It is required by the application");
2585            }
2586        }
2587    }
2588
2589    @Override
2590    public void grantPermission(String packageName, String permissionName) {
2591        mContext.enforceCallingOrSelfPermission(
2592                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2593        synchronized (mPackages) {
2594            final PackageParser.Package pkg = mPackages.get(packageName);
2595            if (pkg == null) {
2596                throw new IllegalArgumentException("Unknown package: " + packageName);
2597            }
2598            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2599            if (bp == null) {
2600                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2601            }
2602
2603            checkGrantRevokePermissions(pkg, bp);
2604
2605            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2606            if (ps == null) {
2607                return;
2608            }
2609            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2610            if (gp.grantedPermissions.add(permissionName)) {
2611                if (ps.haveGids) {
2612                    gp.gids = appendInts(gp.gids, bp.gids);
2613                }
2614                mSettings.writeLPr();
2615            }
2616        }
2617    }
2618
2619    @Override
2620    public void revokePermission(String packageName, String permissionName) {
2621        int changedAppId = -1;
2622
2623        synchronized (mPackages) {
2624            final PackageParser.Package pkg = mPackages.get(packageName);
2625            if (pkg == null) {
2626                throw new IllegalArgumentException("Unknown package: " + packageName);
2627            }
2628            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2629                mContext.enforceCallingOrSelfPermission(
2630                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2631            }
2632            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2633            if (bp == null) {
2634                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2635            }
2636
2637            checkGrantRevokePermissions(pkg, bp);
2638
2639            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2640            if (ps == null) {
2641                return;
2642            }
2643            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2644            if (gp.grantedPermissions.remove(permissionName)) {
2645                gp.grantedPermissions.remove(permissionName);
2646                if (ps.haveGids) {
2647                    gp.gids = removeInts(gp.gids, bp.gids);
2648                }
2649                mSettings.writeLPr();
2650                changedAppId = ps.appId;
2651            }
2652        }
2653
2654        if (changedAppId >= 0) {
2655            // We changed the perm on someone, kill its processes.
2656            IActivityManager am = ActivityManagerNative.getDefault();
2657            if (am != null) {
2658                final int callingUserId = UserHandle.getCallingUserId();
2659                final long ident = Binder.clearCallingIdentity();
2660                try {
2661                    //XXX we should only revoke for the calling user's app permissions,
2662                    // but for now we impact all users.
2663                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2664                    //        "revoke " + permissionName);
2665                    int[] users = sUserManager.getUserIds();
2666                    for (int user : users) {
2667                        am.killUid(UserHandle.getUid(user, changedAppId),
2668                                "revoke " + permissionName);
2669                    }
2670                } catch (RemoteException e) {
2671                } finally {
2672                    Binder.restoreCallingIdentity(ident);
2673                }
2674            }
2675        }
2676    }
2677
2678    @Override
2679    public boolean isProtectedBroadcast(String actionName) {
2680        synchronized (mPackages) {
2681            return mProtectedBroadcasts.contains(actionName);
2682        }
2683    }
2684
2685    @Override
2686    public int checkSignatures(String pkg1, String pkg2) {
2687        synchronized (mPackages) {
2688            final PackageParser.Package p1 = mPackages.get(pkg1);
2689            final PackageParser.Package p2 = mPackages.get(pkg2);
2690            if (p1 == null || p1.mExtras == null
2691                    || p2 == null || p2.mExtras == null) {
2692                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2693            }
2694            return compareSignatures(p1.mSignatures, p2.mSignatures);
2695        }
2696    }
2697
2698    @Override
2699    public int checkUidSignatures(int uid1, int uid2) {
2700        // Map to base uids.
2701        uid1 = UserHandle.getAppId(uid1);
2702        uid2 = UserHandle.getAppId(uid2);
2703        // reader
2704        synchronized (mPackages) {
2705            Signature[] s1;
2706            Signature[] s2;
2707            Object obj = mSettings.getUserIdLPr(uid1);
2708            if (obj != null) {
2709                if (obj instanceof SharedUserSetting) {
2710                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2711                } else if (obj instanceof PackageSetting) {
2712                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2713                } else {
2714                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2715                }
2716            } else {
2717                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2718            }
2719            obj = mSettings.getUserIdLPr(uid2);
2720            if (obj != null) {
2721                if (obj instanceof SharedUserSetting) {
2722                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2723                } else if (obj instanceof PackageSetting) {
2724                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2725                } else {
2726                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2727                }
2728            } else {
2729                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2730            }
2731            return compareSignatures(s1, s2);
2732        }
2733    }
2734
2735    /**
2736     * Compares two sets of signatures. Returns:
2737     * <br />
2738     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2739     * <br />
2740     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2741     * <br />
2742     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2743     * <br />
2744     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2745     * <br />
2746     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2747     */
2748    static int compareSignatures(Signature[] s1, Signature[] s2) {
2749        if (s1 == null) {
2750            return s2 == null
2751                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2752                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2753        }
2754
2755        if (s2 == null) {
2756            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2757        }
2758
2759        if (s1.length != s2.length) {
2760            return PackageManager.SIGNATURE_NO_MATCH;
2761        }
2762
2763        // Since both signature sets are of size 1, we can compare without HashSets.
2764        if (s1.length == 1) {
2765            return s1[0].equals(s2[0]) ?
2766                    PackageManager.SIGNATURE_MATCH :
2767                    PackageManager.SIGNATURE_NO_MATCH;
2768        }
2769
2770        HashSet<Signature> set1 = new HashSet<Signature>();
2771        for (Signature sig : s1) {
2772            set1.add(sig);
2773        }
2774        HashSet<Signature> set2 = new HashSet<Signature>();
2775        for (Signature sig : s2) {
2776            set2.add(sig);
2777        }
2778        // Make sure s2 contains all signatures in s1.
2779        if (set1.equals(set2)) {
2780            return PackageManager.SIGNATURE_MATCH;
2781        }
2782        return PackageManager.SIGNATURE_NO_MATCH;
2783    }
2784
2785    /**
2786     * If the database version for this type of package (internal storage or
2787     * external storage) is less than the version where package signatures
2788     * were updated, return true.
2789     */
2790    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2791        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2792                DatabaseVersion.SIGNATURE_END_ENTITY))
2793                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2794                        DatabaseVersion.SIGNATURE_END_ENTITY));
2795    }
2796
2797    /**
2798     * Used for backward compatibility to make sure any packages with
2799     * certificate chains get upgraded to the new style. {@code existingSigs}
2800     * will be in the old format (since they were stored on disk from before the
2801     * system upgrade) and {@code scannedSigs} will be in the newer format.
2802     */
2803    private int compareSignaturesCompat(PackageSignatures existingSigs,
2804            PackageParser.Package scannedPkg) {
2805        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2806            return PackageManager.SIGNATURE_NO_MATCH;
2807        }
2808
2809        HashSet<Signature> existingSet = new HashSet<Signature>();
2810        for (Signature sig : existingSigs.mSignatures) {
2811            existingSet.add(sig);
2812        }
2813        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2814        for (Signature sig : scannedPkg.mSignatures) {
2815            try {
2816                Signature[] chainSignatures = sig.getChainSignatures();
2817                for (Signature chainSig : chainSignatures) {
2818                    scannedCompatSet.add(chainSig);
2819                }
2820            } catch (CertificateEncodingException e) {
2821                scannedCompatSet.add(sig);
2822            }
2823        }
2824        /*
2825         * Make sure the expanded scanned set contains all signatures in the
2826         * existing one.
2827         */
2828        if (scannedCompatSet.equals(existingSet)) {
2829            // Migrate the old signatures to the new scheme.
2830            existingSigs.assignSignatures(scannedPkg.mSignatures);
2831            // The new KeySets will be re-added later in the scanning process.
2832            mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName);
2833            return PackageManager.SIGNATURE_MATCH;
2834        }
2835        return PackageManager.SIGNATURE_NO_MATCH;
2836    }
2837
2838    @Override
2839    public String[] getPackagesForUid(int uid) {
2840        uid = UserHandle.getAppId(uid);
2841        // reader
2842        synchronized (mPackages) {
2843            Object obj = mSettings.getUserIdLPr(uid);
2844            if (obj instanceof SharedUserSetting) {
2845                final SharedUserSetting sus = (SharedUserSetting) obj;
2846                final int N = sus.packages.size();
2847                final String[] res = new String[N];
2848                final Iterator<PackageSetting> it = sus.packages.iterator();
2849                int i = 0;
2850                while (it.hasNext()) {
2851                    res[i++] = it.next().name;
2852                }
2853                return res;
2854            } else if (obj instanceof PackageSetting) {
2855                final PackageSetting ps = (PackageSetting) obj;
2856                return new String[] { ps.name };
2857            }
2858        }
2859        return null;
2860    }
2861
2862    @Override
2863    public String getNameForUid(int uid) {
2864        // reader
2865        synchronized (mPackages) {
2866            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2867            if (obj instanceof SharedUserSetting) {
2868                final SharedUserSetting sus = (SharedUserSetting) obj;
2869                return sus.name + ":" + sus.userId;
2870            } else if (obj instanceof PackageSetting) {
2871                final PackageSetting ps = (PackageSetting) obj;
2872                return ps.name;
2873            }
2874        }
2875        return null;
2876    }
2877
2878    @Override
2879    public int getUidForSharedUser(String sharedUserName) {
2880        if(sharedUserName == null) {
2881            return -1;
2882        }
2883        // reader
2884        synchronized (mPackages) {
2885            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2886            if (suid == null) {
2887                return -1;
2888            }
2889            return suid.userId;
2890        }
2891    }
2892
2893    @Override
2894    public int getFlagsForUid(int uid) {
2895        synchronized (mPackages) {
2896            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2897            if (obj instanceof SharedUserSetting) {
2898                final SharedUserSetting sus = (SharedUserSetting) obj;
2899                return sus.pkgFlags;
2900            } else if (obj instanceof PackageSetting) {
2901                final PackageSetting ps = (PackageSetting) obj;
2902                return ps.pkgFlags;
2903            }
2904        }
2905        return 0;
2906    }
2907
2908    @Override
2909    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2910            int flags, int userId) {
2911        if (!sUserManager.exists(userId)) return null;
2912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2913        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2914        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2915    }
2916
2917    @Override
2918    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2919            IntentFilter filter, int match, ComponentName activity) {
2920        final int userId = UserHandle.getCallingUserId();
2921        if (DEBUG_PREFERRED) {
2922            Log.v(TAG, "setLastChosenActivity intent=" + intent
2923                + " resolvedType=" + resolvedType
2924                + " flags=" + flags
2925                + " filter=" + filter
2926                + " match=" + match
2927                + " activity=" + activity);
2928            filter.dump(new PrintStreamPrinter(System.out), "    ");
2929        }
2930        intent.setComponent(null);
2931        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2932        // Find any earlier preferred or last chosen entries and nuke them
2933        findPreferredActivity(intent, resolvedType,
2934                flags, query, 0, false, true, false, userId);
2935        // Add the new activity as the last chosen for this filter
2936        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2937    }
2938
2939    @Override
2940    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2941        final int userId = UserHandle.getCallingUserId();
2942        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2943        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2944        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2945                false, false, false, userId);
2946    }
2947
2948    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2949            int flags, List<ResolveInfo> query, int userId) {
2950        if (query != null) {
2951            final int N = query.size();
2952            if (N == 1) {
2953                return query.get(0);
2954            } else if (N > 1) {
2955                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2956                // If there is more than one activity with the same priority,
2957                // then let the user decide between them.
2958                ResolveInfo r0 = query.get(0);
2959                ResolveInfo r1 = query.get(1);
2960                if (DEBUG_INTENT_MATCHING || debug) {
2961                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2962                            + r1.activityInfo.name + "=" + r1.priority);
2963                }
2964                // If the first activity has a higher priority, or a different
2965                // default, then it is always desireable to pick it.
2966                if (r0.priority != r1.priority
2967                        || r0.preferredOrder != r1.preferredOrder
2968                        || r0.isDefault != r1.isDefault) {
2969                    return query.get(0);
2970                }
2971                // If we have saved a preference for a preferred activity for
2972                // this Intent, use that.
2973                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2974                        flags, query, r0.priority, true, false, debug, userId);
2975                if (ri != null) {
2976                    return ri;
2977                }
2978                if (userId != 0) {
2979                    ri = new ResolveInfo(mResolveInfo);
2980                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2981                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2982                            ri.activityInfo.applicationInfo);
2983                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2984                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2985                    return ri;
2986                }
2987                return mResolveInfo;
2988            }
2989        }
2990        return null;
2991    }
2992
2993    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2994            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2995        final int N = query.size();
2996        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2997                .get(userId);
2998        // Get the list of persistent preferred activities that handle the intent
2999        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3000        List<PersistentPreferredActivity> pprefs = ppir != null
3001                ? ppir.queryIntent(intent, resolvedType,
3002                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3003                : null;
3004        if (pprefs != null && pprefs.size() > 0) {
3005            final int M = pprefs.size();
3006            for (int i=0; i<M; i++) {
3007                final PersistentPreferredActivity ppa = pprefs.get(i);
3008                if (DEBUG_PREFERRED || debug) {
3009                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3010                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3011                            + "\n  component=" + ppa.mComponent);
3012                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3013                }
3014                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3015                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3016                if (DEBUG_PREFERRED || debug) {
3017                    Slog.v(TAG, "Found persistent preferred activity:");
3018                    if (ai != null) {
3019                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3020                    } else {
3021                        Slog.v(TAG, "  null");
3022                    }
3023                }
3024                if (ai == null) {
3025                    // This previously registered persistent preferred activity
3026                    // component is no longer known. Ignore it and do NOT remove it.
3027                    continue;
3028                }
3029                for (int j=0; j<N; j++) {
3030                    final ResolveInfo ri = query.get(j);
3031                    if (!ri.activityInfo.applicationInfo.packageName
3032                            .equals(ai.applicationInfo.packageName)) {
3033                        continue;
3034                    }
3035                    if (!ri.activityInfo.name.equals(ai.name)) {
3036                        continue;
3037                    }
3038                    //  Found a persistent preference that can handle the intent.
3039                    if (DEBUG_PREFERRED || debug) {
3040                        Slog.v(TAG, "Returning persistent preferred activity: " +
3041                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3042                    }
3043                    return ri;
3044                }
3045            }
3046        }
3047        return null;
3048    }
3049
3050    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3051            List<ResolveInfo> query, int priority, boolean always,
3052            boolean removeMatches, boolean debug, int userId) {
3053        if (!sUserManager.exists(userId)) return null;
3054        // writer
3055        synchronized (mPackages) {
3056            if (intent.getSelector() != null) {
3057                intent = intent.getSelector();
3058            }
3059            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3060
3061            // Try to find a matching persistent preferred activity.
3062            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3063                    debug, userId);
3064
3065            // If a persistent preferred activity matched, use it.
3066            if (pri != null) {
3067                return pri;
3068            }
3069
3070            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3071            // Get the list of preferred activities that handle the intent
3072            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3073            List<PreferredActivity> prefs = pir != null
3074                    ? pir.queryIntent(intent, resolvedType,
3075                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3076                    : null;
3077            if (prefs != null && prefs.size() > 0) {
3078                // First figure out how good the original match set is.
3079                // We will only allow preferred activities that came
3080                // from the same match quality.
3081                int match = 0;
3082
3083                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3084
3085                final int N = query.size();
3086                for (int j=0; j<N; j++) {
3087                    final ResolveInfo ri = query.get(j);
3088                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3089                            + ": 0x" + Integer.toHexString(match));
3090                    if (ri.match > match) {
3091                        match = ri.match;
3092                    }
3093                }
3094
3095                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3096                        + Integer.toHexString(match));
3097
3098                match &= IntentFilter.MATCH_CATEGORY_MASK;
3099                final int M = prefs.size();
3100                for (int i=0; i<M; i++) {
3101                    final PreferredActivity pa = prefs.get(i);
3102                    if (DEBUG_PREFERRED || debug) {
3103                        Slog.v(TAG, "Checking PreferredActivity ds="
3104                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3105                                + "\n  component=" + pa.mPref.mComponent);
3106                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3107                    }
3108                    if (pa.mPref.mMatch != match) {
3109                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3110                                + Integer.toHexString(pa.mPref.mMatch));
3111                        continue;
3112                    }
3113                    // If it's not an "always" type preferred activity and that's what we're
3114                    // looking for, skip it.
3115                    if (always && !pa.mPref.mAlways) {
3116                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3117                        continue;
3118                    }
3119                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3120                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3121                    if (DEBUG_PREFERRED || debug) {
3122                        Slog.v(TAG, "Found preferred activity:");
3123                        if (ai != null) {
3124                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3125                        } else {
3126                            Slog.v(TAG, "  null");
3127                        }
3128                    }
3129                    if (ai == null) {
3130                        // This previously registered preferred activity
3131                        // component is no longer known.  Most likely an update
3132                        // to the app was installed and in the new version this
3133                        // component no longer exists.  Clean it up by removing
3134                        // it from the preferred activities list, and skip it.
3135                        Slog.w(TAG, "Removing dangling preferred activity: "
3136                                + pa.mPref.mComponent);
3137                        pir.removeFilter(pa);
3138                        continue;
3139                    }
3140                    for (int j=0; j<N; j++) {
3141                        final ResolveInfo ri = query.get(j);
3142                        if (!ri.activityInfo.applicationInfo.packageName
3143                                .equals(ai.applicationInfo.packageName)) {
3144                            continue;
3145                        }
3146                        if (!ri.activityInfo.name.equals(ai.name)) {
3147                            continue;
3148                        }
3149
3150                        if (removeMatches) {
3151                            pir.removeFilter(pa);
3152                            if (DEBUG_PREFERRED) {
3153                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3154                            }
3155                            break;
3156                        }
3157
3158                        // Okay we found a previously set preferred or last chosen app.
3159                        // If the result set is different from when this
3160                        // was created, we need to clear it and re-ask the
3161                        // user their preference, if we're looking for an "always" type entry.
3162                        if (always && !pa.mPref.sameSet(query, priority)) {
3163                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3164                                    + intent + " type " + resolvedType);
3165                            if (DEBUG_PREFERRED) {
3166                                Slog.v(TAG, "Removing preferred activity since set changed "
3167                                        + pa.mPref.mComponent);
3168                            }
3169                            pir.removeFilter(pa);
3170                            // Re-add the filter as a "last chosen" entry (!always)
3171                            PreferredActivity lastChosen = new PreferredActivity(
3172                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3173                            pir.addFilter(lastChosen);
3174                            mSettings.writePackageRestrictionsLPr(userId);
3175                            return null;
3176                        }
3177
3178                        // Yay! Either the set matched or we're looking for the last chosen
3179                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3180                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3181                        mSettings.writePackageRestrictionsLPr(userId);
3182                        return ri;
3183                    }
3184                }
3185            }
3186            mSettings.writePackageRestrictionsLPr(userId);
3187        }
3188        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3189        return null;
3190    }
3191
3192    /*
3193     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3194     */
3195    @Override
3196    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3197            int targetUserId) {
3198        mContext.enforceCallingOrSelfPermission(
3199                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3200        List<CrossProfileIntentFilter> matches =
3201                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3202        if (matches != null) {
3203            int size = matches.size();
3204            for (int i = 0; i < size; i++) {
3205                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3206            }
3207        }
3208
3209        ArrayList<String> packageNames = null;
3210        SparseArray<ArrayList<String>> fromSource =
3211                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3212        if (fromSource != null) {
3213            packageNames = fromSource.get(targetUserId);
3214        }
3215        if (packageNames.contains(intent.getPackage())) {
3216            return true;
3217        }
3218        // We need the package name, so we try to resolve with the loosest flags possible
3219        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3220                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3221        int count = resolveInfos.size();
3222        for (int i = 0; i < count; i++) {
3223            ResolveInfo resolveInfo = resolveInfos.get(i);
3224            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3225                return true;
3226            }
3227        }
3228        return false;
3229    }
3230
3231    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3232            String resolvedType, int userId) {
3233        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3234        if (resolver != null) {
3235            return resolver.queryIntent(intent, resolvedType, false, userId);
3236        }
3237        return null;
3238    }
3239
3240    @Override
3241    public List<ResolveInfo> queryIntentActivities(Intent intent,
3242            String resolvedType, int flags, int userId) {
3243        if (!sUserManager.exists(userId)) return Collections.emptyList();
3244        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3245        ComponentName comp = intent.getComponent();
3246        if (comp == null) {
3247            if (intent.getSelector() != null) {
3248                intent = intent.getSelector();
3249                comp = intent.getComponent();
3250            }
3251        }
3252
3253        if (comp != null) {
3254            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3255            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3256            if (ai != null) {
3257                final ResolveInfo ri = new ResolveInfo();
3258                ri.activityInfo = ai;
3259                list.add(ri);
3260            }
3261            return list;
3262        }
3263
3264        // reader
3265        synchronized (mPackages) {
3266            final String pkgName = intent.getPackage();
3267            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3268            if (pkgName == null) {
3269                ResolveInfo resolveInfo = null;
3270                if (queryCrossProfile) {
3271                    // Check if the intent needs to be forwarded to another user for this package
3272                    ArrayList<ResolveInfo> crossProfileResult =
3273                            queryIntentActivitiesCrossProfilePackage(
3274                                    intent, resolvedType, flags, userId);
3275                    if (!crossProfileResult.isEmpty()) {
3276                        // Skip the current profile
3277                        return crossProfileResult;
3278                    }
3279                    List<CrossProfileIntentFilter> matchingFilters =
3280                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3281                    // Check for results that need to skip the current profile.
3282                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3283                            resolvedType, flags, userId);
3284                    if (resolveInfo != null) {
3285                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3286                        result.add(resolveInfo);
3287                        return result;
3288                    }
3289                    // Check for cross profile results.
3290                    resolveInfo = queryCrossProfileIntents(
3291                            matchingFilters, intent, resolvedType, flags, userId);
3292                }
3293                // Check for results in the current profile.
3294                List<ResolveInfo> result = mActivities.queryIntent(
3295                        intent, resolvedType, flags, userId);
3296                if (resolveInfo != null) {
3297                    result.add(resolveInfo);
3298                }
3299                return result;
3300            }
3301            final PackageParser.Package pkg = mPackages.get(pkgName);
3302            if (pkg != null) {
3303                if (queryCrossProfile) {
3304                    ArrayList<ResolveInfo> crossProfileResult =
3305                            queryIntentActivitiesCrossProfilePackage(
3306                                    intent, resolvedType, flags, userId, pkg, pkgName);
3307                    if (!crossProfileResult.isEmpty()) {
3308                        // Skip the current profile
3309                        return crossProfileResult;
3310                    }
3311                }
3312                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3313                        pkg.activities, userId);
3314            }
3315            return new ArrayList<ResolveInfo>();
3316        }
3317    }
3318
3319    private ResolveInfo querySkipCurrentProfileIntents(
3320            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3321            int flags, int sourceUserId) {
3322        if (matchingFilters != null) {
3323            int size = matchingFilters.size();
3324            for (int i = 0; i < size; i ++) {
3325                CrossProfileIntentFilter filter = matchingFilters.get(i);
3326                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3327                    // Checking if there are activities in the target user that can handle the
3328                    // intent.
3329                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3330                            flags, sourceUserId);
3331                    if (resolveInfo != null) {
3332                        return resolveInfo;
3333                    }
3334                }
3335            }
3336        }
3337        return null;
3338    }
3339
3340    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3341            Intent intent, String resolvedType, int flags, int userId) {
3342        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3343        SparseArray<ArrayList<String>> sourceForwardingInfo =
3344                mSettings.mCrossProfilePackageInfo.get(userId);
3345        if (sourceForwardingInfo != null) {
3346            int NI = sourceForwardingInfo.size();
3347            for (int i = 0; i < NI; i++) {
3348                int targetUserId = sourceForwardingInfo.keyAt(i);
3349                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3350                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3351                        intent, resolvedType, flags, targetUserId);
3352                int NJ = resolveInfos.size();
3353                for (int j = 0; j < NJ; j++) {
3354                    ResolveInfo resolveInfo = resolveInfos.get(j);
3355                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3356                        matchingResolveInfos.add(createForwardingResolveInfo(
3357                                resolveInfo.filter, userId, targetUserId));
3358                    }
3359                }
3360            }
3361        }
3362        return matchingResolveInfos;
3363    }
3364
3365    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3366            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3367            String packageName) {
3368        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3369        SparseArray<ArrayList<String>> sourceForwardingInfo =
3370                mSettings.mCrossProfilePackageInfo.get(userId);
3371        if (sourceForwardingInfo != null) {
3372            int NI = sourceForwardingInfo.size();
3373            for (int i = 0; i < NI; i++) {
3374                int targetUserId = sourceForwardingInfo.keyAt(i);
3375                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3376                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3377                            intent, resolvedType, flags, pkg.activities, targetUserId);
3378                    int NJ = resolveInfos.size();
3379                    for (int j = 0; j < NJ; j++) {
3380                        ResolveInfo resolveInfo = resolveInfos.get(j);
3381                        matchingResolveInfos.add(createForwardingResolveInfo(
3382                                resolveInfo.filter, userId, targetUserId));
3383                    }
3384                }
3385            }
3386        }
3387        return matchingResolveInfos;
3388    }
3389
3390    // Return matching ResolveInfo if any for skip current profile intent filters.
3391    private ResolveInfo queryCrossProfileIntents(
3392            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3393            int flags, int sourceUserId) {
3394        if (matchingFilters != null) {
3395            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3396            // match the same intent. For performance reasons, it is better not to
3397            // run queryIntent twice for the same userId
3398            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3399            int size = matchingFilters.size();
3400            for (int i = 0; i < size; i++) {
3401                CrossProfileIntentFilter filter = matchingFilters.get(i);
3402                int targetUserId = filter.getTargetUserId();
3403                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3404                        && !alreadyTriedUserIds.get(targetUserId)) {
3405                    // Checking if there are activities in the target user that can handle the
3406                    // intent.
3407                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3408                            flags, sourceUserId);
3409                    if (resolveInfo != null) return resolveInfo;
3410                    alreadyTriedUserIds.put(targetUserId, true);
3411                }
3412            }
3413        }
3414        return null;
3415    }
3416
3417    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3418            String resolvedType, int flags, int sourceUserId) {
3419        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3420                resolvedType, flags, filter.getTargetUserId());
3421        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3422            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3423        }
3424        return null;
3425    }
3426
3427    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3428            int sourceUserId, int targetUserId) {
3429        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3430        String className;
3431        if (targetUserId == UserHandle.USER_OWNER) {
3432            className = FORWARD_INTENT_TO_USER_OWNER;
3433        } else {
3434            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3435        }
3436        ComponentName forwardingActivityComponentName = new ComponentName(
3437                mAndroidApplication.packageName, className);
3438        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3439                sourceUserId);
3440        if (targetUserId == UserHandle.USER_OWNER) {
3441            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3442            forwardingResolveInfo.noResourceId = true;
3443        }
3444        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3445        forwardingResolveInfo.priority = 0;
3446        forwardingResolveInfo.preferredOrder = 0;
3447        forwardingResolveInfo.match = 0;
3448        forwardingResolveInfo.isDefault = true;
3449        forwardingResolveInfo.filter = filter;
3450        forwardingResolveInfo.targetUserId = targetUserId;
3451        return forwardingResolveInfo;
3452    }
3453
3454    @Override
3455    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3456            Intent[] specifics, String[] specificTypes, Intent intent,
3457            String resolvedType, int flags, int userId) {
3458        if (!sUserManager.exists(userId)) return Collections.emptyList();
3459        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3460                "query intent activity options");
3461        final String resultsAction = intent.getAction();
3462
3463        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3464                | PackageManager.GET_RESOLVED_FILTER, userId);
3465
3466        if (DEBUG_INTENT_MATCHING) {
3467            Log.v(TAG, "Query " + intent + ": " + results);
3468        }
3469
3470        int specificsPos = 0;
3471        int N;
3472
3473        // todo: note that the algorithm used here is O(N^2).  This
3474        // isn't a problem in our current environment, but if we start running
3475        // into situations where we have more than 5 or 10 matches then this
3476        // should probably be changed to something smarter...
3477
3478        // First we go through and resolve each of the specific items
3479        // that were supplied, taking care of removing any corresponding
3480        // duplicate items in the generic resolve list.
3481        if (specifics != null) {
3482            for (int i=0; i<specifics.length; i++) {
3483                final Intent sintent = specifics[i];
3484                if (sintent == null) {
3485                    continue;
3486                }
3487
3488                if (DEBUG_INTENT_MATCHING) {
3489                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3490                }
3491
3492                String action = sintent.getAction();
3493                if (resultsAction != null && resultsAction.equals(action)) {
3494                    // If this action was explicitly requested, then don't
3495                    // remove things that have it.
3496                    action = null;
3497                }
3498
3499                ResolveInfo ri = null;
3500                ActivityInfo ai = null;
3501
3502                ComponentName comp = sintent.getComponent();
3503                if (comp == null) {
3504                    ri = resolveIntent(
3505                        sintent,
3506                        specificTypes != null ? specificTypes[i] : null,
3507                            flags, userId);
3508                    if (ri == null) {
3509                        continue;
3510                    }
3511                    if (ri == mResolveInfo) {
3512                        // ACK!  Must do something better with this.
3513                    }
3514                    ai = ri.activityInfo;
3515                    comp = new ComponentName(ai.applicationInfo.packageName,
3516                            ai.name);
3517                } else {
3518                    ai = getActivityInfo(comp, flags, userId);
3519                    if (ai == null) {
3520                        continue;
3521                    }
3522                }
3523
3524                // Look for any generic query activities that are duplicates
3525                // of this specific one, and remove them from the results.
3526                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3527                N = results.size();
3528                int j;
3529                for (j=specificsPos; j<N; j++) {
3530                    ResolveInfo sri = results.get(j);
3531                    if ((sri.activityInfo.name.equals(comp.getClassName())
3532                            && sri.activityInfo.applicationInfo.packageName.equals(
3533                                    comp.getPackageName()))
3534                        || (action != null && sri.filter.matchAction(action))) {
3535                        results.remove(j);
3536                        if (DEBUG_INTENT_MATCHING) Log.v(
3537                            TAG, "Removing duplicate item from " + j
3538                            + " due to specific " + specificsPos);
3539                        if (ri == null) {
3540                            ri = sri;
3541                        }
3542                        j--;
3543                        N--;
3544                    }
3545                }
3546
3547                // Add this specific item to its proper place.
3548                if (ri == null) {
3549                    ri = new ResolveInfo();
3550                    ri.activityInfo = ai;
3551                }
3552                results.add(specificsPos, ri);
3553                ri.specificIndex = i;
3554                specificsPos++;
3555            }
3556        }
3557
3558        // Now we go through the remaining generic results and remove any
3559        // duplicate actions that are found here.
3560        N = results.size();
3561        for (int i=specificsPos; i<N-1; i++) {
3562            final ResolveInfo rii = results.get(i);
3563            if (rii.filter == null) {
3564                continue;
3565            }
3566
3567            // Iterate over all of the actions of this result's intent
3568            // filter...  typically this should be just one.
3569            final Iterator<String> it = rii.filter.actionsIterator();
3570            if (it == null) {
3571                continue;
3572            }
3573            while (it.hasNext()) {
3574                final String action = it.next();
3575                if (resultsAction != null && resultsAction.equals(action)) {
3576                    // If this action was explicitly requested, then don't
3577                    // remove things that have it.
3578                    continue;
3579                }
3580                for (int j=i+1; j<N; j++) {
3581                    final ResolveInfo rij = results.get(j);
3582                    if (rij.filter != null && rij.filter.hasAction(action)) {
3583                        results.remove(j);
3584                        if (DEBUG_INTENT_MATCHING) Log.v(
3585                            TAG, "Removing duplicate item from " + j
3586                            + " due to action " + action + " at " + i);
3587                        j--;
3588                        N--;
3589                    }
3590                }
3591            }
3592
3593            // If the caller didn't request filter information, drop it now
3594            // so we don't have to marshall/unmarshall it.
3595            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3596                rii.filter = null;
3597            }
3598        }
3599
3600        // Filter out the caller activity if so requested.
3601        if (caller != null) {
3602            N = results.size();
3603            for (int i=0; i<N; i++) {
3604                ActivityInfo ainfo = results.get(i).activityInfo;
3605                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3606                        && caller.getClassName().equals(ainfo.name)) {
3607                    results.remove(i);
3608                    break;
3609                }
3610            }
3611        }
3612
3613        // If the caller didn't request filter information,
3614        // drop them now so we don't have to
3615        // marshall/unmarshall it.
3616        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3617            N = results.size();
3618            for (int i=0; i<N; i++) {
3619                results.get(i).filter = null;
3620            }
3621        }
3622
3623        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3624        return results;
3625    }
3626
3627    @Override
3628    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3629            int userId) {
3630        if (!sUserManager.exists(userId)) return Collections.emptyList();
3631        ComponentName comp = intent.getComponent();
3632        if (comp == null) {
3633            if (intent.getSelector() != null) {
3634                intent = intent.getSelector();
3635                comp = intent.getComponent();
3636            }
3637        }
3638        if (comp != null) {
3639            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3640            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3641            if (ai != null) {
3642                ResolveInfo ri = new ResolveInfo();
3643                ri.activityInfo = ai;
3644                list.add(ri);
3645            }
3646            return list;
3647        }
3648
3649        // reader
3650        synchronized (mPackages) {
3651            String pkgName = intent.getPackage();
3652            if (pkgName == null) {
3653                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3654            }
3655            final PackageParser.Package pkg = mPackages.get(pkgName);
3656            if (pkg != null) {
3657                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3658                        userId);
3659            }
3660            return null;
3661        }
3662    }
3663
3664    @Override
3665    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3666        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3667        if (!sUserManager.exists(userId)) return null;
3668        if (query != null) {
3669            if (query.size() >= 1) {
3670                // If there is more than one service with the same priority,
3671                // just arbitrarily pick the first one.
3672                return query.get(0);
3673            }
3674        }
3675        return null;
3676    }
3677
3678    @Override
3679    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3680            int userId) {
3681        if (!sUserManager.exists(userId)) return Collections.emptyList();
3682        ComponentName comp = intent.getComponent();
3683        if (comp == null) {
3684            if (intent.getSelector() != null) {
3685                intent = intent.getSelector();
3686                comp = intent.getComponent();
3687            }
3688        }
3689        if (comp != null) {
3690            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3691            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3692            if (si != null) {
3693                final ResolveInfo ri = new ResolveInfo();
3694                ri.serviceInfo = si;
3695                list.add(ri);
3696            }
3697            return list;
3698        }
3699
3700        // reader
3701        synchronized (mPackages) {
3702            String pkgName = intent.getPackage();
3703            if (pkgName == null) {
3704                return mServices.queryIntent(intent, resolvedType, flags, userId);
3705            }
3706            final PackageParser.Package pkg = mPackages.get(pkgName);
3707            if (pkg != null) {
3708                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3709                        userId);
3710            }
3711            return null;
3712        }
3713    }
3714
3715    @Override
3716    public List<ResolveInfo> queryIntentContentProviders(
3717            Intent intent, String resolvedType, int flags, int userId) {
3718        if (!sUserManager.exists(userId)) return Collections.emptyList();
3719        ComponentName comp = intent.getComponent();
3720        if (comp == null) {
3721            if (intent.getSelector() != null) {
3722                intent = intent.getSelector();
3723                comp = intent.getComponent();
3724            }
3725        }
3726        if (comp != null) {
3727            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3728            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3729            if (pi != null) {
3730                final ResolveInfo ri = new ResolveInfo();
3731                ri.providerInfo = pi;
3732                list.add(ri);
3733            }
3734            return list;
3735        }
3736
3737        // reader
3738        synchronized (mPackages) {
3739            String pkgName = intent.getPackage();
3740            if (pkgName == null) {
3741                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3742            }
3743            final PackageParser.Package pkg = mPackages.get(pkgName);
3744            if (pkg != null) {
3745                return mProviders.queryIntentForPackage(
3746                        intent, resolvedType, flags, pkg.providers, userId);
3747            }
3748            return null;
3749        }
3750    }
3751
3752    @Override
3753    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3754        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3755
3756        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3757
3758        // writer
3759        synchronized (mPackages) {
3760            ArrayList<PackageInfo> list;
3761            if (listUninstalled) {
3762                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3763                for (PackageSetting ps : mSettings.mPackages.values()) {
3764                    PackageInfo pi;
3765                    if (ps.pkg != null) {
3766                        pi = generatePackageInfo(ps.pkg, flags, userId);
3767                    } else {
3768                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3769                    }
3770                    if (pi != null) {
3771                        list.add(pi);
3772                    }
3773                }
3774            } else {
3775                list = new ArrayList<PackageInfo>(mPackages.size());
3776                for (PackageParser.Package p : mPackages.values()) {
3777                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3778                    if (pi != null) {
3779                        list.add(pi);
3780                    }
3781                }
3782            }
3783
3784            return new ParceledListSlice<PackageInfo>(list);
3785        }
3786    }
3787
3788    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3789            String[] permissions, boolean[] tmp, int flags, int userId) {
3790        int numMatch = 0;
3791        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3792        for (int i=0; i<permissions.length; i++) {
3793            if (gp.grantedPermissions.contains(permissions[i])) {
3794                tmp[i] = true;
3795                numMatch++;
3796            } else {
3797                tmp[i] = false;
3798            }
3799        }
3800        if (numMatch == 0) {
3801            return;
3802        }
3803        PackageInfo pi;
3804        if (ps.pkg != null) {
3805            pi = generatePackageInfo(ps.pkg, flags, userId);
3806        } else {
3807            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3808        }
3809        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3810            if (numMatch == permissions.length) {
3811                pi.requestedPermissions = permissions;
3812            } else {
3813                pi.requestedPermissions = new String[numMatch];
3814                numMatch = 0;
3815                for (int i=0; i<permissions.length; i++) {
3816                    if (tmp[i]) {
3817                        pi.requestedPermissions[numMatch] = permissions[i];
3818                        numMatch++;
3819                    }
3820                }
3821            }
3822        }
3823        list.add(pi);
3824    }
3825
3826    @Override
3827    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3828            String[] permissions, int flags, int userId) {
3829        if (!sUserManager.exists(userId)) return null;
3830        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3831
3832        // writer
3833        synchronized (mPackages) {
3834            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3835            boolean[] tmpBools = new boolean[permissions.length];
3836            if (listUninstalled) {
3837                for (PackageSetting ps : mSettings.mPackages.values()) {
3838                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3839                }
3840            } else {
3841                for (PackageParser.Package pkg : mPackages.values()) {
3842                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3843                    if (ps != null) {
3844                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3845                                userId);
3846                    }
3847                }
3848            }
3849
3850            return new ParceledListSlice<PackageInfo>(list);
3851        }
3852    }
3853
3854    @Override
3855    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3856        if (!sUserManager.exists(userId)) return null;
3857        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3858
3859        // writer
3860        synchronized (mPackages) {
3861            ArrayList<ApplicationInfo> list;
3862            if (listUninstalled) {
3863                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3864                for (PackageSetting ps : mSettings.mPackages.values()) {
3865                    ApplicationInfo ai;
3866                    if (ps.pkg != null) {
3867                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3868                                ps.readUserState(userId), userId);
3869                    } else {
3870                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3871                    }
3872                    if (ai != null) {
3873                        list.add(ai);
3874                    }
3875                }
3876            } else {
3877                list = new ArrayList<ApplicationInfo>(mPackages.size());
3878                for (PackageParser.Package p : mPackages.values()) {
3879                    if (p.mExtras != null) {
3880                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3881                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3882                        if (ai != null) {
3883                            list.add(ai);
3884                        }
3885                    }
3886                }
3887            }
3888
3889            return new ParceledListSlice<ApplicationInfo>(list);
3890        }
3891    }
3892
3893    public List<ApplicationInfo> getPersistentApplications(int flags) {
3894        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3895
3896        // reader
3897        synchronized (mPackages) {
3898            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3899            final int userId = UserHandle.getCallingUserId();
3900            while (i.hasNext()) {
3901                final PackageParser.Package p = i.next();
3902                if (p.applicationInfo != null
3903                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3904                        && (!mSafeMode || isSystemApp(p))) {
3905                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3906                    if (ps != null) {
3907                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3908                                ps.readUserState(userId), userId);
3909                        if (ai != null) {
3910                            finalList.add(ai);
3911                        }
3912                    }
3913                }
3914            }
3915        }
3916
3917        return finalList;
3918    }
3919
3920    @Override
3921    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3922        if (!sUserManager.exists(userId)) return null;
3923        // reader
3924        synchronized (mPackages) {
3925            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3926            PackageSetting ps = provider != null
3927                    ? mSettings.mPackages.get(provider.owner.packageName)
3928                    : null;
3929            return ps != null
3930                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3931                    && (!mSafeMode || (provider.info.applicationInfo.flags
3932                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3933                    ? PackageParser.generateProviderInfo(provider, flags,
3934                            ps.readUserState(userId), userId)
3935                    : null;
3936        }
3937    }
3938
3939    /**
3940     * @deprecated
3941     */
3942    @Deprecated
3943    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3944        // reader
3945        synchronized (mPackages) {
3946            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3947                    .entrySet().iterator();
3948            final int userId = UserHandle.getCallingUserId();
3949            while (i.hasNext()) {
3950                Map.Entry<String, PackageParser.Provider> entry = i.next();
3951                PackageParser.Provider p = entry.getValue();
3952                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3953
3954                if (ps != null && p.syncable
3955                        && (!mSafeMode || (p.info.applicationInfo.flags
3956                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3957                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3958                            ps.readUserState(userId), userId);
3959                    if (info != null) {
3960                        outNames.add(entry.getKey());
3961                        outInfo.add(info);
3962                    }
3963                }
3964            }
3965        }
3966    }
3967
3968    @Override
3969    public List<ProviderInfo> queryContentProviders(String processName,
3970            int uid, int flags) {
3971        ArrayList<ProviderInfo> finalList = null;
3972        // reader
3973        synchronized (mPackages) {
3974            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3975            final int userId = processName != null ?
3976                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3977            while (i.hasNext()) {
3978                final PackageParser.Provider p = i.next();
3979                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3980                if (ps != null && p.info.authority != null
3981                        && (processName == null
3982                                || (p.info.processName.equals(processName)
3983                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3984                        && mSettings.isEnabledLPr(p.info, flags, userId)
3985                        && (!mSafeMode
3986                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3987                    if (finalList == null) {
3988                        finalList = new ArrayList<ProviderInfo>(3);
3989                    }
3990                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3991                            ps.readUserState(userId), userId);
3992                    if (info != null) {
3993                        finalList.add(info);
3994                    }
3995                }
3996            }
3997        }
3998
3999        if (finalList != null) {
4000            Collections.sort(finalList, mProviderInitOrderSorter);
4001        }
4002
4003        return finalList;
4004    }
4005
4006    @Override
4007    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4008            int flags) {
4009        // reader
4010        synchronized (mPackages) {
4011            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4012            return PackageParser.generateInstrumentationInfo(i, flags);
4013        }
4014    }
4015
4016    @Override
4017    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4018            int flags) {
4019        ArrayList<InstrumentationInfo> finalList =
4020            new ArrayList<InstrumentationInfo>();
4021
4022        // reader
4023        synchronized (mPackages) {
4024            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4025            while (i.hasNext()) {
4026                final PackageParser.Instrumentation p = i.next();
4027                if (targetPackage == null
4028                        || targetPackage.equals(p.info.targetPackage)) {
4029                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4030                            flags);
4031                    if (ii != null) {
4032                        finalList.add(ii);
4033                    }
4034                }
4035            }
4036        }
4037
4038        return finalList;
4039    }
4040
4041    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4042        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4043        if (overlays == null) {
4044            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4045            return;
4046        }
4047        for (PackageParser.Package opkg : overlays.values()) {
4048            // Not much to do if idmap fails: we already logged the error
4049            // and we certainly don't want to abort installation of pkg simply
4050            // because an overlay didn't fit properly. For these reasons,
4051            // ignore the return value of createIdmapForPackagePairLI.
4052            createIdmapForPackagePairLI(pkg, opkg);
4053        }
4054    }
4055
4056    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4057            PackageParser.Package opkg) {
4058        if (!opkg.mTrustedOverlay) {
4059            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4060                    opkg.baseCodePath + ": overlay not trusted");
4061            return false;
4062        }
4063        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4064        if (overlaySet == null) {
4065            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4066                    opkg.baseCodePath + " but target package has no known overlays");
4067            return false;
4068        }
4069        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4070        // TODO: generate idmap for split APKs
4071        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4072            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4073                    + opkg.baseCodePath);
4074            return false;
4075        }
4076        PackageParser.Package[] overlayArray =
4077            overlaySet.values().toArray(new PackageParser.Package[0]);
4078        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4079            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4080                return p1.mOverlayPriority - p2.mOverlayPriority;
4081            }
4082        };
4083        Arrays.sort(overlayArray, cmp);
4084
4085        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4086        int i = 0;
4087        for (PackageParser.Package p : overlayArray) {
4088            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4089        }
4090        return true;
4091    }
4092
4093    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4094        final File[] files = dir.listFiles();
4095        if (ArrayUtils.isEmpty(files)) {
4096            Log.d(TAG, "No files in app dir " + dir);
4097            return;
4098        }
4099
4100        if (DEBUG_PACKAGE_SCANNING) {
4101            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4102                    + " flags=0x" + Integer.toHexString(flags));
4103        }
4104
4105        for (File file : files) {
4106            final boolean isPackage = isApkFile(file) || file.isDirectory();
4107            if (!isPackage) {
4108                // Ignore entries which are not apk's
4109                continue;
4110            }
4111            PackageParser.Package pkg = scanPackageLI(file,
4112                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4113            // Don't mess around with apps in system partition.
4114            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4115                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4116                // Delete the apk
4117                Slog.w(TAG, "Cleaning up failed install of " + file);
4118                file.delete();
4119            }
4120        }
4121    }
4122
4123    private static File getSettingsProblemFile() {
4124        File dataDir = Environment.getDataDirectory();
4125        File systemDir = new File(dataDir, "system");
4126        File fname = new File(systemDir, "uiderrors.txt");
4127        return fname;
4128    }
4129
4130    static void reportSettingsProblem(int priority, String msg) {
4131        try {
4132            File fname = getSettingsProblemFile();
4133            FileOutputStream out = new FileOutputStream(fname, true);
4134            PrintWriter pw = new FastPrintWriter(out);
4135            SimpleDateFormat formatter = new SimpleDateFormat();
4136            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4137            pw.println(dateString + ": " + msg);
4138            pw.close();
4139            FileUtils.setPermissions(
4140                    fname.toString(),
4141                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4142                    -1, -1);
4143        } catch (java.io.IOException e) {
4144        }
4145        Slog.println(priority, TAG, msg);
4146    }
4147
4148    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4149            PackageParser.Package pkg, File srcFile, int parseFlags) {
4150        if (ps != null
4151                && ps.codePath.equals(srcFile)
4152                && ps.timeStamp == srcFile.lastModified()
4153                && !isCompatSignatureUpdateNeeded(pkg)) {
4154            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4155            if (ps.signatures.mSignatures != null
4156                    && ps.signatures.mSignatures.length != 0
4157                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4158                // Optimization: reuse the existing cached certificates
4159                // if the package appears to be unchanged.
4160                pkg.mSignatures = ps.signatures.mSignatures;
4161                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4162                pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId);
4163                return true;
4164            }
4165
4166            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4167        } else {
4168            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4169        }
4170
4171        try {
4172            pp.collectCertificates(pkg, parseFlags);
4173            pp.collectManifestDigest(pkg);
4174        } catch (PackageParserException e) {
4175            mLastScanError = e.error;
4176            return false;
4177        }
4178        return true;
4179    }
4180
4181    /*
4182     *  Scan a package and return the newly parsed package.
4183     *  Returns null in case of errors and the error code is stored in mLastScanError
4184     */
4185    private PackageParser.Package scanPackageLI(File scanFile,
4186            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4187        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4188        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4189        parseFlags |= mDefParseFlags;
4190        PackageParser pp = new PackageParser();
4191        pp.setSeparateProcesses(mSeparateProcesses);
4192        pp.setOnlyCoreApps(mOnlyCore);
4193        pp.setDisplayMetrics(mMetrics);
4194
4195        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4196            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4197        }
4198
4199        final PackageParser.Package pkg;
4200        try {
4201            pkg = pp.parsePackage(scanFile, parseFlags);
4202        } catch (PackageParserException e) {
4203            mLastScanError = e.error;
4204            return null;
4205        }
4206
4207        PackageSetting ps = null;
4208        PackageSetting updatedPkg;
4209        // reader
4210        synchronized (mPackages) {
4211            // Look to see if we already know about this package.
4212            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4213            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4214                // This package has been renamed to its original name.  Let's
4215                // use that.
4216                ps = mSettings.peekPackageLPr(oldName);
4217            }
4218            // If there was no original package, see one for the real package name.
4219            if (ps == null) {
4220                ps = mSettings.peekPackageLPr(pkg.packageName);
4221            }
4222            // Check to see if this package could be hiding/updating a system
4223            // package.  Must look for it either under the original or real
4224            // package name depending on our state.
4225            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4226            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4227        }
4228        boolean updatedPkgBetter = false;
4229        // First check if this is a system package that may involve an update
4230        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4231            if (ps != null && !ps.codePath.equals(scanFile)) {
4232                // The path has changed from what was last scanned...  check the
4233                // version of the new path against what we have stored to determine
4234                // what to do.
4235                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4236                if (pkg.mVersionCode < ps.versionCode) {
4237                    // The system package has been updated and the code path does not match
4238                    // Ignore entry. Skip it.
4239                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4240                            + " ignored: updated version " + ps.versionCode
4241                            + " better than this " + pkg.mVersionCode);
4242                    if (!updatedPkg.codePath.equals(scanFile)) {
4243                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4244                                + ps.name + " changing from " + updatedPkg.codePathString
4245                                + " to " + scanFile);
4246                        updatedPkg.codePath = scanFile;
4247                        updatedPkg.codePathString = scanFile.toString();
4248                        // This is the point at which we know that the system-disk APK
4249                        // for this package has moved during a reboot (e.g. due to an OTA),
4250                        // so we need to reevaluate it for privilege policy.
4251                        if (locationIsPrivileged(scanFile)) {
4252                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4253                        }
4254                    }
4255                    updatedPkg.pkg = pkg;
4256                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4257                    return null;
4258                } else {
4259                    // The current app on the system partition is better than
4260                    // what we have updated to on the data partition; switch
4261                    // back to the system partition version.
4262                    // At this point, its safely assumed that package installation for
4263                    // apps in system partition will go through. If not there won't be a working
4264                    // version of the app
4265                    // writer
4266                    synchronized (mPackages) {
4267                        // Just remove the loaded entries from package lists.
4268                        mPackages.remove(ps.name);
4269                    }
4270                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4271                            + "reverting from " + ps.codePathString
4272                            + ": new version " + pkg.mVersionCode
4273                            + " better than installed " + ps.versionCode);
4274
4275                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4276                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4277                            getAppInstructionSetFromSettings(ps));
4278                    synchronized (mInstallLock) {
4279                        args.cleanUpResourcesLI();
4280                    }
4281                    synchronized (mPackages) {
4282                        mSettings.enableSystemPackageLPw(ps.name);
4283                    }
4284                    updatedPkgBetter = true;
4285                }
4286            }
4287        }
4288
4289        if (updatedPkg != null) {
4290            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4291            // initially
4292            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4293
4294            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4295            // flag set initially
4296            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4297                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4298            }
4299        }
4300        // Verify certificates against what was last scanned
4301        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4302            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4303            return null;
4304        }
4305
4306        /*
4307         * A new system app appeared, but we already had a non-system one of the
4308         * same name installed earlier.
4309         */
4310        boolean shouldHideSystemApp = false;
4311        if (updatedPkg == null && ps != null
4312                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4313            /*
4314             * Check to make sure the signatures match first. If they don't,
4315             * wipe the installed application and its data.
4316             */
4317            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4318                    != PackageManager.SIGNATURE_MATCH) {
4319                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4320                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4321                ps = null;
4322            } else {
4323                /*
4324                 * If the newly-added system app is an older version than the
4325                 * already installed version, hide it. It will be scanned later
4326                 * and re-added like an update.
4327                 */
4328                if (pkg.mVersionCode < ps.versionCode) {
4329                    shouldHideSystemApp = true;
4330                } else {
4331                    /*
4332                     * The newly found system app is a newer version that the
4333                     * one previously installed. Simply remove the
4334                     * already-installed application and replace it with our own
4335                     * while keeping the application data.
4336                     */
4337                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4338                            + ps.codePathString + ": new version " + pkg.mVersionCode
4339                            + " better than installed " + ps.versionCode);
4340                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4341                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4342                            getAppInstructionSetFromSettings(ps));
4343                    synchronized (mInstallLock) {
4344                        args.cleanUpResourcesLI();
4345                    }
4346                }
4347            }
4348        }
4349
4350        // The apk is forward locked (not public) if its code and resources
4351        // are kept in different files. (except for app in either system or
4352        // vendor path).
4353        // TODO grab this value from PackageSettings
4354        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4355            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4356                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4357            }
4358        }
4359
4360        // TODO: extend to support forward-locked splits
4361        String resourcePath = null;
4362        String baseResourcePath = null;
4363        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4364            if (ps != null && ps.resourcePathString != null) {
4365                resourcePath = ps.resourcePathString;
4366                baseResourcePath = ps.resourcePathString;
4367            } else {
4368                // Should not happen at all. Just log an error.
4369                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4370            }
4371        } else {
4372            resourcePath = pkg.codePath;
4373            baseResourcePath = pkg.baseCodePath;
4374        }
4375
4376        // Set application objects path explicitly.
4377        pkg.applicationInfo.setCodePath(pkg.codePath);
4378        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4379        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4380        pkg.applicationInfo.setResourcePath(resourcePath);
4381        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4382        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4383
4384        // Note that we invoke the following method only if we are about to unpack an application
4385        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4386                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4387
4388        /*
4389         * If the system app should be overridden by a previously installed
4390         * data, hide the system app now and let the /data/app scan pick it up
4391         * again.
4392         */
4393        if (shouldHideSystemApp) {
4394            synchronized (mPackages) {
4395                /*
4396                 * We have to grant systems permissions before we hide, because
4397                 * grantPermissions will assume the package update is trying to
4398                 * expand its permissions.
4399                 */
4400                grantPermissionsLPw(pkg, true);
4401                mSettings.disableSystemPackageLPw(pkg.packageName);
4402            }
4403        }
4404
4405        return scannedPkg;
4406    }
4407
4408    private static String fixProcessName(String defProcessName,
4409            String processName, int uid) {
4410        if (processName == null) {
4411            return defProcessName;
4412        }
4413        return processName;
4414    }
4415
4416    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4417        if (pkgSetting.signatures.mSignatures != null) {
4418            // Already existing package. Make sure signatures match
4419            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4420                    == PackageManager.SIGNATURE_MATCH;
4421            if (!match) {
4422                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4423                        == PackageManager.SIGNATURE_MATCH;
4424            }
4425            if (!match) {
4426                Slog.e(TAG, "Package " + pkg.packageName
4427                        + " signatures do not match the previously installed version; ignoring!");
4428                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4429                return false;
4430            }
4431        }
4432
4433        // Check for shared user signatures
4434        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4435            // Already existing package. Make sure signatures match
4436            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4437                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4438            if (!match) {
4439                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4440                        == PackageManager.SIGNATURE_MATCH;
4441            }
4442            if (!match) {
4443                Slog.e(TAG, "Package " + pkg.packageName
4444                        + " has no signatures that match those in shared user "
4445                        + pkgSetting.sharedUser.name + "; ignoring!");
4446                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4447                return false;
4448            }
4449        }
4450        return true;
4451    }
4452
4453    /**
4454     * Enforces that only the system UID or root's UID can call a method exposed
4455     * via Binder.
4456     *
4457     * @param message used as message if SecurityException is thrown
4458     * @throws SecurityException if the caller is not system or root
4459     */
4460    private static final void enforceSystemOrRoot(String message) {
4461        final int uid = Binder.getCallingUid();
4462        if (uid != Process.SYSTEM_UID && uid != 0) {
4463            throw new SecurityException(message);
4464        }
4465    }
4466
4467    @Override
4468    public void performBootDexOpt() {
4469        enforceSystemOrRoot("Only the system can request dexopt be performed");
4470
4471        final HashSet<PackageParser.Package> pkgs;
4472        synchronized (mPackages) {
4473            pkgs = mDeferredDexOpt;
4474            mDeferredDexOpt = null;
4475        }
4476
4477        if (pkgs != null) {
4478            // Filter out packages that aren't recently used.
4479            //
4480            // The exception is first boot of a non-eng device, which
4481            // should do a full dexopt.
4482            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4483            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4484                // TODO: add a property to control this?
4485                long dexOptLRUThresholdInMinutes;
4486                if (eng) {
4487                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4488                } else {
4489                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4490                }
4491                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4492
4493                int total = pkgs.size();
4494                int skipped = 0;
4495                long now = System.currentTimeMillis();
4496                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4497                    PackageParser.Package pkg = i.next();
4498                    long then = pkg.mLastPackageUsageTimeInMills;
4499                    if (then + dexOptLRUThresholdInMills < now) {
4500                        if (DEBUG_DEXOPT) {
4501                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4502                                  ((then == 0) ? "never" : new Date(then)));
4503                        }
4504                        i.remove();
4505                        skipped++;
4506                    }
4507                }
4508                if (DEBUG_DEXOPT) {
4509                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4510                }
4511            }
4512
4513            int i = 0;
4514            for (PackageParser.Package pkg : pkgs) {
4515                i++;
4516                if (DEBUG_DEXOPT) {
4517                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4518                          + ": " + pkg.packageName);
4519                }
4520                if (!isFirstBoot()) {
4521                    try {
4522                        ActivityManagerNative.getDefault().showBootMessage(
4523                                mContext.getResources().getString(
4524                                        R.string.android_upgrading_apk,
4525                                        i, pkgs.size()), true);
4526                    } catch (RemoteException e) {
4527                    }
4528                }
4529                PackageParser.Package p = pkg;
4530                synchronized (mInstallLock) {
4531                    if (p.mDexOptNeeded) {
4532                        performDexOptLI(p, false /* force dex */, false /* defer */,
4533                                true /* include dependencies */);
4534                    }
4535                }
4536            }
4537        }
4538    }
4539
4540    @Override
4541    public boolean performDexOpt(String packageName) {
4542        enforceSystemOrRoot("Only the system can request dexopt be performed");
4543        return performDexOpt(packageName, true);
4544    }
4545
4546    public boolean performDexOpt(String packageName, boolean updateUsage) {
4547
4548        PackageParser.Package p;
4549        synchronized (mPackages) {
4550            p = mPackages.get(packageName);
4551            if (p == null) {
4552                return false;
4553            }
4554            if (updateUsage) {
4555                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4556            }
4557            mPackageUsage.write(false);
4558            if (!p.mDexOptNeeded) {
4559                return false;
4560            }
4561        }
4562
4563        synchronized (mInstallLock) {
4564            return performDexOptLI(p, false /* force dex */, false /* defer */,
4565                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4566        }
4567    }
4568
4569    public HashSet<String> getPackagesThatNeedDexOpt() {
4570        HashSet<String> pkgs = null;
4571        synchronized (mPackages) {
4572            for (PackageParser.Package p : mPackages.values()) {
4573                if (DEBUG_DEXOPT) {
4574                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4575                }
4576                if (!p.mDexOptNeeded) {
4577                    continue;
4578                }
4579                if (pkgs == null) {
4580                    pkgs = new HashSet<String>();
4581                }
4582                pkgs.add(p.packageName);
4583            }
4584        }
4585        return pkgs;
4586    }
4587
4588    public void shutdown() {
4589        mPackageUsage.write(true);
4590    }
4591
4592    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4593             boolean forceDex, boolean defer, HashSet<String> done) {
4594        for (int i=0; i<libs.size(); i++) {
4595            PackageParser.Package libPkg;
4596            String libName;
4597            synchronized (mPackages) {
4598                libName = libs.get(i);
4599                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4600                if (lib != null && lib.apk != null) {
4601                    libPkg = mPackages.get(lib.apk);
4602                } else {
4603                    libPkg = null;
4604                }
4605            }
4606            if (libPkg != null && !done.contains(libName)) {
4607                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4608            }
4609        }
4610    }
4611
4612    static final int DEX_OPT_SKIPPED = 0;
4613    static final int DEX_OPT_PERFORMED = 1;
4614    static final int DEX_OPT_DEFERRED = 2;
4615    static final int DEX_OPT_FAILED = -1;
4616
4617    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4618            boolean forceDex, boolean defer, HashSet<String> done) {
4619        final String instructionSet = instructionSetOverride != null ?
4620                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4621
4622        if (done != null) {
4623            done.add(pkg.packageName);
4624            if (pkg.usesLibraries != null) {
4625                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4626            }
4627            if (pkg.usesOptionalLibraries != null) {
4628                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4629            }
4630        }
4631
4632        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
4633            final Collection<String> paths = pkg.getAllCodePaths();
4634            for (String path : paths) {
4635                try {
4636                    boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4637                            pkg.packageName, instructionSet, defer);
4638                    // There are three basic cases here:
4639                    // 1.) we need to dexopt, either because we are forced or it is needed
4640                    // 2.) we are defering a needed dexopt
4641                    // 3.) we are skipping an unneeded dexopt
4642                    if (forceDex || (!defer && isDexOptNeededInternal)) {
4643                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4644                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4645                        int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4646                                                    pkg.packageName, instructionSet);
4647                        // Note that we ran dexopt, since rerunning will
4648                        // probably just result in an error again.
4649                        pkg.mDexOptNeeded = false;
4650                        if (ret < 0) {
4651                            return DEX_OPT_FAILED;
4652                        }
4653                        return DEX_OPT_PERFORMED;
4654                    }
4655                    if (defer && isDexOptNeededInternal) {
4656                        if (mDeferredDexOpt == null) {
4657                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4658                        }
4659                        mDeferredDexOpt.add(pkg);
4660                        return DEX_OPT_DEFERRED;
4661                    }
4662                    pkg.mDexOptNeeded = false;
4663                    return DEX_OPT_SKIPPED;
4664                } catch (FileNotFoundException e) {
4665                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4666                    return DEX_OPT_FAILED;
4667                } catch (IOException e) {
4668                    Slog.w(TAG, "IOException reading apk: " + path, e);
4669                    return DEX_OPT_FAILED;
4670                } catch (StaleDexCacheError e) {
4671                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4672                    return DEX_OPT_FAILED;
4673                } catch (Exception e) {
4674                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4675                    return DEX_OPT_FAILED;
4676                }
4677            }
4678        }
4679        return DEX_OPT_SKIPPED;
4680    }
4681
4682    private String getAppInstructionSet(ApplicationInfo info) {
4683        String instructionSet = getPreferredInstructionSet();
4684
4685        if (info.cpuAbi != null) {
4686            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4687        }
4688
4689        return instructionSet;
4690    }
4691
4692    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4693        String instructionSet = getPreferredInstructionSet();
4694
4695        if (ps.cpuAbiString != null) {
4696            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4697        }
4698
4699        return instructionSet;
4700    }
4701
4702    private static String getPreferredInstructionSet() {
4703        if (sPreferredInstructionSet == null) {
4704            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4705        }
4706
4707        return sPreferredInstructionSet;
4708    }
4709
4710    private static List<String> getAllInstructionSets() {
4711        final String[] allAbis = Build.SUPPORTED_ABIS;
4712        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4713
4714        for (String abi : allAbis) {
4715            final String instructionSet = VMRuntime.getInstructionSet(abi);
4716            if (!allInstructionSets.contains(instructionSet)) {
4717                allInstructionSets.add(instructionSet);
4718            }
4719        }
4720
4721        return allInstructionSets;
4722    }
4723
4724    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4725            boolean inclDependencies) {
4726        HashSet<String> done;
4727        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4728            done = new HashSet<String>();
4729            done.add(pkg.packageName);
4730        } else {
4731            done = null;
4732        }
4733        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4734    }
4735
4736    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4737        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4738            Slog.w(TAG, "Unable to update from " + oldPkg.name
4739                    + " to " + newPkg.packageName
4740                    + ": old package not in system partition");
4741            return false;
4742        } else if (mPackages.get(oldPkg.name) != null) {
4743            Slog.w(TAG, "Unable to update from " + oldPkg.name
4744                    + " to " + newPkg.packageName
4745                    + ": old package still exists");
4746            return false;
4747        }
4748        return true;
4749    }
4750
4751    File getDataPathForUser(int userId) {
4752        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4753    }
4754
4755    private File getDataPathForPackage(String packageName, int userId) {
4756        /*
4757         * Until we fully support multiple users, return the directory we
4758         * previously would have. The PackageManagerTests will need to be
4759         * revised when this is changed back..
4760         */
4761        if (userId == 0) {
4762            return new File(mAppDataDir, packageName);
4763        } else {
4764            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4765                + File.separator + packageName);
4766        }
4767    }
4768
4769    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4770        int[] users = sUserManager.getUserIds();
4771        int res = mInstaller.install(packageName, uid, uid, seinfo);
4772        if (res < 0) {
4773            return res;
4774        }
4775        for (int user : users) {
4776            if (user != 0) {
4777                res = mInstaller.createUserData(packageName,
4778                        UserHandle.getUid(user, uid), user, seinfo);
4779                if (res < 0) {
4780                    return res;
4781                }
4782            }
4783        }
4784        return res;
4785    }
4786
4787    private int removeDataDirsLI(String packageName) {
4788        int[] users = sUserManager.getUserIds();
4789        int res = 0;
4790        for (int user : users) {
4791            int resInner = mInstaller.remove(packageName, user);
4792            if (resInner < 0) {
4793                res = resInner;
4794            }
4795        }
4796
4797        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4798        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4799        if (!nativeLibraryFile.delete()) {
4800            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4801        }
4802
4803        return res;
4804    }
4805
4806    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4807            PackageParser.Package changingLib) {
4808        if (file.path != null) {
4809            usesLibraryFiles.add(file.path);
4810            return;
4811        }
4812        PackageParser.Package p = mPackages.get(file.apk);
4813        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4814            // If we are doing this while in the middle of updating a library apk,
4815            // then we need to make sure to use that new apk for determining the
4816            // dependencies here.  (We haven't yet finished committing the new apk
4817            // to the package manager state.)
4818            if (p == null || p.packageName.equals(changingLib.packageName)) {
4819                p = changingLib;
4820            }
4821        }
4822        if (p != null) {
4823            usesLibraryFiles.addAll(p.getAllCodePaths());
4824        }
4825    }
4826
4827    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4828            PackageParser.Package changingLib) {
4829        // We might be upgrading from a version of the platform that did not
4830        // provide per-package native library directories for system apps.
4831        // Fix that up here.
4832        if (isSystemApp(pkg)) {
4833            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4834            setInternalAppNativeLibraryPath(pkg, ps);
4835        }
4836
4837        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4838            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4839            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4840            for (int i=0; i<N; i++) {
4841                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4842                if (file == null) {
4843                    Slog.e(TAG, "Package " + pkg.packageName
4844                            + " requires unavailable shared library "
4845                            + pkg.usesLibraries.get(i) + "; failing!");
4846                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4847                    return false;
4848                }
4849                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4850            }
4851            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4852            for (int i=0; i<N; i++) {
4853                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4854                if (file == null) {
4855                    Slog.w(TAG, "Package " + pkg.packageName
4856                            + " desires unavailable shared library "
4857                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4858                } else {
4859                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4860                }
4861            }
4862            N = usesLibraryFiles.size();
4863            if (N > 0) {
4864                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4865            } else {
4866                pkg.usesLibraryFiles = null;
4867            }
4868        }
4869        return true;
4870    }
4871
4872    private static boolean hasString(List<String> list, List<String> which) {
4873        if (list == null) {
4874            return false;
4875        }
4876        for (int i=list.size()-1; i>=0; i--) {
4877            for (int j=which.size()-1; j>=0; j--) {
4878                if (which.get(j).equals(list.get(i))) {
4879                    return true;
4880                }
4881            }
4882        }
4883        return false;
4884    }
4885
4886    private void updateAllSharedLibrariesLPw() {
4887        for (PackageParser.Package pkg : mPackages.values()) {
4888            updateSharedLibrariesLPw(pkg, null);
4889        }
4890    }
4891
4892    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4893            PackageParser.Package changingPkg) {
4894        ArrayList<PackageParser.Package> res = null;
4895        for (PackageParser.Package pkg : mPackages.values()) {
4896            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4897                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4898                if (res == null) {
4899                    res = new ArrayList<PackageParser.Package>();
4900                }
4901                res.add(pkg);
4902                updateSharedLibrariesLPw(pkg, changingPkg);
4903            }
4904        }
4905        return res;
4906    }
4907
4908    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4909            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4910        final File scanFile = new File(pkg.codePath);
4911        if (pkg.applicationInfo.getCodePath() == null ||
4912                pkg.applicationInfo.getResourcePath() == null) {
4913            // Bail out. The resource and code paths haven't been set.
4914            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4915            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4916            return null;
4917        }
4918
4919        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4920            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4921        }
4922
4923        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4924            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4925        }
4926
4927        if (mCustomResolverComponentName != null &&
4928                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4929            setUpCustomResolverActivity(pkg);
4930        }
4931
4932        if (pkg.packageName.equals("android")) {
4933            synchronized (mPackages) {
4934                if (mAndroidApplication != null) {
4935                    Slog.w(TAG, "*************************************************");
4936                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4937                    Slog.w(TAG, " file=" + scanFile);
4938                    Slog.w(TAG, "*************************************************");
4939                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4940                    return null;
4941                }
4942
4943                // Set up information for our fall-back user intent resolution activity.
4944                mPlatformPackage = pkg;
4945                pkg.mVersionCode = mSdkVersion;
4946                mAndroidApplication = pkg.applicationInfo;
4947
4948                if (!mResolverReplaced) {
4949                    mResolveActivity.applicationInfo = mAndroidApplication;
4950                    mResolveActivity.name = ResolverActivity.class.getName();
4951                    mResolveActivity.packageName = mAndroidApplication.packageName;
4952                    mResolveActivity.processName = "system:ui";
4953                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4954                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4955                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4956                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4957                    mResolveActivity.exported = true;
4958                    mResolveActivity.enabled = true;
4959                    mResolveInfo.activityInfo = mResolveActivity;
4960                    mResolveInfo.priority = 0;
4961                    mResolveInfo.preferredOrder = 0;
4962                    mResolveInfo.match = 0;
4963                    mResolveComponentName = new ComponentName(
4964                            mAndroidApplication.packageName, mResolveActivity.name);
4965                }
4966            }
4967        }
4968
4969        if (DEBUG_PACKAGE_SCANNING) {
4970            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4971                Log.d(TAG, "Scanning package " + pkg.packageName);
4972        }
4973
4974        if (mPackages.containsKey(pkg.packageName)
4975                || mSharedLibraries.containsKey(pkg.packageName)) {
4976            Slog.w(TAG, "Application package " + pkg.packageName
4977                    + " already installed.  Skipping duplicate.");
4978            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4979            return null;
4980        }
4981
4982        // Initialize package source and resource directories
4983        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
4984        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
4985
4986        SharedUserSetting suid = null;
4987        PackageSetting pkgSetting = null;
4988
4989        if (!isSystemApp(pkg)) {
4990            // Only system apps can use these features.
4991            pkg.mOriginalPackages = null;
4992            pkg.mRealPackage = null;
4993            pkg.mAdoptPermissions = null;
4994        }
4995
4996        // writer
4997        synchronized (mPackages) {
4998            if (pkg.mSharedUserId != null) {
4999                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5000                if (suid == null) {
5001                    Slog.w(TAG, "Creating application package " + pkg.packageName
5002                            + " for shared user failed");
5003                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5004                    return null;
5005                }
5006                if (DEBUG_PACKAGE_SCANNING) {
5007                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5008                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5009                                + "): packages=" + suid.packages);
5010                }
5011            }
5012
5013            // Check if we are renaming from an original package name.
5014            PackageSetting origPackage = null;
5015            String realName = null;
5016            if (pkg.mOriginalPackages != null) {
5017                // This package may need to be renamed to a previously
5018                // installed name.  Let's check on that...
5019                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5020                if (pkg.mOriginalPackages.contains(renamed)) {
5021                    // This package had originally been installed as the
5022                    // original name, and we have already taken care of
5023                    // transitioning to the new one.  Just update the new
5024                    // one to continue using the old name.
5025                    realName = pkg.mRealPackage;
5026                    if (!pkg.packageName.equals(renamed)) {
5027                        // Callers into this function may have already taken
5028                        // care of renaming the package; only do it here if
5029                        // it is not already done.
5030                        pkg.setPackageName(renamed);
5031                    }
5032
5033                } else {
5034                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5035                        if ((origPackage = mSettings.peekPackageLPr(
5036                                pkg.mOriginalPackages.get(i))) != null) {
5037                            // We do have the package already installed under its
5038                            // original name...  should we use it?
5039                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5040                                // New package is not compatible with original.
5041                                origPackage = null;
5042                                continue;
5043                            } else if (origPackage.sharedUser != null) {
5044                                // Make sure uid is compatible between packages.
5045                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5046                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5047                                            + " to " + pkg.packageName + ": old uid "
5048                                            + origPackage.sharedUser.name
5049                                            + " differs from " + pkg.mSharedUserId);
5050                                    origPackage = null;
5051                                    continue;
5052                                }
5053                            } else {
5054                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5055                                        + pkg.packageName + " to old name " + origPackage.name);
5056                            }
5057                            break;
5058                        }
5059                    }
5060                }
5061            }
5062
5063            if (mTransferedPackages.contains(pkg.packageName)) {
5064                Slog.w(TAG, "Package " + pkg.packageName
5065                        + " was transferred to another, but its .apk remains");
5066            }
5067
5068            // Just create the setting, don't add it yet. For already existing packages
5069            // the PkgSetting exists already and doesn't have to be created.
5070            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5071                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5072                    pkg.applicationInfo.cpuAbi,
5073                    pkg.applicationInfo.flags, user, false);
5074            if (pkgSetting == null) {
5075                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5076                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5077                return null;
5078            }
5079
5080            if (pkgSetting.origPackage != null) {
5081                // If we are first transitioning from an original package,
5082                // fix up the new package's name now.  We need to do this after
5083                // looking up the package under its new name, so getPackageLP
5084                // can take care of fiddling things correctly.
5085                pkg.setPackageName(origPackage.name);
5086
5087                // File a report about this.
5088                String msg = "New package " + pkgSetting.realName
5089                        + " renamed to replace old package " + pkgSetting.name;
5090                reportSettingsProblem(Log.WARN, msg);
5091
5092                // Make a note of it.
5093                mTransferedPackages.add(origPackage.name);
5094
5095                // No longer need to retain this.
5096                pkgSetting.origPackage = null;
5097            }
5098
5099            if (realName != null) {
5100                // Make a note of it.
5101                mTransferedPackages.add(pkg.packageName);
5102            }
5103
5104            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5105                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5106            }
5107
5108            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5109                // Check all shared libraries and map to their actual file path.
5110                // We only do this here for apps not on a system dir, because those
5111                // are the only ones that can fail an install due to this.  We
5112                // will take care of the system apps by updating all of their
5113                // library paths after the scan is done.
5114                if (!updateSharedLibrariesLPw(pkg, null)) {
5115                    return null;
5116                }
5117            }
5118
5119            if (mFoundPolicyFile) {
5120                SELinuxMMAC.assignSeinfoValue(pkg);
5121            }
5122
5123            pkg.applicationInfo.uid = pkgSetting.appId;
5124            pkg.mExtras = pkgSetting;
5125            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5126                if (!verifySignaturesLP(pkgSetting, pkg)) {
5127                    if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5128                        return null;
5129                    }
5130                    // The signature has changed, but this package is in the system
5131                    // image...  let's recover!
5132                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5133                    // However...  if this package is part of a shared user, but it
5134                    // doesn't match the signature of the shared user, let's fail.
5135                    // What this means is that you can't change the signatures
5136                    // associated with an overall shared user, which doesn't seem all
5137                    // that unreasonable.
5138                    if (pkgSetting.sharedUser != null) {
5139                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5140                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5141                            Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5142                            mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5143                            return null;
5144                        }
5145                    }
5146                    // File a report about this.
5147                    String msg = "System package " + pkg.packageName
5148                        + " signature changed; retaining data.";
5149                    reportSettingsProblem(Log.WARN, msg);
5150                }
5151            } else {
5152                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5153                    Slog.e(TAG, "Package " + pkg.packageName
5154                           + " upgrade keys do not match the previously installed version; ");
5155                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5156                    return null;
5157                } else {
5158                    // signatures may have changed as result of upgrade
5159                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5160                }
5161            }
5162            // Verify that this new package doesn't have any content providers
5163            // that conflict with existing packages.  Only do this if the
5164            // package isn't already installed, since we don't want to break
5165            // things that are installed.
5166            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5167                final int N = pkg.providers.size();
5168                int i;
5169                for (i=0; i<N; i++) {
5170                    PackageParser.Provider p = pkg.providers.get(i);
5171                    if (p.info.authority != null) {
5172                        String names[] = p.info.authority.split(";");
5173                        for (int j = 0; j < names.length; j++) {
5174                            if (mProvidersByAuthority.containsKey(names[j])) {
5175                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5176                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5177                                        " (in package " + pkg.applicationInfo.packageName +
5178                                        ") is already used by "
5179                                        + ((other != null && other.getComponentName() != null)
5180                                                ? other.getComponentName().getPackageName() : "?"));
5181                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5182                                return null;
5183                            }
5184                        }
5185                    }
5186                }
5187            }
5188
5189            if (pkg.mAdoptPermissions != null) {
5190                // This package wants to adopt ownership of permissions from
5191                // another package.
5192                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5193                    final String origName = pkg.mAdoptPermissions.get(i);
5194                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5195                    if (orig != null) {
5196                        if (verifyPackageUpdateLPr(orig, pkg)) {
5197                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5198                                    + pkg.packageName);
5199                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5200                        }
5201                    }
5202                }
5203            }
5204        }
5205
5206        final String pkgName = pkg.packageName;
5207
5208        final long scanFileTime = scanFile.lastModified();
5209        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5210        pkg.applicationInfo.processName = fixProcessName(
5211                pkg.applicationInfo.packageName,
5212                pkg.applicationInfo.processName,
5213                pkg.applicationInfo.uid);
5214
5215        File dataPath;
5216        if (mPlatformPackage == pkg) {
5217            // The system package is special.
5218            dataPath = new File (Environment.getDataDirectory(), "system");
5219            pkg.applicationInfo.dataDir = dataPath.getPath();
5220        } else {
5221            // This is a normal package, need to make its data directory.
5222            dataPath = getDataPathForPackage(pkg.packageName, 0);
5223
5224            boolean uidError = false;
5225
5226            if (dataPath.exists()) {
5227                int currentUid = 0;
5228                try {
5229                    StructStat stat = Os.stat(dataPath.getPath());
5230                    currentUid = stat.st_uid;
5231                } catch (ErrnoException e) {
5232                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5233                }
5234
5235                // If we have mismatched owners for the data path, we have a problem.
5236                if (currentUid != pkg.applicationInfo.uid) {
5237                    boolean recovered = false;
5238                    if (currentUid == 0) {
5239                        // The directory somehow became owned by root.  Wow.
5240                        // This is probably because the system was stopped while
5241                        // installd was in the middle of messing with its libs
5242                        // directory.  Ask installd to fix that.
5243                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5244                                pkg.applicationInfo.uid);
5245                        if (ret >= 0) {
5246                            recovered = true;
5247                            String msg = "Package " + pkg.packageName
5248                                    + " unexpectedly changed to uid 0; recovered to " +
5249                                    + pkg.applicationInfo.uid;
5250                            reportSettingsProblem(Log.WARN, msg);
5251                        }
5252                    }
5253                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5254                            || (scanMode&SCAN_BOOTING) != 0)) {
5255                        // If this is a system app, we can at least delete its
5256                        // current data so the application will still work.
5257                        int ret = removeDataDirsLI(pkgName);
5258                        if (ret >= 0) {
5259                            // TODO: Kill the processes first
5260                            // Old data gone!
5261                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5262                                    ? "System package " : "Third party package ";
5263                            String msg = prefix + pkg.packageName
5264                                    + " has changed from uid: "
5265                                    + currentUid + " to "
5266                                    + pkg.applicationInfo.uid + "; old data erased";
5267                            reportSettingsProblem(Log.WARN, msg);
5268                            recovered = true;
5269
5270                            // And now re-install the app.
5271                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5272                                                   pkg.applicationInfo.seinfo);
5273                            if (ret == -1) {
5274                                // Ack should not happen!
5275                                msg = prefix + pkg.packageName
5276                                        + " could not have data directory re-created after delete.";
5277                                reportSettingsProblem(Log.WARN, msg);
5278                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5279                                return null;
5280                            }
5281                        }
5282                        if (!recovered) {
5283                            mHasSystemUidErrors = true;
5284                        }
5285                    } else if (!recovered) {
5286                        // If we allow this install to proceed, we will be broken.
5287                        // Abort, abort!
5288                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5289                        return null;
5290                    }
5291                    if (!recovered) {
5292                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5293                            + pkg.applicationInfo.uid + "/fs_"
5294                            + currentUid;
5295                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5296                        String msg = "Package " + pkg.packageName
5297                                + " has mismatched uid: "
5298                                + currentUid + " on disk, "
5299                                + pkg.applicationInfo.uid + " in settings";
5300                        // writer
5301                        synchronized (mPackages) {
5302                            mSettings.mReadMessages.append(msg);
5303                            mSettings.mReadMessages.append('\n');
5304                            uidError = true;
5305                            if (!pkgSetting.uidError) {
5306                                reportSettingsProblem(Log.ERROR, msg);
5307                            }
5308                        }
5309                    }
5310                }
5311                pkg.applicationInfo.dataDir = dataPath.getPath();
5312                if (mShouldRestoreconData) {
5313                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5314                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5315                                pkg.applicationInfo.uid);
5316                }
5317            } else {
5318                if (DEBUG_PACKAGE_SCANNING) {
5319                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5320                        Log.v(TAG, "Want this data dir: " + dataPath);
5321                }
5322                //invoke installer to do the actual installation
5323                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5324                                           pkg.applicationInfo.seinfo);
5325                if (ret < 0) {
5326                    // Error from installer
5327                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5328                    return null;
5329                }
5330
5331                if (dataPath.exists()) {
5332                    pkg.applicationInfo.dataDir = dataPath.getPath();
5333                } else {
5334                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5335                    pkg.applicationInfo.dataDir = null;
5336                }
5337            }
5338
5339            /*
5340             * Set the data dir to the default "/data/data/<package name>/lib"
5341             * if we got here without anyone telling us different (e.g., apps
5342             * stored on SD card have their native libraries stored in the ASEC
5343             * container with the APK).
5344             *
5345             * This happens during an upgrade from a package settings file that
5346             * doesn't have a native library path attribute at all.
5347             */
5348            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5349                if (pkgSetting.nativeLibraryPathString == null) {
5350                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5351                } else {
5352                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5353                }
5354            }
5355            pkgSetting.uidError = uidError;
5356        }
5357
5358        final String path = scanFile.getPath();
5359        /* Note: We don't want to unpack the native binaries for
5360         *        system applications, unless they have been updated
5361         *        (the binaries are already under /system/lib).
5362         *        Also, don't unpack libs for apps on the external card
5363         *        since they should have their libraries in the ASEC
5364         *        container already.
5365         *
5366         *        In other words, we're going to unpack the binaries
5367         *        only for non-system apps and system app upgrades.
5368         */
5369        if (pkg.applicationInfo.nativeLibraryDir != null) {
5370            NativeLibraryHelper.Handle handle = null;
5371            try {
5372                handle = NativeLibraryHelper.Handle.create(scanFile);
5373                // Enable gross and lame hacks for apps that are built with old
5374                // SDK tools. We must scan their APKs for renderscript bitcode and
5375                // not launch them if it's present. Don't bother checking on devices
5376                // that don't have 64 bit support.
5377                String[] abiList = Build.SUPPORTED_ABIS;
5378                boolean hasLegacyRenderscriptBitcode = false;
5379                if (abiOverride != null) {
5380                    abiList = new String[] { abiOverride };
5381                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5382                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5383                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5384                    hasLegacyRenderscriptBitcode = true;
5385                }
5386
5387                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5388                final String dataPathString = dataPath.getCanonicalPath();
5389
5390                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5391                    /*
5392                     * Upgrading from a previous version of the OS sometimes
5393                     * leaves native libraries in the /data/data/<app>/lib
5394                     * directory for system apps even when they shouldn't be.
5395                     * Recent changes in the JNI library search path
5396                     * necessitates we remove those to match previous behavior.
5397                     */
5398                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5399                        Log.i(TAG, "removed obsolete native libraries for system package "
5400                                + path);
5401                    }
5402                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5403                        pkg.applicationInfo.cpuAbi = abiList[0];
5404                        pkgSetting.cpuAbiString = abiList[0];
5405                    } else {
5406                        setInternalAppAbi(pkg, pkgSetting);
5407                    }
5408                } else {
5409                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5410                        /*
5411                        * Update native library dir if it starts with
5412                        * /data/data
5413                        */
5414                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5415                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5416                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5417                        }
5418
5419                        try {
5420                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5421                                    nativeLibraryDir, abiList);
5422                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5423                                Slog.e(TAG, "Unable to copy native libraries");
5424                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5425                                return null;
5426                            }
5427
5428                            // We've successfully copied native libraries across, so we make a
5429                            // note of what ABI we're using
5430                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5431                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5432                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5433                                pkg.applicationInfo.cpuAbi = abiList[0];
5434                            } else {
5435                                pkg.applicationInfo.cpuAbi = null;
5436                            }
5437                        } catch (IOException e) {
5438                            Slog.e(TAG, "Unable to copy native libraries", e);
5439                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5440                            return null;
5441                        }
5442                    } else {
5443                        // We don't have to copy the shared libraries if we're in the ASEC container
5444                        // but we still need to scan the file to figure out what ABI the app needs.
5445                        //
5446                        // TODO: This duplicates work done in the default container service. It's possible
5447                        // to clean this up but we'll need to change the interface between this service
5448                        // and IMediaContainerService (but doing so will spread this logic out, rather
5449                        // than centralizing it).
5450                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5451                        if (abi >= 0) {
5452                            pkg.applicationInfo.cpuAbi = abiList[abi];
5453                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5454                            // Note that (non upgraded) system apps will not have any native
5455                            // libraries bundled in their APK, but we're guaranteed not to be
5456                            // such an app at this point.
5457                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5458                                pkg.applicationInfo.cpuAbi = abiList[0];
5459                            } else {
5460                                pkg.applicationInfo.cpuAbi = null;
5461                            }
5462                        } else {
5463                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5464                            return null;
5465                        }
5466                    }
5467
5468                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5469                    final int[] userIds = sUserManager.getUserIds();
5470                    synchronized (mInstallLock) {
5471                        for (int userId : userIds) {
5472                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5473                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5474                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5475                                        + ")");
5476                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5477                                return null;
5478                            }
5479                        }
5480                    }
5481                }
5482
5483                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5484            } catch (IOException ioe) {
5485                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5486            } finally {
5487                IoUtils.closeQuietly(handle);
5488            }
5489        }
5490
5491        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5492            // We don't do this here during boot because we can do it all
5493            // at once after scanning all existing packages.
5494            //
5495            // We also do this *before* we perform dexopt on this package, so that
5496            // we can avoid redundant dexopts, and also to make sure we've got the
5497            // code and package path correct.
5498            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5499                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5500                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5501                return null;
5502            }
5503        }
5504
5505        if ((scanMode&SCAN_NO_DEX) == 0) {
5506            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5507                    == DEX_OPT_FAILED) {
5508                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5509                    removeDataDirsLI(pkg.packageName);
5510                }
5511
5512                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5513                return null;
5514            }
5515        }
5516
5517        if (mFactoryTest && pkg.requestedPermissions.contains(
5518                android.Manifest.permission.FACTORY_TEST)) {
5519            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5520        }
5521
5522        ArrayList<PackageParser.Package> clientLibPkgs = null;
5523
5524        // writer
5525        synchronized (mPackages) {
5526            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5527                // Only system apps can add new shared libraries.
5528                if (pkg.libraryNames != null) {
5529                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5530                        String name = pkg.libraryNames.get(i);
5531                        boolean allowed = false;
5532                        if (isUpdatedSystemApp(pkg)) {
5533                            // New library entries can only be added through the
5534                            // system image.  This is important to get rid of a lot
5535                            // of nasty edge cases: for example if we allowed a non-
5536                            // system update of the app to add a library, then uninstalling
5537                            // the update would make the library go away, and assumptions
5538                            // we made such as through app install filtering would now
5539                            // have allowed apps on the device which aren't compatible
5540                            // with it.  Better to just have the restriction here, be
5541                            // conservative, and create many fewer cases that can negatively
5542                            // impact the user experience.
5543                            final PackageSetting sysPs = mSettings
5544                                    .getDisabledSystemPkgLPr(pkg.packageName);
5545                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5546                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5547                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5548                                        allowed = true;
5549                                        allowed = true;
5550                                        break;
5551                                    }
5552                                }
5553                            }
5554                        } else {
5555                            allowed = true;
5556                        }
5557                        if (allowed) {
5558                            if (!mSharedLibraries.containsKey(name)) {
5559                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5560                            } else if (!name.equals(pkg.packageName)) {
5561                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5562                                        + name + " already exists; skipping");
5563                            }
5564                        } else {
5565                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5566                                    + name + " that is not declared on system image; skipping");
5567                        }
5568                    }
5569                    if ((scanMode&SCAN_BOOTING) == 0) {
5570                        // If we are not booting, we need to update any applications
5571                        // that are clients of our shared library.  If we are booting,
5572                        // this will all be done once the scan is complete.
5573                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5574                    }
5575                }
5576            }
5577        }
5578
5579        // We also need to dexopt any apps that are dependent on this library.  Note that
5580        // if these fail, we should abort the install since installing the library will
5581        // result in some apps being broken.
5582        if (clientLibPkgs != null) {
5583            if ((scanMode&SCAN_NO_DEX) == 0) {
5584                for (int i=0; i<clientLibPkgs.size(); i++) {
5585                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5586                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5587                            == DEX_OPT_FAILED) {
5588                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5589                            removeDataDirsLI(pkg.packageName);
5590                        }
5591
5592                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5593                        return null;
5594                    }
5595                }
5596            }
5597        }
5598
5599        // Request the ActivityManager to kill the process(only for existing packages)
5600        // so that we do not end up in a confused state while the user is still using the older
5601        // version of the application while the new one gets installed.
5602        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5603            // If the package lives in an asec, tell everyone that the container is going
5604            // away so they can clean up any references to its resources (which would prevent
5605            // vold from being able to unmount the asec)
5606            if (isForwardLocked(pkg) || isExternal(pkg)) {
5607                if (DEBUG_INSTALL) {
5608                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5609                }
5610                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5611                final ArrayList<String> pkgList = new ArrayList<String>(1);
5612                pkgList.add(pkg.applicationInfo.packageName);
5613                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5614            }
5615
5616            // Post the request that it be killed now that the going-away broadcast is en route
5617            killApplication(pkg.applicationInfo.packageName,
5618                        pkg.applicationInfo.uid, "update pkg");
5619        }
5620
5621        // Also need to kill any apps that are dependent on the library.
5622        if (clientLibPkgs != null) {
5623            for (int i=0; i<clientLibPkgs.size(); i++) {
5624                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5625                killApplication(clientPkg.applicationInfo.packageName,
5626                        clientPkg.applicationInfo.uid, "update lib");
5627            }
5628        }
5629
5630        // writer
5631        synchronized (mPackages) {
5632            // We don't expect installation to fail beyond this point,
5633            if ((scanMode&SCAN_MONITOR) != 0) {
5634                mAppDirs.put(pkg.codePath, pkg);
5635            }
5636            // Add the new setting to mSettings
5637            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5638            // Add the new setting to mPackages
5639            mPackages.put(pkg.applicationInfo.packageName, pkg);
5640            // Make sure we don't accidentally delete its data.
5641            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5642            while (iter.hasNext()) {
5643                PackageCleanItem item = iter.next();
5644                if (pkgName.equals(item.packageName)) {
5645                    iter.remove();
5646                }
5647            }
5648
5649            // Take care of first install / last update times.
5650            if (currentTime != 0) {
5651                if (pkgSetting.firstInstallTime == 0) {
5652                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5653                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5654                    pkgSetting.lastUpdateTime = currentTime;
5655                }
5656            } else if (pkgSetting.firstInstallTime == 0) {
5657                // We need *something*.  Take time time stamp of the file.
5658                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5659            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5660                if (scanFileTime != pkgSetting.timeStamp) {
5661                    // A package on the system image has changed; consider this
5662                    // to be an update.
5663                    pkgSetting.lastUpdateTime = scanFileTime;
5664                }
5665            }
5666
5667            // Add the package's KeySets to the global KeySetManagerService
5668            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5669            try {
5670                // Old KeySetData no longer valid.
5671                ksms.removeAppKeySetData(pkg.packageName);
5672                ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5673                if (pkg.mKeySetMapping != null) {
5674                    for (Map.Entry<String, Set<PublicKey>> entry :
5675                            pkg.mKeySetMapping.entrySet()) {
5676                        if (entry.getValue() != null) {
5677                            ksms.addDefinedKeySetToPackage(pkg.packageName,
5678                                                          entry.getValue(), entry.getKey());
5679                        }
5680                    }
5681                    if (pkg.mUpgradeKeySets != null
5682                            && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) {
5683                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5684                            ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias);
5685                        }
5686                    }
5687                }
5688            } catch (NullPointerException e) {
5689                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5690            } catch (IllegalArgumentException e) {
5691                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5692            }
5693
5694            int N = pkg.providers.size();
5695            StringBuilder r = null;
5696            int i;
5697            for (i=0; i<N; i++) {
5698                PackageParser.Provider p = pkg.providers.get(i);
5699                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5700                        p.info.processName, pkg.applicationInfo.uid);
5701                mProviders.addProvider(p);
5702                p.syncable = p.info.isSyncable;
5703                if (p.info.authority != null) {
5704                    String names[] = p.info.authority.split(";");
5705                    p.info.authority = null;
5706                    for (int j = 0; j < names.length; j++) {
5707                        if (j == 1 && p.syncable) {
5708                            // We only want the first authority for a provider to possibly be
5709                            // syncable, so if we already added this provider using a different
5710                            // authority clear the syncable flag. We copy the provider before
5711                            // changing it because the mProviders object contains a reference
5712                            // to a provider that we don't want to change.
5713                            // Only do this for the second authority since the resulting provider
5714                            // object can be the same for all future authorities for this provider.
5715                            p = new PackageParser.Provider(p);
5716                            p.syncable = false;
5717                        }
5718                        if (!mProvidersByAuthority.containsKey(names[j])) {
5719                            mProvidersByAuthority.put(names[j], p);
5720                            if (p.info.authority == null) {
5721                                p.info.authority = names[j];
5722                            } else {
5723                                p.info.authority = p.info.authority + ";" + names[j];
5724                            }
5725                            if (DEBUG_PACKAGE_SCANNING) {
5726                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5727                                    Log.d(TAG, "Registered content provider: " + names[j]
5728                                            + ", className = " + p.info.name + ", isSyncable = "
5729                                            + p.info.isSyncable);
5730                            }
5731                        } else {
5732                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5733                            Slog.w(TAG, "Skipping provider name " + names[j] +
5734                                    " (in package " + pkg.applicationInfo.packageName +
5735                                    "): name already used by "
5736                                    + ((other != null && other.getComponentName() != null)
5737                                            ? other.getComponentName().getPackageName() : "?"));
5738                        }
5739                    }
5740                }
5741                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5742                    if (r == null) {
5743                        r = new StringBuilder(256);
5744                    } else {
5745                        r.append(' ');
5746                    }
5747                    r.append(p.info.name);
5748                }
5749            }
5750            if (r != null) {
5751                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5752            }
5753
5754            N = pkg.services.size();
5755            r = null;
5756            for (i=0; i<N; i++) {
5757                PackageParser.Service s = pkg.services.get(i);
5758                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5759                        s.info.processName, pkg.applicationInfo.uid);
5760                mServices.addService(s);
5761                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5762                    if (r == null) {
5763                        r = new StringBuilder(256);
5764                    } else {
5765                        r.append(' ');
5766                    }
5767                    r.append(s.info.name);
5768                }
5769            }
5770            if (r != null) {
5771                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5772            }
5773
5774            N = pkg.receivers.size();
5775            r = null;
5776            for (i=0; i<N; i++) {
5777                PackageParser.Activity a = pkg.receivers.get(i);
5778                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5779                        a.info.processName, pkg.applicationInfo.uid);
5780                mReceivers.addActivity(a, "receiver");
5781                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5782                    if (r == null) {
5783                        r = new StringBuilder(256);
5784                    } else {
5785                        r.append(' ');
5786                    }
5787                    r.append(a.info.name);
5788                }
5789            }
5790            if (r != null) {
5791                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5792            }
5793
5794            N = pkg.activities.size();
5795            r = null;
5796            for (i=0; i<N; i++) {
5797                PackageParser.Activity a = pkg.activities.get(i);
5798                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5799                        a.info.processName, pkg.applicationInfo.uid);
5800                mActivities.addActivity(a, "activity");
5801                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5802                    if (r == null) {
5803                        r = new StringBuilder(256);
5804                    } else {
5805                        r.append(' ');
5806                    }
5807                    r.append(a.info.name);
5808                }
5809            }
5810            if (r != null) {
5811                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5812            }
5813
5814            N = pkg.permissionGroups.size();
5815            r = null;
5816            for (i=0; i<N; i++) {
5817                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5818                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5819                if (cur == null) {
5820                    mPermissionGroups.put(pg.info.name, pg);
5821                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5822                        if (r == null) {
5823                            r = new StringBuilder(256);
5824                        } else {
5825                            r.append(' ');
5826                        }
5827                        r.append(pg.info.name);
5828                    }
5829                } else {
5830                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5831                            + pg.info.packageName + " ignored: original from "
5832                            + cur.info.packageName);
5833                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5834                        if (r == null) {
5835                            r = new StringBuilder(256);
5836                        } else {
5837                            r.append(' ');
5838                        }
5839                        r.append("DUP:");
5840                        r.append(pg.info.name);
5841                    }
5842                }
5843            }
5844            if (r != null) {
5845                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5846            }
5847
5848            N = pkg.permissions.size();
5849            r = null;
5850            for (i=0; i<N; i++) {
5851                PackageParser.Permission p = pkg.permissions.get(i);
5852                HashMap<String, BasePermission> permissionMap =
5853                        p.tree ? mSettings.mPermissionTrees
5854                        : mSettings.mPermissions;
5855                p.group = mPermissionGroups.get(p.info.group);
5856                if (p.info.group == null || p.group != null) {
5857                    BasePermission bp = permissionMap.get(p.info.name);
5858                    if (bp == null) {
5859                        bp = new BasePermission(p.info.name, p.info.packageName,
5860                                BasePermission.TYPE_NORMAL);
5861                        permissionMap.put(p.info.name, bp);
5862                    }
5863                    if (bp.perm == null) {
5864                        if (bp.sourcePackage != null
5865                                && !bp.sourcePackage.equals(p.info.packageName)) {
5866                            // If this is a permission that was formerly defined by a non-system
5867                            // app, but is now defined by a system app (following an upgrade),
5868                            // discard the previous declaration and consider the system's to be
5869                            // canonical.
5870                            if (isSystemApp(p.owner)) {
5871                                String msg = "New decl " + p.owner + " of permission  "
5872                                        + p.info.name + " is system";
5873                                reportSettingsProblem(Log.WARN, msg);
5874                                bp.sourcePackage = null;
5875                            }
5876                        }
5877                        if (bp.sourcePackage == null
5878                                || bp.sourcePackage.equals(p.info.packageName)) {
5879                            BasePermission tree = findPermissionTreeLP(p.info.name);
5880                            if (tree == null
5881                                    || tree.sourcePackage.equals(p.info.packageName)) {
5882                                bp.packageSetting = pkgSetting;
5883                                bp.perm = p;
5884                                bp.uid = pkg.applicationInfo.uid;
5885                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5886                                    if (r == null) {
5887                                        r = new StringBuilder(256);
5888                                    } else {
5889                                        r.append(' ');
5890                                    }
5891                                    r.append(p.info.name);
5892                                }
5893                            } else {
5894                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5895                                        + p.info.packageName + " ignored: base tree "
5896                                        + tree.name + " is from package "
5897                                        + tree.sourcePackage);
5898                            }
5899                        } else {
5900                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5901                                    + p.info.packageName + " ignored: original from "
5902                                    + bp.sourcePackage);
5903                        }
5904                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5905                        if (r == null) {
5906                            r = new StringBuilder(256);
5907                        } else {
5908                            r.append(' ');
5909                        }
5910                        r.append("DUP:");
5911                        r.append(p.info.name);
5912                    }
5913                    if (bp.perm == p) {
5914                        bp.protectionLevel = p.info.protectionLevel;
5915                    }
5916                } else {
5917                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5918                            + p.info.packageName + " ignored: no group "
5919                            + p.group);
5920                }
5921            }
5922            if (r != null) {
5923                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5924            }
5925
5926            N = pkg.instrumentation.size();
5927            r = null;
5928            for (i=0; i<N; i++) {
5929                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5930                a.info.packageName = pkg.applicationInfo.packageName;
5931                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5932                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5933                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5934                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5935                a.info.dataDir = pkg.applicationInfo.dataDir;
5936                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5937                mInstrumentation.put(a.getComponentName(), a);
5938                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5939                    if (r == null) {
5940                        r = new StringBuilder(256);
5941                    } else {
5942                        r.append(' ');
5943                    }
5944                    r.append(a.info.name);
5945                }
5946            }
5947            if (r != null) {
5948                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5949            }
5950
5951            if (pkg.protectedBroadcasts != null) {
5952                N = pkg.protectedBroadcasts.size();
5953                for (i=0; i<N; i++) {
5954                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5955                }
5956            }
5957
5958            pkgSetting.setTimeStamp(scanFileTime);
5959
5960            // Create idmap files for pairs of (packages, overlay packages).
5961            // Note: "android", ie framework-res.apk, is handled by native layers.
5962            if (pkg.mOverlayTarget != null) {
5963                // This is an overlay package.
5964                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5965                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5966                        mOverlays.put(pkg.mOverlayTarget,
5967                                new HashMap<String, PackageParser.Package>());
5968                    }
5969                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5970                    map.put(pkg.packageName, pkg);
5971                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5972                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5973                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5974                        return null;
5975                    }
5976                }
5977            } else if (mOverlays.containsKey(pkg.packageName) &&
5978                    !pkg.packageName.equals("android")) {
5979                // This is a regular package, with one or more known overlay packages.
5980                createIdmapsForPackageLI(pkg);
5981            }
5982        }
5983
5984        return pkg;
5985    }
5986
5987    /**
5988     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5989     * i.e, so that all packages can be run inside a single process if required.
5990     *
5991     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5992     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5993     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5994     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5995     * updating a package that belongs to a shared user.
5996     */
5997    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5998            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5999        String requiredInstructionSet = null;
6000        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
6001            requiredInstructionSet = VMRuntime.getInstructionSet(
6002                     scannedPackage.applicationInfo.cpuAbi);
6003        }
6004
6005        PackageSetting requirer = null;
6006        for (PackageSetting ps : packagesForUser) {
6007            // If packagesForUser contains scannedPackage, we skip it. This will happen
6008            // when scannedPackage is an update of an existing package. Without this check,
6009            // we will never be able to change the ABI of any package belonging to a shared
6010            // user, even if it's compatible with other packages.
6011            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6012                if (ps.cpuAbiString == null) {
6013                    continue;
6014                }
6015
6016                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6017                if (requiredInstructionSet != null) {
6018                    if (!instructionSet.equals(requiredInstructionSet)) {
6019                        // We have a mismatch between instruction sets (say arm vs arm64).
6020                        // bail out.
6021                        String errorMessage = "Instruction set mismatch, "
6022                                + ((requirer == null) ? "[caller]" : requirer)
6023                                + " requires " + requiredInstructionSet + " whereas " + ps
6024                                + " requires " + instructionSet;
6025                        Slog.e(TAG, errorMessage);
6026
6027                        reportSettingsProblem(Log.WARN, errorMessage);
6028                        // Give up, don't bother making any other changes to the package settings.
6029                        return false;
6030                    }
6031                } else {
6032                    requiredInstructionSet = instructionSet;
6033                    requirer = ps;
6034                }
6035            }
6036        }
6037
6038        if (requiredInstructionSet != null) {
6039            String adjustedAbi;
6040            if (requirer != null) {
6041                // requirer != null implies that either scannedPackage was null or that scannedPackage
6042                // did not require an ABI, in which case we have to adjust scannedPackage to match
6043                // the ABI of the set (which is the same as requirer's ABI)
6044                adjustedAbi = requirer.cpuAbiString;
6045                if (scannedPackage != null) {
6046                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6047                }
6048            } else {
6049                // requirer == null implies that we're updating all ABIs in the set to
6050                // match scannedPackage.
6051                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6052            }
6053
6054            for (PackageSetting ps : packagesForUser) {
6055                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6056                    if (ps.cpuAbiString != null) {
6057                        continue;
6058                    }
6059
6060                    ps.cpuAbiString = adjustedAbi;
6061                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6062                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6063                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6064
6065                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6066                            ps.cpuAbiString = null;
6067                            ps.pkg.applicationInfo.cpuAbi = null;
6068                            return false;
6069                        } else {
6070                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6071                        }
6072                    }
6073                }
6074            }
6075        }
6076
6077        return true;
6078    }
6079
6080    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6081        synchronized (mPackages) {
6082            mResolverReplaced = true;
6083            // Set up information for custom user intent resolution activity.
6084            mResolveActivity.applicationInfo = pkg.applicationInfo;
6085            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6086            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6087            mResolveActivity.processName = null;
6088            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6089            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6090                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6091            mResolveActivity.theme = 0;
6092            mResolveActivity.exported = true;
6093            mResolveActivity.enabled = true;
6094            mResolveInfo.activityInfo = mResolveActivity;
6095            mResolveInfo.priority = 0;
6096            mResolveInfo.preferredOrder = 0;
6097            mResolveInfo.match = 0;
6098            mResolveComponentName = mCustomResolverComponentName;
6099            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6100                    mResolveComponentName);
6101        }
6102    }
6103
6104    private String calculateApkRoot(final String codePathString) {
6105        final File codePath = new File(codePathString);
6106        final File codeRoot;
6107        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6108            codeRoot = Environment.getRootDirectory();
6109        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6110            codeRoot = Environment.getOemDirectory();
6111        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6112            codeRoot = Environment.getVendorDirectory();
6113        } else {
6114            // Unrecognized code path; take its top real segment as the apk root:
6115            // e.g. /something/app/blah.apk => /something
6116            try {
6117                File f = codePath.getCanonicalFile();
6118                File parent = f.getParentFile();    // non-null because codePath is a file
6119                File tmp;
6120                while ((tmp = parent.getParentFile()) != null) {
6121                    f = parent;
6122                    parent = tmp;
6123                }
6124                codeRoot = f;
6125                Slog.w(TAG, "Unrecognized code path "
6126                        + codePath + " - using " + codeRoot);
6127            } catch (IOException e) {
6128                // Can't canonicalize the lib path -- shenanigans?
6129                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6130                return Environment.getRootDirectory().getPath();
6131            }
6132        }
6133        return codeRoot.getPath();
6134    }
6135
6136    // This is the initial scan-time determination of how to handle a given
6137    // package for purposes of native library location.
6138    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6139            PackageSetting pkgSetting) {
6140        // "bundled" here means system-installed with no overriding update
6141        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6142        final File codeFile = new File(pkg.applicationInfo.getCodePath());
6143        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6144
6145        String nativeLibraryPath = null;
6146        if (bundledApk) {
6147            // If "/system/lib64/apkname" exists, assume that is the per-package
6148            // native library directory to use; otherwise use "/system/lib/apkname".
6149            String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath());
6150            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6151            File packLib64 = new File(lib64, apkName);
6152            File libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6153            nativeLibraryPath = (new File(libDir, apkName)).getAbsolutePath();
6154        } else {
6155            // Upgraded system app; derive its library path by inspecting.
6156            // TODO: pipe through abiOverride
6157            String[] abiList = Build.SUPPORTED_ABIS;
6158            NativeLibraryHelper.Handle handle = null;
6159            try {
6160                handle = NativeLibraryHelper.Handle.create(codeFile);
6161                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
6162                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
6163                    abiList = Build.SUPPORTED_32_BIT_ABIS;
6164                }
6165
6166                final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6167                if (abiIndex >= 0) {
6168                    final File baseLibFile = new File(codeFile, LIB_DIR_NAME);
6169                    final String abi = Build.SUPPORTED_ABIS[abiIndex];
6170                    final String instructionSet = VMRuntime.getInstructionSet(abi);
6171                    nativeLibraryPath = new File(baseLibFile, instructionSet).getAbsolutePath();
6172                }
6173            } catch (IOException e) {
6174                Slog.e(TAG, "Failed to detect native libraries", e);
6175            } finally {
6176                IoUtils.closeQuietly(handle);
6177            }
6178        }
6179        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6180        // pkgSetting might be null during rescan following uninstall of updates
6181        // to a bundled app, so accommodate that possibility.  The settings in
6182        // that case will be established later from the parsed package.
6183        if (pkgSetting != null) {
6184            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6185        }
6186    }
6187
6188    // Deduces the required ABI of an upgraded system app.
6189    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6190        final String apkRoot = calculateApkRoot(pkg.applicationInfo.getCodePath());
6191        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6192
6193        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6194        // or similar.
6195        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6196        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6197
6198        // Assume that the bundled native libraries always correspond to the
6199        // most preferred 32 or 64 bit ABI.
6200        if (lib64.exists()) {
6201            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6202            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6203        } else if (lib.exists()) {
6204            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6205            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6206        } else {
6207            // This is the case where the app has no native code.
6208            pkg.applicationInfo.cpuAbi = null;
6209            pkgSetting.cpuAbiString = null;
6210        }
6211    }
6212
6213    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6214            final File nativeLibraryDir, String[] abiList) throws IOException {
6215        if (!nativeLibraryDir.isDirectory()) {
6216            nativeLibraryDir.delete();
6217
6218            if (!nativeLibraryDir.mkdir()) {
6219                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6220            }
6221
6222            try {
6223                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6224            } catch (ErrnoException e) {
6225                throw new IOException("Cannot chmod native library directory "
6226                        + nativeLibraryDir.getPath(), e);
6227            }
6228        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6229            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6230        }
6231
6232        /*
6233         * If this is an internal application or our nativeLibraryPath points to
6234         * the app-lib directory, unpack the libraries if necessary.
6235         */
6236        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6237        if (abi >= 0) {
6238            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6239                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6240            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6241                return copyRet;
6242            }
6243        }
6244
6245        return abi;
6246    }
6247
6248    private void killApplication(String pkgName, int appId, String reason) {
6249        // Request the ActivityManager to kill the process(only for existing packages)
6250        // so that we do not end up in a confused state while the user is still using the older
6251        // version of the application while the new one gets installed.
6252        IActivityManager am = ActivityManagerNative.getDefault();
6253        if (am != null) {
6254            try {
6255                am.killApplicationWithAppId(pkgName, appId, reason);
6256            } catch (RemoteException e) {
6257            }
6258        }
6259    }
6260
6261    void removePackageLI(PackageSetting ps, boolean chatty) {
6262        if (DEBUG_INSTALL) {
6263            if (chatty)
6264                Log.d(TAG, "Removing package " + ps.name);
6265        }
6266
6267        // writer
6268        synchronized (mPackages) {
6269            mPackages.remove(ps.name);
6270            if (ps.codePathString != null) {
6271                mAppDirs.remove(ps.codePathString);
6272            }
6273
6274            final PackageParser.Package pkg = ps.pkg;
6275            if (pkg != null) {
6276                cleanPackageDataStructuresLILPw(pkg, chatty);
6277            }
6278        }
6279    }
6280
6281    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6282        if (DEBUG_INSTALL) {
6283            if (chatty)
6284                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6285        }
6286
6287        // writer
6288        synchronized (mPackages) {
6289            mPackages.remove(pkg.applicationInfo.packageName);
6290            if (pkg.codePath != null) {
6291                mAppDirs.remove(pkg.codePath);
6292            }
6293            cleanPackageDataStructuresLILPw(pkg, chatty);
6294        }
6295    }
6296
6297    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6298        int N = pkg.providers.size();
6299        StringBuilder r = null;
6300        int i;
6301        for (i=0; i<N; i++) {
6302            PackageParser.Provider p = pkg.providers.get(i);
6303            mProviders.removeProvider(p);
6304            if (p.info.authority == null) {
6305
6306                /* There was another ContentProvider with this authority when
6307                 * this app was installed so this authority is null,
6308                 * Ignore it as we don't have to unregister the provider.
6309                 */
6310                continue;
6311            }
6312            String names[] = p.info.authority.split(";");
6313            for (int j = 0; j < names.length; j++) {
6314                if (mProvidersByAuthority.get(names[j]) == p) {
6315                    mProvidersByAuthority.remove(names[j]);
6316                    if (DEBUG_REMOVE) {
6317                        if (chatty)
6318                            Log.d(TAG, "Unregistered content provider: " + names[j]
6319                                    + ", className = " + p.info.name + ", isSyncable = "
6320                                    + p.info.isSyncable);
6321                    }
6322                }
6323            }
6324            if (DEBUG_REMOVE && chatty) {
6325                if (r == null) {
6326                    r = new StringBuilder(256);
6327                } else {
6328                    r.append(' ');
6329                }
6330                r.append(p.info.name);
6331            }
6332        }
6333        if (r != null) {
6334            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6335        }
6336
6337        N = pkg.services.size();
6338        r = null;
6339        for (i=0; i<N; i++) {
6340            PackageParser.Service s = pkg.services.get(i);
6341            mServices.removeService(s);
6342            if (chatty) {
6343                if (r == null) {
6344                    r = new StringBuilder(256);
6345                } else {
6346                    r.append(' ');
6347                }
6348                r.append(s.info.name);
6349            }
6350        }
6351        if (r != null) {
6352            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6353        }
6354
6355        N = pkg.receivers.size();
6356        r = null;
6357        for (i=0; i<N; i++) {
6358            PackageParser.Activity a = pkg.receivers.get(i);
6359            mReceivers.removeActivity(a, "receiver");
6360            if (DEBUG_REMOVE && chatty) {
6361                if (r == null) {
6362                    r = new StringBuilder(256);
6363                } else {
6364                    r.append(' ');
6365                }
6366                r.append(a.info.name);
6367            }
6368        }
6369        if (r != null) {
6370            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6371        }
6372
6373        N = pkg.activities.size();
6374        r = null;
6375        for (i=0; i<N; i++) {
6376            PackageParser.Activity a = pkg.activities.get(i);
6377            mActivities.removeActivity(a, "activity");
6378            if (DEBUG_REMOVE && chatty) {
6379                if (r == null) {
6380                    r = new StringBuilder(256);
6381                } else {
6382                    r.append(' ');
6383                }
6384                r.append(a.info.name);
6385            }
6386        }
6387        if (r != null) {
6388            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6389        }
6390
6391        N = pkg.permissions.size();
6392        r = null;
6393        for (i=0; i<N; i++) {
6394            PackageParser.Permission p = pkg.permissions.get(i);
6395            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6396            if (bp == null) {
6397                bp = mSettings.mPermissionTrees.get(p.info.name);
6398            }
6399            if (bp != null && bp.perm == p) {
6400                bp.perm = null;
6401                if (DEBUG_REMOVE && chatty) {
6402                    if (r == null) {
6403                        r = new StringBuilder(256);
6404                    } else {
6405                        r.append(' ');
6406                    }
6407                    r.append(p.info.name);
6408                }
6409            }
6410        }
6411        if (r != null) {
6412            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6413        }
6414
6415        N = pkg.instrumentation.size();
6416        r = null;
6417        for (i=0; i<N; i++) {
6418            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6419            mInstrumentation.remove(a.getComponentName());
6420            if (DEBUG_REMOVE && chatty) {
6421                if (r == null) {
6422                    r = new StringBuilder(256);
6423                } else {
6424                    r.append(' ');
6425                }
6426                r.append(a.info.name);
6427            }
6428        }
6429        if (r != null) {
6430            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6431        }
6432
6433        r = null;
6434        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6435            // Only system apps can hold shared libraries.
6436            if (pkg.libraryNames != null) {
6437                for (i=0; i<pkg.libraryNames.size(); i++) {
6438                    String name = pkg.libraryNames.get(i);
6439                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6440                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6441                        mSharedLibraries.remove(name);
6442                        if (DEBUG_REMOVE && chatty) {
6443                            if (r == null) {
6444                                r = new StringBuilder(256);
6445                            } else {
6446                                r.append(' ');
6447                            }
6448                            r.append(name);
6449                        }
6450                    }
6451                }
6452            }
6453        }
6454        if (r != null) {
6455            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6456        }
6457    }
6458
6459    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6460        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6461            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6462                return true;
6463            }
6464        }
6465        return false;
6466    }
6467
6468    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6469    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6470    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6471
6472    private void updatePermissionsLPw(String changingPkg,
6473            PackageParser.Package pkgInfo, int flags) {
6474        // Make sure there are no dangling permission trees.
6475        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6476        while (it.hasNext()) {
6477            final BasePermission bp = it.next();
6478            if (bp.packageSetting == null) {
6479                // We may not yet have parsed the package, so just see if
6480                // we still know about its settings.
6481                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6482            }
6483            if (bp.packageSetting == null) {
6484                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6485                        + " from package " + bp.sourcePackage);
6486                it.remove();
6487            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6488                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6489                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6490                            + " from package " + bp.sourcePackage);
6491                    flags |= UPDATE_PERMISSIONS_ALL;
6492                    it.remove();
6493                }
6494            }
6495        }
6496
6497        // Make sure all dynamic permissions have been assigned to a package,
6498        // and make sure there are no dangling permissions.
6499        it = mSettings.mPermissions.values().iterator();
6500        while (it.hasNext()) {
6501            final BasePermission bp = it.next();
6502            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6503                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6504                        + bp.name + " pkg=" + bp.sourcePackage
6505                        + " info=" + bp.pendingInfo);
6506                if (bp.packageSetting == null && bp.pendingInfo != null) {
6507                    final BasePermission tree = findPermissionTreeLP(bp.name);
6508                    if (tree != null && tree.perm != null) {
6509                        bp.packageSetting = tree.packageSetting;
6510                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6511                                new PermissionInfo(bp.pendingInfo));
6512                        bp.perm.info.packageName = tree.perm.info.packageName;
6513                        bp.perm.info.name = bp.name;
6514                        bp.uid = tree.uid;
6515                    }
6516                }
6517            }
6518            if (bp.packageSetting == null) {
6519                // We may not yet have parsed the package, so just see if
6520                // we still know about its settings.
6521                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6522            }
6523            if (bp.packageSetting == null) {
6524                Slog.w(TAG, "Removing dangling permission: " + bp.name
6525                        + " from package " + bp.sourcePackage);
6526                it.remove();
6527            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6528                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6529                    Slog.i(TAG, "Removing old permission: " + bp.name
6530                            + " from package " + bp.sourcePackage);
6531                    flags |= UPDATE_PERMISSIONS_ALL;
6532                    it.remove();
6533                }
6534            }
6535        }
6536
6537        // Now update the permissions for all packages, in particular
6538        // replace the granted permissions of the system packages.
6539        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6540            for (PackageParser.Package pkg : mPackages.values()) {
6541                if (pkg != pkgInfo) {
6542                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6543                }
6544            }
6545        }
6546
6547        if (pkgInfo != null) {
6548            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6549        }
6550    }
6551
6552    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6553        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6554        if (ps == null) {
6555            return;
6556        }
6557        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6558        HashSet<String> origPermissions = gp.grantedPermissions;
6559        boolean changedPermission = false;
6560
6561        if (replace) {
6562            ps.permissionsFixed = false;
6563            if (gp == ps) {
6564                origPermissions = new HashSet<String>(gp.grantedPermissions);
6565                gp.grantedPermissions.clear();
6566                gp.gids = mGlobalGids;
6567            }
6568        }
6569
6570        if (gp.gids == null) {
6571            gp.gids = mGlobalGids;
6572        }
6573
6574        final int N = pkg.requestedPermissions.size();
6575        for (int i=0; i<N; i++) {
6576            final String name = pkg.requestedPermissions.get(i);
6577            final boolean required = pkg.requestedPermissionsRequired.get(i);
6578            final BasePermission bp = mSettings.mPermissions.get(name);
6579            if (DEBUG_INSTALL) {
6580                if (gp != ps) {
6581                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6582                }
6583            }
6584
6585            if (bp == null || bp.packageSetting == null) {
6586                Slog.w(TAG, "Unknown permission " + name
6587                        + " in package " + pkg.packageName);
6588                continue;
6589            }
6590
6591            final String perm = bp.name;
6592            boolean allowed;
6593            boolean allowedSig = false;
6594            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6595            if (level == PermissionInfo.PROTECTION_NORMAL
6596                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6597                // We grant a normal or dangerous permission if any of the following
6598                // are true:
6599                // 1) The permission is required
6600                // 2) The permission is optional, but was granted in the past
6601                // 3) The permission is optional, but was requested by an
6602                //    app in /system (not /data)
6603                //
6604                // Otherwise, reject the permission.
6605                allowed = (required || origPermissions.contains(perm)
6606                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6607            } else if (bp.packageSetting == null) {
6608                // This permission is invalid; skip it.
6609                allowed = false;
6610            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6611                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6612                if (allowed) {
6613                    allowedSig = true;
6614                }
6615            } else {
6616                allowed = false;
6617            }
6618            if (DEBUG_INSTALL) {
6619                if (gp != ps) {
6620                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6621                }
6622            }
6623            if (allowed) {
6624                if (!isSystemApp(ps) && ps.permissionsFixed) {
6625                    // If this is an existing, non-system package, then
6626                    // we can't add any new permissions to it.
6627                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6628                        // Except...  if this is a permission that was added
6629                        // to the platform (note: need to only do this when
6630                        // updating the platform).
6631                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6632                    }
6633                }
6634                if (allowed) {
6635                    if (!gp.grantedPermissions.contains(perm)) {
6636                        changedPermission = true;
6637                        gp.grantedPermissions.add(perm);
6638                        gp.gids = appendInts(gp.gids, bp.gids);
6639                    } else if (!ps.haveGids) {
6640                        gp.gids = appendInts(gp.gids, bp.gids);
6641                    }
6642                } else {
6643                    Slog.w(TAG, "Not granting permission " + perm
6644                            + " to package " + pkg.packageName
6645                            + " because it was previously installed without");
6646                }
6647            } else {
6648                if (gp.grantedPermissions.remove(perm)) {
6649                    changedPermission = true;
6650                    gp.gids = removeInts(gp.gids, bp.gids);
6651                    Slog.i(TAG, "Un-granting permission " + perm
6652                            + " from package " + pkg.packageName
6653                            + " (protectionLevel=" + bp.protectionLevel
6654                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6655                            + ")");
6656                } else {
6657                    Slog.w(TAG, "Not granting permission " + perm
6658                            + " to package " + pkg.packageName
6659                            + " (protectionLevel=" + bp.protectionLevel
6660                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6661                            + ")");
6662                }
6663            }
6664        }
6665
6666        if ((changedPermission || replace) && !ps.permissionsFixed &&
6667                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6668            // This is the first that we have heard about this package, so the
6669            // permissions we have now selected are fixed until explicitly
6670            // changed.
6671            ps.permissionsFixed = true;
6672        }
6673        ps.haveGids = true;
6674    }
6675
6676    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6677        boolean allowed = false;
6678        final int NP = PackageParser.NEW_PERMISSIONS.length;
6679        for (int ip=0; ip<NP; ip++) {
6680            final PackageParser.NewPermissionInfo npi
6681                    = PackageParser.NEW_PERMISSIONS[ip];
6682            if (npi.name.equals(perm)
6683                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6684                allowed = true;
6685                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6686                        + pkg.packageName);
6687                break;
6688            }
6689        }
6690        return allowed;
6691    }
6692
6693    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6694                                          BasePermission bp, HashSet<String> origPermissions) {
6695        boolean allowed;
6696        allowed = (compareSignatures(
6697                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6698                        == PackageManager.SIGNATURE_MATCH)
6699                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6700                        == PackageManager.SIGNATURE_MATCH);
6701        if (!allowed && (bp.protectionLevel
6702                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6703            if (isSystemApp(pkg)) {
6704                // For updated system applications, a system permission
6705                // is granted only if it had been defined by the original application.
6706                if (isUpdatedSystemApp(pkg)) {
6707                    final PackageSetting sysPs = mSettings
6708                            .getDisabledSystemPkgLPr(pkg.packageName);
6709                    final GrantedPermissions origGp = sysPs.sharedUser != null
6710                            ? sysPs.sharedUser : sysPs;
6711
6712                    if (origGp.grantedPermissions.contains(perm)) {
6713                        // If the original was granted this permission, we take
6714                        // that grant decision as read and propagate it to the
6715                        // update.
6716                        allowed = true;
6717                    } else {
6718                        // The system apk may have been updated with an older
6719                        // version of the one on the data partition, but which
6720                        // granted a new system permission that it didn't have
6721                        // before.  In this case we do want to allow the app to
6722                        // now get the new permission if the ancestral apk is
6723                        // privileged to get it.
6724                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6725                            for (int j=0;
6726                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6727                                if (perm.equals(
6728                                        sysPs.pkg.requestedPermissions.get(j))) {
6729                                    allowed = true;
6730                                    break;
6731                                }
6732                            }
6733                        }
6734                    }
6735                } else {
6736                    allowed = isPrivilegedApp(pkg);
6737                }
6738            }
6739        }
6740        if (!allowed && (bp.protectionLevel
6741                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6742            // For development permissions, a development permission
6743            // is granted only if it was already granted.
6744            allowed = origPermissions.contains(perm);
6745        }
6746        return allowed;
6747    }
6748
6749    final class ActivityIntentResolver
6750            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6751        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6752                boolean defaultOnly, int userId) {
6753            if (!sUserManager.exists(userId)) return null;
6754            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6755            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6756        }
6757
6758        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6759                int userId) {
6760            if (!sUserManager.exists(userId)) return null;
6761            mFlags = flags;
6762            return super.queryIntent(intent, resolvedType,
6763                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6764        }
6765
6766        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6767                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6768            if (!sUserManager.exists(userId)) return null;
6769            if (packageActivities == null) {
6770                return null;
6771            }
6772            mFlags = flags;
6773            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6774            final int N = packageActivities.size();
6775            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6776                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6777
6778            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6779            for (int i = 0; i < N; ++i) {
6780                intentFilters = packageActivities.get(i).intents;
6781                if (intentFilters != null && intentFilters.size() > 0) {
6782                    PackageParser.ActivityIntentInfo[] array =
6783                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6784                    intentFilters.toArray(array);
6785                    listCut.add(array);
6786                }
6787            }
6788            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6789        }
6790
6791        public final void addActivity(PackageParser.Activity a, String type) {
6792            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6793            mActivities.put(a.getComponentName(), a);
6794            if (DEBUG_SHOW_INFO)
6795                Log.v(
6796                TAG, "  " + type + " " +
6797                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6798            if (DEBUG_SHOW_INFO)
6799                Log.v(TAG, "    Class=" + a.info.name);
6800            final int NI = a.intents.size();
6801            for (int j=0; j<NI; j++) {
6802                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6803                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6804                    intent.setPriority(0);
6805                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6806                            + a.className + " with priority > 0, forcing to 0");
6807                }
6808                if (DEBUG_SHOW_INFO) {
6809                    Log.v(TAG, "    IntentFilter:");
6810                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6811                }
6812                if (!intent.debugCheck()) {
6813                    Log.w(TAG, "==> For Activity " + a.info.name);
6814                }
6815                addFilter(intent);
6816            }
6817        }
6818
6819        public final void removeActivity(PackageParser.Activity a, String type) {
6820            mActivities.remove(a.getComponentName());
6821            if (DEBUG_SHOW_INFO) {
6822                Log.v(TAG, "  " + type + " "
6823                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6824                                : a.info.name) + ":");
6825                Log.v(TAG, "    Class=" + a.info.name);
6826            }
6827            final int NI = a.intents.size();
6828            for (int j=0; j<NI; j++) {
6829                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6830                if (DEBUG_SHOW_INFO) {
6831                    Log.v(TAG, "    IntentFilter:");
6832                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6833                }
6834                removeFilter(intent);
6835            }
6836        }
6837
6838        @Override
6839        protected boolean allowFilterResult(
6840                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6841            ActivityInfo filterAi = filter.activity.info;
6842            for (int i=dest.size()-1; i>=0; i--) {
6843                ActivityInfo destAi = dest.get(i).activityInfo;
6844                if (destAi.name == filterAi.name
6845                        && destAi.packageName == filterAi.packageName) {
6846                    return false;
6847                }
6848            }
6849            return true;
6850        }
6851
6852        @Override
6853        protected ActivityIntentInfo[] newArray(int size) {
6854            return new ActivityIntentInfo[size];
6855        }
6856
6857        @Override
6858        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6859            if (!sUserManager.exists(userId)) return true;
6860            PackageParser.Package p = filter.activity.owner;
6861            if (p != null) {
6862                PackageSetting ps = (PackageSetting)p.mExtras;
6863                if (ps != null) {
6864                    // System apps are never considered stopped for purposes of
6865                    // filtering, because there may be no way for the user to
6866                    // actually re-launch them.
6867                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6868                            && ps.getStopped(userId);
6869                }
6870            }
6871            return false;
6872        }
6873
6874        @Override
6875        protected boolean isPackageForFilter(String packageName,
6876                PackageParser.ActivityIntentInfo info) {
6877            return packageName.equals(info.activity.owner.packageName);
6878        }
6879
6880        @Override
6881        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6882                int match, int userId) {
6883            if (!sUserManager.exists(userId)) return null;
6884            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6885                return null;
6886            }
6887            final PackageParser.Activity activity = info.activity;
6888            if (mSafeMode && (activity.info.applicationInfo.flags
6889                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6890                return null;
6891            }
6892            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6893            if (ps == null) {
6894                return null;
6895            }
6896            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6897                    ps.readUserState(userId), userId);
6898            if (ai == null) {
6899                return null;
6900            }
6901            final ResolveInfo res = new ResolveInfo();
6902            res.activityInfo = ai;
6903            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6904                res.filter = info;
6905            }
6906            res.priority = info.getPriority();
6907            res.preferredOrder = activity.owner.mPreferredOrder;
6908            //System.out.println("Result: " + res.activityInfo.className +
6909            //                   " = " + res.priority);
6910            res.match = match;
6911            res.isDefault = info.hasDefault;
6912            res.labelRes = info.labelRes;
6913            res.nonLocalizedLabel = info.nonLocalizedLabel;
6914            if (userNeedsBadging(userId)) {
6915                res.noResourceId = true;
6916            } else {
6917                res.icon = info.icon;
6918            }
6919            res.system = isSystemApp(res.activityInfo.applicationInfo);
6920            return res;
6921        }
6922
6923        @Override
6924        protected void sortResults(List<ResolveInfo> results) {
6925            Collections.sort(results, mResolvePrioritySorter);
6926        }
6927
6928        @Override
6929        protected void dumpFilter(PrintWriter out, String prefix,
6930                PackageParser.ActivityIntentInfo filter) {
6931            out.print(prefix); out.print(
6932                    Integer.toHexString(System.identityHashCode(filter.activity)));
6933                    out.print(' ');
6934                    filter.activity.printComponentShortName(out);
6935                    out.print(" filter ");
6936                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6937        }
6938
6939//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6940//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6941//            final List<ResolveInfo> retList = Lists.newArrayList();
6942//            while (i.hasNext()) {
6943//                final ResolveInfo resolveInfo = i.next();
6944//                if (isEnabledLP(resolveInfo.activityInfo)) {
6945//                    retList.add(resolveInfo);
6946//                }
6947//            }
6948//            return retList;
6949//        }
6950
6951        // Keys are String (activity class name), values are Activity.
6952        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6953                = new HashMap<ComponentName, PackageParser.Activity>();
6954        private int mFlags;
6955    }
6956
6957    private final class ServiceIntentResolver
6958            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6959        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6960                boolean defaultOnly, int userId) {
6961            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6962            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6963        }
6964
6965        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6966                int userId) {
6967            if (!sUserManager.exists(userId)) return null;
6968            mFlags = flags;
6969            return super.queryIntent(intent, resolvedType,
6970                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6971        }
6972
6973        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6974                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6975            if (!sUserManager.exists(userId)) return null;
6976            if (packageServices == null) {
6977                return null;
6978            }
6979            mFlags = flags;
6980            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6981            final int N = packageServices.size();
6982            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6983                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6984
6985            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6986            for (int i = 0; i < N; ++i) {
6987                intentFilters = packageServices.get(i).intents;
6988                if (intentFilters != null && intentFilters.size() > 0) {
6989                    PackageParser.ServiceIntentInfo[] array =
6990                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6991                    intentFilters.toArray(array);
6992                    listCut.add(array);
6993                }
6994            }
6995            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6996        }
6997
6998        public final void addService(PackageParser.Service s) {
6999            mServices.put(s.getComponentName(), s);
7000            if (DEBUG_SHOW_INFO) {
7001                Log.v(TAG, "  "
7002                        + (s.info.nonLocalizedLabel != null
7003                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7004                Log.v(TAG, "    Class=" + s.info.name);
7005            }
7006            final int NI = s.intents.size();
7007            int j;
7008            for (j=0; j<NI; j++) {
7009                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7010                if (DEBUG_SHOW_INFO) {
7011                    Log.v(TAG, "    IntentFilter:");
7012                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7013                }
7014                if (!intent.debugCheck()) {
7015                    Log.w(TAG, "==> For Service " + s.info.name);
7016                }
7017                addFilter(intent);
7018            }
7019        }
7020
7021        public final void removeService(PackageParser.Service s) {
7022            mServices.remove(s.getComponentName());
7023            if (DEBUG_SHOW_INFO) {
7024                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7025                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7026                Log.v(TAG, "    Class=" + s.info.name);
7027            }
7028            final int NI = s.intents.size();
7029            int j;
7030            for (j=0; j<NI; j++) {
7031                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7032                if (DEBUG_SHOW_INFO) {
7033                    Log.v(TAG, "    IntentFilter:");
7034                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7035                }
7036                removeFilter(intent);
7037            }
7038        }
7039
7040        @Override
7041        protected boolean allowFilterResult(
7042                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7043            ServiceInfo filterSi = filter.service.info;
7044            for (int i=dest.size()-1; i>=0; i--) {
7045                ServiceInfo destAi = dest.get(i).serviceInfo;
7046                if (destAi.name == filterSi.name
7047                        && destAi.packageName == filterSi.packageName) {
7048                    return false;
7049                }
7050            }
7051            return true;
7052        }
7053
7054        @Override
7055        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7056            return new PackageParser.ServiceIntentInfo[size];
7057        }
7058
7059        @Override
7060        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7061            if (!sUserManager.exists(userId)) return true;
7062            PackageParser.Package p = filter.service.owner;
7063            if (p != null) {
7064                PackageSetting ps = (PackageSetting)p.mExtras;
7065                if (ps != null) {
7066                    // System apps are never considered stopped for purposes of
7067                    // filtering, because there may be no way for the user to
7068                    // actually re-launch them.
7069                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7070                            && ps.getStopped(userId);
7071                }
7072            }
7073            return false;
7074        }
7075
7076        @Override
7077        protected boolean isPackageForFilter(String packageName,
7078                PackageParser.ServiceIntentInfo info) {
7079            return packageName.equals(info.service.owner.packageName);
7080        }
7081
7082        @Override
7083        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7084                int match, int userId) {
7085            if (!sUserManager.exists(userId)) return null;
7086            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7087            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7088                return null;
7089            }
7090            final PackageParser.Service service = info.service;
7091            if (mSafeMode && (service.info.applicationInfo.flags
7092                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7093                return null;
7094            }
7095            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7096            if (ps == null) {
7097                return null;
7098            }
7099            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7100                    ps.readUserState(userId), userId);
7101            if (si == null) {
7102                return null;
7103            }
7104            final ResolveInfo res = new ResolveInfo();
7105            res.serviceInfo = si;
7106            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7107                res.filter = filter;
7108            }
7109            res.priority = info.getPriority();
7110            res.preferredOrder = service.owner.mPreferredOrder;
7111            //System.out.println("Result: " + res.activityInfo.className +
7112            //                   " = " + res.priority);
7113            res.match = match;
7114            res.isDefault = info.hasDefault;
7115            res.labelRes = info.labelRes;
7116            res.nonLocalizedLabel = info.nonLocalizedLabel;
7117            res.icon = info.icon;
7118            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7119            return res;
7120        }
7121
7122        @Override
7123        protected void sortResults(List<ResolveInfo> results) {
7124            Collections.sort(results, mResolvePrioritySorter);
7125        }
7126
7127        @Override
7128        protected void dumpFilter(PrintWriter out, String prefix,
7129                PackageParser.ServiceIntentInfo filter) {
7130            out.print(prefix); out.print(
7131                    Integer.toHexString(System.identityHashCode(filter.service)));
7132                    out.print(' ');
7133                    filter.service.printComponentShortName(out);
7134                    out.print(" filter ");
7135                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7136        }
7137
7138//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7139//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7140//            final List<ResolveInfo> retList = Lists.newArrayList();
7141//            while (i.hasNext()) {
7142//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7143//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7144//                    retList.add(resolveInfo);
7145//                }
7146//            }
7147//            return retList;
7148//        }
7149
7150        // Keys are String (activity class name), values are Activity.
7151        private final HashMap<ComponentName, PackageParser.Service> mServices
7152                = new HashMap<ComponentName, PackageParser.Service>();
7153        private int mFlags;
7154    };
7155
7156    private final class ProviderIntentResolver
7157            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7158        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7159                boolean defaultOnly, int userId) {
7160            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7161            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7162        }
7163
7164        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7165                int userId) {
7166            if (!sUserManager.exists(userId))
7167                return null;
7168            mFlags = flags;
7169            return super.queryIntent(intent, resolvedType,
7170                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7171        }
7172
7173        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7174                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7175            if (!sUserManager.exists(userId))
7176                return null;
7177            if (packageProviders == null) {
7178                return null;
7179            }
7180            mFlags = flags;
7181            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7182            final int N = packageProviders.size();
7183            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7184                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7185
7186            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7187            for (int i = 0; i < N; ++i) {
7188                intentFilters = packageProviders.get(i).intents;
7189                if (intentFilters != null && intentFilters.size() > 0) {
7190                    PackageParser.ProviderIntentInfo[] array =
7191                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7192                    intentFilters.toArray(array);
7193                    listCut.add(array);
7194                }
7195            }
7196            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7197        }
7198
7199        public final void addProvider(PackageParser.Provider p) {
7200            if (mProviders.containsKey(p.getComponentName())) {
7201                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7202                return;
7203            }
7204
7205            mProviders.put(p.getComponentName(), p);
7206            if (DEBUG_SHOW_INFO) {
7207                Log.v(TAG, "  "
7208                        + (p.info.nonLocalizedLabel != null
7209                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7210                Log.v(TAG, "    Class=" + p.info.name);
7211            }
7212            final int NI = p.intents.size();
7213            int j;
7214            for (j = 0; j < NI; j++) {
7215                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7216                if (DEBUG_SHOW_INFO) {
7217                    Log.v(TAG, "    IntentFilter:");
7218                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7219                }
7220                if (!intent.debugCheck()) {
7221                    Log.w(TAG, "==> For Provider " + p.info.name);
7222                }
7223                addFilter(intent);
7224            }
7225        }
7226
7227        public final void removeProvider(PackageParser.Provider p) {
7228            mProviders.remove(p.getComponentName());
7229            if (DEBUG_SHOW_INFO) {
7230                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7231                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7232                Log.v(TAG, "    Class=" + p.info.name);
7233            }
7234            final int NI = p.intents.size();
7235            int j;
7236            for (j = 0; j < NI; j++) {
7237                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7238                if (DEBUG_SHOW_INFO) {
7239                    Log.v(TAG, "    IntentFilter:");
7240                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7241                }
7242                removeFilter(intent);
7243            }
7244        }
7245
7246        @Override
7247        protected boolean allowFilterResult(
7248                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7249            ProviderInfo filterPi = filter.provider.info;
7250            for (int i = dest.size() - 1; i >= 0; i--) {
7251                ProviderInfo destPi = dest.get(i).providerInfo;
7252                if (destPi.name == filterPi.name
7253                        && destPi.packageName == filterPi.packageName) {
7254                    return false;
7255                }
7256            }
7257            return true;
7258        }
7259
7260        @Override
7261        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7262            return new PackageParser.ProviderIntentInfo[size];
7263        }
7264
7265        @Override
7266        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7267            if (!sUserManager.exists(userId))
7268                return true;
7269            PackageParser.Package p = filter.provider.owner;
7270            if (p != null) {
7271                PackageSetting ps = (PackageSetting) p.mExtras;
7272                if (ps != null) {
7273                    // System apps are never considered stopped for purposes of
7274                    // filtering, because there may be no way for the user to
7275                    // actually re-launch them.
7276                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7277                            && ps.getStopped(userId);
7278                }
7279            }
7280            return false;
7281        }
7282
7283        @Override
7284        protected boolean isPackageForFilter(String packageName,
7285                PackageParser.ProviderIntentInfo info) {
7286            return packageName.equals(info.provider.owner.packageName);
7287        }
7288
7289        @Override
7290        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7291                int match, int userId) {
7292            if (!sUserManager.exists(userId))
7293                return null;
7294            final PackageParser.ProviderIntentInfo info = filter;
7295            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7296                return null;
7297            }
7298            final PackageParser.Provider provider = info.provider;
7299            if (mSafeMode && (provider.info.applicationInfo.flags
7300                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7301                return null;
7302            }
7303            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7304            if (ps == null) {
7305                return null;
7306            }
7307            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7308                    ps.readUserState(userId), userId);
7309            if (pi == null) {
7310                return null;
7311            }
7312            final ResolveInfo res = new ResolveInfo();
7313            res.providerInfo = pi;
7314            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7315                res.filter = filter;
7316            }
7317            res.priority = info.getPriority();
7318            res.preferredOrder = provider.owner.mPreferredOrder;
7319            res.match = match;
7320            res.isDefault = info.hasDefault;
7321            res.labelRes = info.labelRes;
7322            res.nonLocalizedLabel = info.nonLocalizedLabel;
7323            res.icon = info.icon;
7324            res.system = isSystemApp(res.providerInfo.applicationInfo);
7325            return res;
7326        }
7327
7328        @Override
7329        protected void sortResults(List<ResolveInfo> results) {
7330            Collections.sort(results, mResolvePrioritySorter);
7331        }
7332
7333        @Override
7334        protected void dumpFilter(PrintWriter out, String prefix,
7335                PackageParser.ProviderIntentInfo filter) {
7336            out.print(prefix);
7337            out.print(
7338                    Integer.toHexString(System.identityHashCode(filter.provider)));
7339            out.print(' ');
7340            filter.provider.printComponentShortName(out);
7341            out.print(" filter ");
7342            out.println(Integer.toHexString(System.identityHashCode(filter)));
7343        }
7344
7345        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7346                = new HashMap<ComponentName, PackageParser.Provider>();
7347        private int mFlags;
7348    };
7349
7350    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7351            new Comparator<ResolveInfo>() {
7352        public int compare(ResolveInfo r1, ResolveInfo r2) {
7353            int v1 = r1.priority;
7354            int v2 = r2.priority;
7355            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7356            if (v1 != v2) {
7357                return (v1 > v2) ? -1 : 1;
7358            }
7359            v1 = r1.preferredOrder;
7360            v2 = r2.preferredOrder;
7361            if (v1 != v2) {
7362                return (v1 > v2) ? -1 : 1;
7363            }
7364            if (r1.isDefault != r2.isDefault) {
7365                return r1.isDefault ? -1 : 1;
7366            }
7367            v1 = r1.match;
7368            v2 = r2.match;
7369            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7370            if (v1 != v2) {
7371                return (v1 > v2) ? -1 : 1;
7372            }
7373            if (r1.system != r2.system) {
7374                return r1.system ? -1 : 1;
7375            }
7376            return 0;
7377        }
7378    };
7379
7380    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7381            new Comparator<ProviderInfo>() {
7382        public int compare(ProviderInfo p1, ProviderInfo p2) {
7383            final int v1 = p1.initOrder;
7384            final int v2 = p2.initOrder;
7385            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7386        }
7387    };
7388
7389    static final void sendPackageBroadcast(String action, String pkg,
7390            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7391            int[] userIds) {
7392        IActivityManager am = ActivityManagerNative.getDefault();
7393        if (am != null) {
7394            try {
7395                if (userIds == null) {
7396                    userIds = am.getRunningUserIds();
7397                }
7398                for (int id : userIds) {
7399                    final Intent intent = new Intent(action,
7400                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7401                    if (extras != null) {
7402                        intent.putExtras(extras);
7403                    }
7404                    if (targetPkg != null) {
7405                        intent.setPackage(targetPkg);
7406                    }
7407                    // Modify the UID when posting to other users
7408                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7409                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7410                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7411                        intent.putExtra(Intent.EXTRA_UID, uid);
7412                    }
7413                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7414                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7415                    if (DEBUG_BROADCASTS) {
7416                        RuntimeException here = new RuntimeException("here");
7417                        here.fillInStackTrace();
7418                        Slog.d(TAG, "Sending to user " + id + ": "
7419                                + intent.toShortString(false, true, false, false)
7420                                + " " + intent.getExtras(), here);
7421                    }
7422                    am.broadcastIntent(null, intent, null, finishedReceiver,
7423                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7424                            finishedReceiver != null, false, id);
7425                }
7426            } catch (RemoteException ex) {
7427            }
7428        }
7429    }
7430
7431    /**
7432     * Check if the external storage media is available. This is true if there
7433     * is a mounted external storage medium or if the external storage is
7434     * emulated.
7435     */
7436    private boolean isExternalMediaAvailable() {
7437        return mMediaMounted || Environment.isExternalStorageEmulated();
7438    }
7439
7440    @Override
7441    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7442        // writer
7443        synchronized (mPackages) {
7444            if (!isExternalMediaAvailable()) {
7445                // If the external storage is no longer mounted at this point,
7446                // the caller may not have been able to delete all of this
7447                // packages files and can not delete any more.  Bail.
7448                return null;
7449            }
7450            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7451            if (lastPackage != null) {
7452                pkgs.remove(lastPackage);
7453            }
7454            if (pkgs.size() > 0) {
7455                return pkgs.get(0);
7456            }
7457        }
7458        return null;
7459    }
7460
7461    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7462        if (false) {
7463            RuntimeException here = new RuntimeException("here");
7464            here.fillInStackTrace();
7465            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7466                    + " andCode=" + andCode, here);
7467        }
7468        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7469                userId, andCode ? 1 : 0, packageName));
7470    }
7471
7472    void startCleaningPackages() {
7473        // reader
7474        synchronized (mPackages) {
7475            if (!isExternalMediaAvailable()) {
7476                return;
7477            }
7478            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7479                return;
7480            }
7481        }
7482        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7483        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7484        IActivityManager am = ActivityManagerNative.getDefault();
7485        if (am != null) {
7486            try {
7487                am.startService(null, intent, null, UserHandle.USER_OWNER);
7488            } catch (RemoteException e) {
7489            }
7490        }
7491    }
7492
7493    private final class AppDirObserver extends FileObserver {
7494        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7495            super(path, mask);
7496            mRootDir = path;
7497            mIsRom = isrom;
7498            mIsPrivileged = isPrivileged;
7499        }
7500
7501        public void onEvent(int event, String path) {
7502            String removedPackage = null;
7503            int removedAppId = -1;
7504            int[] removedUsers = null;
7505            String addedPackage = null;
7506            int addedAppId = -1;
7507            int[] addedUsers = null;
7508
7509            // TODO post a message to the handler to obtain serial ordering
7510            synchronized (mInstallLock) {
7511                String fullPathStr = null;
7512                File fullPath = null;
7513                if (path != null) {
7514                    fullPath = new File(mRootDir, path);
7515                    fullPathStr = fullPath.getPath();
7516                }
7517
7518                if (DEBUG_APP_DIR_OBSERVER)
7519                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7520
7521                if (!isApkFile(fullPath)) {
7522                    if (DEBUG_APP_DIR_OBSERVER)
7523                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7524                    return;
7525                }
7526
7527                // Ignore packages that are being installed or
7528                // have just been installed.
7529                if (ignoreCodePath(fullPathStr)) {
7530                    return;
7531                }
7532                PackageParser.Package p = null;
7533                PackageSetting ps = null;
7534                // reader
7535                synchronized (mPackages) {
7536                    p = mAppDirs.get(fullPathStr);
7537                    if (p != null) {
7538                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7539                        if (ps != null) {
7540                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7541                        } else {
7542                            removedUsers = sUserManager.getUserIds();
7543                        }
7544                    }
7545                    addedUsers = sUserManager.getUserIds();
7546                }
7547                if ((event&REMOVE_EVENTS) != 0) {
7548                    if (ps != null) {
7549                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7550                        removePackageLI(ps, true);
7551                        removedPackage = ps.name;
7552                        removedAppId = ps.appId;
7553                    }
7554                }
7555
7556                if ((event&ADD_EVENTS) != 0) {
7557                    if (p == null) {
7558                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7559                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7560                        if (mIsRom) {
7561                            flags |= PackageParser.PARSE_IS_SYSTEM
7562                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7563                            if (mIsPrivileged) {
7564                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7565                            }
7566                        }
7567                        p = scanPackageLI(fullPath, flags,
7568                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7569                                System.currentTimeMillis(), UserHandle.ALL, null);
7570                        if (p != null) {
7571                            /*
7572                             * TODO this seems dangerous as the package may have
7573                             * changed since we last acquired the mPackages
7574                             * lock.
7575                             */
7576                            // writer
7577                            synchronized (mPackages) {
7578                                updatePermissionsLPw(p.packageName, p,
7579                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7580                            }
7581                            addedPackage = p.applicationInfo.packageName;
7582                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7583                        }
7584                    }
7585                }
7586
7587                // reader
7588                synchronized (mPackages) {
7589                    mSettings.writeLPr();
7590                }
7591            }
7592
7593            if (removedPackage != null) {
7594                Bundle extras = new Bundle(1);
7595                extras.putInt(Intent.EXTRA_UID, removedAppId);
7596                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7597                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7598                        extras, null, null, removedUsers);
7599            }
7600            if (addedPackage != null) {
7601                Bundle extras = new Bundle(1);
7602                extras.putInt(Intent.EXTRA_UID, addedAppId);
7603                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7604                        extras, null, null, addedUsers);
7605            }
7606        }
7607
7608        private final String mRootDir;
7609        private final boolean mIsRom;
7610        private final boolean mIsPrivileged;
7611    }
7612
7613    @Override
7614    public void installPackage(String originPath, IPackageInstallObserver2 observer, int flags,
7615            String installerPackageName, VerificationParams verificationParams,
7616            String packageAbiOverride) {
7617        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7618                null);
7619
7620        final File originFile = new File(originPath);
7621        final int uid = Binder.getCallingUid();
7622        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7623            try {
7624                if (observer != null) {
7625                    observer.packageInstalled("", null, INSTALL_FAILED_USER_RESTRICTED);
7626                }
7627            } catch (RemoteException re) {
7628            }
7629            return;
7630        }
7631
7632        UserHandle user;
7633        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7634            user = UserHandle.ALL;
7635        } else {
7636            user = new UserHandle(UserHandle.getUserId(uid));
7637        }
7638
7639        final int filteredFlags;
7640        if (uid == Process.SHELL_UID || uid == 0) {
7641            if (DEBUG_INSTALL) {
7642                Slog.v(TAG, "Install from ADB");
7643            }
7644            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7645        } else {
7646            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7647        }
7648
7649        verificationParams.setInstallerUid(uid);
7650
7651        final Message msg = mHandler.obtainMessage(INIT_COPY);
7652        msg.obj = new InstallParams(originFile, observer, filteredFlags, installerPackageName,
7653                verificationParams, user, packageAbiOverride);
7654        mHandler.sendMessage(msg);
7655    }
7656
7657    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7658        Bundle extras = new Bundle(1);
7659        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7660
7661        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7662                packageName, extras, null, null, new int[] {userId});
7663        try {
7664            IActivityManager am = ActivityManagerNative.getDefault();
7665            final boolean isSystem =
7666                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7667            if (isSystem && am.isUserRunning(userId, false)) {
7668                // The just-installed/enabled app is bundled on the system, so presumed
7669                // to be able to run automatically without needing an explicit launch.
7670                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7671                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7672                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7673                        .setPackage(packageName);
7674                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7675                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7676            }
7677        } catch (RemoteException e) {
7678            // shouldn't happen
7679            Slog.w(TAG, "Unable to bootstrap installed package", e);
7680        }
7681    }
7682
7683    @Override
7684    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7685            int userId) {
7686        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7687        PackageSetting pkgSetting;
7688        final int uid = Binder.getCallingUid();
7689        if (UserHandle.getUserId(uid) != userId) {
7690            mContext.enforceCallingOrSelfPermission(
7691                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7692                    "setApplicationBlockedSetting for user " + userId);
7693        }
7694
7695        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7696            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7697            return false;
7698        }
7699
7700        long callingId = Binder.clearCallingIdentity();
7701        try {
7702            boolean sendAdded = false;
7703            boolean sendRemoved = false;
7704            // writer
7705            synchronized (mPackages) {
7706                pkgSetting = mSettings.mPackages.get(packageName);
7707                if (pkgSetting == null) {
7708                    return false;
7709                }
7710                if (pkgSetting.getBlocked(userId) != blocked) {
7711                    pkgSetting.setBlocked(blocked, userId);
7712                    mSettings.writePackageRestrictionsLPr(userId);
7713                    if (blocked) {
7714                        sendRemoved = true;
7715                    } else {
7716                        sendAdded = true;
7717                    }
7718                }
7719            }
7720            if (sendAdded) {
7721                sendPackageAddedForUser(packageName, pkgSetting, userId);
7722                return true;
7723            }
7724            if (sendRemoved) {
7725                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7726                        "blocking pkg");
7727                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7728            }
7729        } finally {
7730            Binder.restoreCallingIdentity(callingId);
7731        }
7732        return false;
7733    }
7734
7735    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7736            int userId) {
7737        final PackageRemovedInfo info = new PackageRemovedInfo();
7738        info.removedPackage = packageName;
7739        info.removedUsers = new int[] {userId};
7740        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7741        info.sendBroadcast(false, false, false);
7742    }
7743
7744    /**
7745     * Returns true if application is not found or there was an error. Otherwise it returns
7746     * the blocked state of the package for the given user.
7747     */
7748    @Override
7749    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7750        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7751        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7752                "getApplicationBlocked for user " + userId);
7753        PackageSetting pkgSetting;
7754        long callingId = Binder.clearCallingIdentity();
7755        try {
7756            // writer
7757            synchronized (mPackages) {
7758                pkgSetting = mSettings.mPackages.get(packageName);
7759                if (pkgSetting == null) {
7760                    return true;
7761                }
7762                return pkgSetting.getBlocked(userId);
7763            }
7764        } finally {
7765            Binder.restoreCallingIdentity(callingId);
7766        }
7767    }
7768
7769    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2,
7770            PackageInstallerParams params, String installerPackageName, int installerUid,
7771            UserHandle user) {
7772        Slog.e(TAG, "TODO: install stage!");
7773        try {
7774            observer2.packageInstalled(packageName, null,
7775                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7776        } catch (RemoteException ignored) {
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} lives in a trusted location,
8366         * meaning downstream users don't need to defensively copy the contents.
8367         */
8368        boolean originTrusted;
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, IPackageInstallObserver2 observer, int flags,
8380                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8381                String packageAbiOverride) {
8382            super(user);
8383            this.originFile = Preconditions.checkNotNull(originFile);
8384            this.originTrusted = false;
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#originTrusted */
8913        final boolean originTrusted;
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 originTrusted, IPackageInstallObserver2 observer,
8927                int flags, String installerPackageName, ManifestDigest manifestDigest,
8928                UserHandle user, String instructionSet, String abiOverride) {
8929            this.originFile = originFile;
8930            this.originTrusted = originTrusted;
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.originTrusted, 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, true, 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            try {
9054                final File tempDir = createTempPackageDir(mAppInstallDir);
9055                codeFile = tempDir;
9056                resourceFile = tempDir;
9057            } catch (IOException e) {
9058                Slog.w(TAG, "Failed to create copy file: " + e);
9059                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9060            }
9061
9062            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9063                @Override
9064                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9065                    if (!FileUtils.isValidExtFilename(name)) {
9066                        throw new IllegalArgumentException("Invalid filename: " + name);
9067                    }
9068                    try {
9069                        final File file = new File(codeFile, name);
9070                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9071                                O_RDWR | O_CREAT, 0644);
9072                        Os.chmod(file.getAbsolutePath(), 0644);
9073                        return new ParcelFileDescriptor(fd);
9074                    } catch (ErrnoException e) {
9075                        throw new RemoteException("Failed to open: " + e.getMessage());
9076                    }
9077                }
9078            };
9079
9080            int ret = imcs.copyPackage(originFile.getAbsolutePath(), target);
9081            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9082                Slog.e(TAG, "Failed to copy package");
9083                return ret;
9084            }
9085
9086            String[] abiList = (abiOverride != null) ?
9087                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9088            NativeLibraryHelper.Handle handle = null;
9089            try {
9090                handle = NativeLibraryHelper.Handle.create(codeFile);
9091                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9092                        abiOverride == null &&
9093                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9094                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9095                }
9096
9097                // TODO: refactor to avoid double findSupportedAbi()
9098                final int abiIndex = NativeLibraryHelper.findSupportedAbi(handle, abiList);
9099                if (abiIndex < 0 && abiIndex != PackageManager.NO_NATIVE_LIBRARIES) {
9100                    return abiIndex;
9101                } else if (abiIndex >= 0) {
9102                    final File baseLibFile = new File(codeFile, LIB_DIR_NAME);
9103                    baseLibFile.mkdir();
9104                    Os.chmod(baseLibFile.getAbsolutePath(), 0755);
9105
9106                    final String abi = Build.SUPPORTED_ABIS[abiIndex];
9107                    final String instructionSet = VMRuntime.getInstructionSet(abi);
9108                    nativeLibraryFile = new File(baseLibFile, instructionSet);
9109                    nativeLibraryFile.mkdir();
9110                    Os.chmod(nativeLibraryFile.getAbsolutePath(), 0755);
9111
9112                    copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9113                }
9114            } catch (IOException | ErrnoException e) {
9115                Slog.e(TAG, "Copying native libraries failed", e);
9116                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9117            } finally {
9118                IoUtils.closeQuietly(handle);
9119            }
9120
9121            return ret;
9122        }
9123
9124        int doPreInstall(int status) {
9125            if (status != PackageManager.INSTALL_SUCCEEDED) {
9126                cleanUp();
9127            }
9128            return status;
9129        }
9130
9131        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9132            if (status != PackageManager.INSTALL_SUCCEEDED) {
9133                cleanUp();
9134                return false;
9135            } else {
9136                final File beforeCodeFile = codeFile;
9137                final File afterCodeFile = new File(mAppInstallDir,
9138                        getNextCodePath(oldCodePath, pkg.packageName, null));
9139
9140                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9141                if (!beforeCodeFile.renameTo(afterCodeFile)) {
9142                    return false;
9143                }
9144                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9145                    return false;
9146                }
9147
9148                // Reflect the rename internally
9149                codeFile = afterCodeFile;
9150                resourceFile = afterCodeFile;
9151                nativeLibraryFile = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9152                        nativeLibraryFile);
9153
9154                // Reflect the rename in scanned details
9155                pkg.codePath = afterCodeFile.getAbsolutePath();
9156                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9157                        pkg.baseCodePath);
9158                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9159                        pkg.splitCodePaths);
9160
9161                // Reflect the rename in app info
9162                pkg.applicationInfo.setCodePath(pkg.codePath);
9163                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9164                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9165                pkg.applicationInfo.setResourcePath(pkg.codePath);
9166                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9167                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9168                pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath();
9169
9170                return true;
9171            }
9172        }
9173
9174        int doPostInstall(int status, int uid) {
9175            if (status != PackageManager.INSTALL_SUCCEEDED) {
9176                cleanUp();
9177            }
9178            return status;
9179        }
9180
9181        @Override
9182        String getCodePath() {
9183            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9184        }
9185
9186        @Override
9187        String getResourcePath() {
9188            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9189        }
9190
9191        @Override
9192        String getNativeLibraryPath() {
9193            return (nativeLibraryFile != null) ? nativeLibraryFile.getAbsolutePath() : null;
9194        }
9195
9196        private boolean cleanUp() {
9197            if (codeFile == null || !codeFile.exists()) {
9198                return false;
9199            }
9200
9201            if (codeFile.isDirectory()) {
9202                FileUtils.deleteContents(codeFile);
9203            }
9204            codeFile.delete();
9205
9206            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9207                resourceFile.delete();
9208            }
9209
9210            if (nativeLibraryFile != null && !FileUtils.contains(codeFile, nativeLibraryFile)) {
9211                FileUtils.deleteContents(nativeLibraryFile);
9212                nativeLibraryFile.delete();
9213            }
9214
9215            return true;
9216        }
9217
9218        void cleanUpResourcesLI() {
9219            // Try enumerating all code paths before deleting
9220            List<String> allCodePaths = Collections.EMPTY_LIST;
9221            if (codeFile != null && codeFile.exists()) {
9222                try {
9223                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9224                    allCodePaths = pkg.getAllCodePaths();
9225                } catch (PackageParserException e) {
9226                    // Ignored; we tried our best
9227                }
9228            }
9229
9230            cleanUp();
9231
9232            if (!allCodePaths.isEmpty()) {
9233                if (instructionSet == null) {
9234                    throw new IllegalStateException("instructionSet == null");
9235                }
9236
9237                for (String codePath : allCodePaths) {
9238                    int retCode = mInstaller.rmdex(codePath, instructionSet);
9239                    if (retCode < 0) {
9240                        Slog.w(TAG, "Couldn't remove dex file for package: "
9241                                +  " at location " + codePath + ", retcode=" + retCode);
9242                        // we don't consider this to be a failure of the core package deletion
9243                    }
9244                }
9245            }
9246        }
9247
9248        boolean doPostDeleteLI(boolean delete) {
9249            // XXX err, shouldn't we respect the delete flag?
9250            cleanUpResourcesLI();
9251            return true;
9252        }
9253    }
9254
9255    private boolean isAsecExternal(String cid) {
9256        final String asecPath = PackageHelper.getSdFilesystem(cid);
9257        return !asecPath.startsWith(mAsecInternalPath);
9258    }
9259
9260    /**
9261     * Extract the MountService "container ID" from the full code path of an
9262     * .apk.
9263     */
9264    static String cidFromCodePath(String fullCodePath) {
9265        int eidx = fullCodePath.lastIndexOf("/");
9266        String subStr1 = fullCodePath.substring(0, eidx);
9267        int sidx = subStr1.lastIndexOf("/");
9268        return subStr1.substring(sidx+1, eidx);
9269    }
9270
9271    /**
9272     * Logic to handle installation of ASEC applications, including copying and
9273     * renaming logic.
9274     */
9275    class AsecInstallArgs extends InstallArgs {
9276        // TODO: teach about handling cluster directories
9277
9278        static final String RES_FILE_NAME = "pkg.apk";
9279        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9280
9281        String cid;
9282        String packagePath;
9283        String resourcePath;
9284        String libraryPath;
9285
9286        /** New install */
9287        AsecInstallArgs(InstallParams params) {
9288            super(params.originFile, params.originTrusted, params.observer, params.flags,
9289                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9290                    params.packageInstructionSetOverride, params.packageAbiOverride);
9291        }
9292
9293        /** Existing install */
9294        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9295                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9296            super(null, false, null, (isExternal ? INSTALL_EXTERNAL : 0)
9297                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9298                    instructionSet, null);
9299            // Extract cid from fullCodePath
9300            int eidx = fullCodePath.lastIndexOf("/");
9301            String subStr1 = fullCodePath.substring(0, eidx);
9302            int sidx = subStr1.lastIndexOf("/");
9303            cid = subStr1.substring(sidx+1, eidx);
9304            setCachePath(subStr1);
9305        }
9306
9307        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9308            super(null, false, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9309                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9310                    instructionSet, null);
9311            this.cid = cid;
9312            setCachePath(PackageHelper.getSdDir(cid));
9313        }
9314
9315        /** New install from existing */
9316        AsecInstallArgs(File originPackageFile, String cid, String instructionSet,
9317                boolean isExternal, boolean isForwardLocked) {
9318            super(originPackageFile, true, null, (isExternal ? INSTALL_EXTERNAL : 0)
9319                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9320                    instructionSet, null);
9321            this.cid = cid;
9322        }
9323
9324        void createCopyFile() {
9325            cid = getTempContainerId();
9326        }
9327
9328        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9329            return imcs.checkExternalFreeStorage(originFile.getAbsolutePath(), isFwdLocked(),
9330                    abiOverride);
9331        }
9332
9333        private final boolean isExternal() {
9334            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9335        }
9336
9337        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9338            if (temp) {
9339                createCopyFile();
9340            } else {
9341                /*
9342                 * Pre-emptively destroy the container since it's destroyed if
9343                 * copying fails due to it existing anyway.
9344                 */
9345                PackageHelper.destroySdDir(cid);
9346            }
9347
9348            final String newCachePath = imcs.copyPackageToContainer(
9349                    originFile.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9350                    isFwdLocked(), abiOverride);
9351
9352            if (newCachePath != null) {
9353                setCachePath(newCachePath);
9354                return PackageManager.INSTALL_SUCCEEDED;
9355            } else {
9356                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9357            }
9358        }
9359
9360        @Override
9361        String getCodePath() {
9362            return packagePath;
9363        }
9364
9365        @Override
9366        String getResourcePath() {
9367            return resourcePath;
9368        }
9369
9370        @Override
9371        String getNativeLibraryPath() {
9372            return libraryPath;
9373        }
9374
9375        int doPreInstall(int status) {
9376            if (status != PackageManager.INSTALL_SUCCEEDED) {
9377                // Destroy container
9378                PackageHelper.destroySdDir(cid);
9379            } else {
9380                boolean mounted = PackageHelper.isContainerMounted(cid);
9381                if (!mounted) {
9382                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9383                            Process.SYSTEM_UID);
9384                    if (newCachePath != null) {
9385                        setCachePath(newCachePath);
9386                    } else {
9387                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9388                    }
9389                }
9390            }
9391            return status;
9392        }
9393
9394        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9395            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9396            String newCachePath = null;
9397            if (PackageHelper.isContainerMounted(cid)) {
9398                // Unmount the container
9399                if (!PackageHelper.unMountSdDir(cid)) {
9400                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9401                    return false;
9402                }
9403            }
9404            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9405                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9406                        " which might be stale. Will try to clean up.");
9407                // Clean up the stale container and proceed to recreate.
9408                if (!PackageHelper.destroySdDir(newCacheId)) {
9409                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9410                    return false;
9411                }
9412                // Successfully cleaned up stale container. Try to rename again.
9413                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9414                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9415                            + " inspite of cleaning it up.");
9416                    return false;
9417                }
9418            }
9419            if (!PackageHelper.isContainerMounted(newCacheId)) {
9420                Slog.w(TAG, "Mounting container " + newCacheId);
9421                newCachePath = PackageHelper.mountSdDir(newCacheId,
9422                        getEncryptKey(), Process.SYSTEM_UID);
9423            } else {
9424                newCachePath = PackageHelper.getSdDir(newCacheId);
9425            }
9426            if (newCachePath == null) {
9427                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9428                return false;
9429            }
9430            Log.i(TAG, "Succesfully renamed " + cid +
9431                    " to " + newCacheId +
9432                    " at new path: " + newCachePath);
9433            cid = newCacheId;
9434            setCachePath(newCachePath);
9435
9436            // TODO: extend to support split APKs
9437            pkg.codePath = getCodePath();
9438            pkg.baseCodePath = getCodePath();
9439            pkg.splitCodePaths = null;
9440
9441            pkg.applicationInfo.setCodePath(getCodePath());
9442            pkg.applicationInfo.setBaseCodePath(getCodePath());
9443            pkg.applicationInfo.setSplitCodePaths(null);
9444            pkg.applicationInfo.setResourcePath(getResourcePath());
9445            pkg.applicationInfo.setBaseResourcePath(getResourcePath());
9446            pkg.applicationInfo.setSplitResourcePaths(null);
9447            pkg.applicationInfo.nativeLibraryDir = getNativeLibraryPath();
9448
9449            return true;
9450        }
9451
9452        private void setCachePath(String newCachePath) {
9453            File cachePath = new File(newCachePath);
9454            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9455            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9456
9457            if (isFwdLocked()) {
9458                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9459            } else {
9460                resourcePath = packagePath;
9461            }
9462        }
9463
9464        int doPostInstall(int status, int uid) {
9465            if (status != PackageManager.INSTALL_SUCCEEDED) {
9466                cleanUp();
9467            } else {
9468                final int groupOwner;
9469                final String protectedFile;
9470                if (isFwdLocked()) {
9471                    groupOwner = UserHandle.getSharedAppGid(uid);
9472                    protectedFile = RES_FILE_NAME;
9473                } else {
9474                    groupOwner = -1;
9475                    protectedFile = null;
9476                }
9477
9478                if (uid < Process.FIRST_APPLICATION_UID
9479                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9480                    Slog.e(TAG, "Failed to finalize " + cid);
9481                    PackageHelper.destroySdDir(cid);
9482                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9483                }
9484
9485                boolean mounted = PackageHelper.isContainerMounted(cid);
9486                if (!mounted) {
9487                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9488                }
9489            }
9490            return status;
9491        }
9492
9493        private void cleanUp() {
9494            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9495
9496            // Destroy secure container
9497            PackageHelper.destroySdDir(cid);
9498        }
9499
9500        void cleanUpResourcesLI() {
9501            String sourceFile = getCodePath();
9502            // Remove dex file
9503            if (instructionSet == null) {
9504                throw new IllegalStateException("instructionSet == null");
9505            }
9506            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9507            if (retCode < 0) {
9508                Slog.w(TAG, "Couldn't remove dex file for package: "
9509                        + " at location "
9510                        + sourceFile.toString() + ", retcode=" + retCode);
9511                // we don't consider this to be a failure of the core package deletion
9512            }
9513            cleanUp();
9514        }
9515
9516        boolean matchContainer(String app) {
9517            if (cid.startsWith(app)) {
9518                return true;
9519            }
9520            return false;
9521        }
9522
9523        String getPackageName() {
9524            return getAsecPackageName(cid);
9525        }
9526
9527        boolean doPostDeleteLI(boolean delete) {
9528            boolean ret = false;
9529            boolean mounted = PackageHelper.isContainerMounted(cid);
9530            if (mounted) {
9531                // Unmount first
9532                ret = PackageHelper.unMountSdDir(cid);
9533            }
9534            if (ret && delete) {
9535                cleanUpResourcesLI();
9536            }
9537            return ret;
9538        }
9539
9540        @Override
9541        int doPreCopy() {
9542            if (isFwdLocked()) {
9543                if (!PackageHelper.fixSdPermissions(cid,
9544                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9545                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9546                }
9547            }
9548
9549            return PackageManager.INSTALL_SUCCEEDED;
9550        }
9551
9552        @Override
9553        int doPostCopy(int uid) {
9554            if (isFwdLocked()) {
9555                if (uid < Process.FIRST_APPLICATION_UID
9556                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9557                                RES_FILE_NAME)) {
9558                    Slog.e(TAG, "Failed to finalize " + cid);
9559                    PackageHelper.destroySdDir(cid);
9560                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9561                }
9562            }
9563
9564            return PackageManager.INSTALL_SUCCEEDED;
9565        }
9566    }
9567
9568    static String getAsecPackageName(String packageCid) {
9569        int idx = packageCid.lastIndexOf("-");
9570        if (idx == -1) {
9571            return packageCid;
9572        }
9573        return packageCid.substring(0, idx);
9574    }
9575
9576    // Utility method used to create code paths based on package name and available index.
9577    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9578        String idxStr = "";
9579        int idx = 1;
9580        // Fall back to default value of idx=1 if prefix is not
9581        // part of oldCodePath
9582        if (oldCodePath != null) {
9583            String subStr = oldCodePath;
9584            // Drop the suffix right away
9585            if (suffix != null && subStr.endsWith(suffix)) {
9586                subStr = subStr.substring(0, subStr.length() - suffix.length());
9587            }
9588            // If oldCodePath already contains prefix find out the
9589            // ending index to either increment or decrement.
9590            int sidx = subStr.lastIndexOf(prefix);
9591            if (sidx != -1) {
9592                subStr = subStr.substring(sidx + prefix.length());
9593                if (subStr != null) {
9594                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9595                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9596                    }
9597                    try {
9598                        idx = Integer.parseInt(subStr);
9599                        if (idx <= 1) {
9600                            idx++;
9601                        } else {
9602                            idx--;
9603                        }
9604                    } catch(NumberFormatException e) {
9605                    }
9606                }
9607            }
9608        }
9609        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9610        return prefix + idxStr;
9611    }
9612
9613    // Utility method used to ignore ADD/REMOVE events
9614    // by directory observer.
9615    private static boolean ignoreCodePath(String fullPathStr) {
9616        String apkName = deriveCodePathName(fullPathStr);
9617        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9618        if (idx != -1 && ((idx+1) < apkName.length())) {
9619            // Make sure the package ends with a numeral
9620            String version = apkName.substring(idx+1);
9621            try {
9622                Integer.parseInt(version);
9623                return true;
9624            } catch (NumberFormatException e) {}
9625        }
9626        return false;
9627    }
9628
9629    // Utility method that returns the relative package path with respect
9630    // to the installation directory. Like say for /data/data/com.test-1.apk
9631    // string com.test-1 is returned.
9632    static String deriveCodePathName(String codePath) {
9633        if (codePath == null) {
9634            return null;
9635        }
9636        final File codeFile = new File(codePath);
9637        final String name = codeFile.getName();
9638        if (codeFile.isDirectory()) {
9639            return name;
9640        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9641            final int lastDot = name.lastIndexOf('.');
9642            return name.substring(0, lastDot);
9643        } else {
9644            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9645            return null;
9646        }
9647    }
9648
9649    class PackageInstalledInfo {
9650        String name;
9651        int uid;
9652        // The set of users that originally had this package installed.
9653        int[] origUsers;
9654        // The set of users that now have this package installed.
9655        int[] newUsers;
9656        PackageParser.Package pkg;
9657        int returnCode;
9658        PackageRemovedInfo removedInfo;
9659
9660        // In some error cases we want to convey more info back to the observer
9661        String origPackage;
9662        String origPermission;
9663    }
9664
9665    /*
9666     * Install a non-existing package.
9667     */
9668    private void installNewPackageLI(PackageParser.Package pkg,
9669            int parseFlags, int scanMode, UserHandle user,
9670            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9671        // Remember this for later, in case we need to rollback this install
9672        String pkgName = pkg.packageName;
9673
9674        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9675        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9676        synchronized(mPackages) {
9677            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9678                // A package with the same name is already installed, though
9679                // it has been renamed to an older name.  The package we
9680                // are trying to install should be installed as an update to
9681                // the existing one, but that has not been requested, so bail.
9682                Slog.w(TAG, "Attempt to re-install " + pkgName
9683                        + " without first uninstalling package running as "
9684                        + mSettings.mRenamedPackages.get(pkgName));
9685                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9686                return;
9687            }
9688            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9689                // Don't allow installation over an existing package with the same name.
9690                Slog.w(TAG, "Attempt to re-install " + pkgName
9691                        + " without first uninstalling.");
9692                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9693                return;
9694            }
9695        }
9696        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9697        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9698                System.currentTimeMillis(), user, abiOverride);
9699        if (newPackage == null) {
9700            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9701            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9702                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9703            }
9704        } else {
9705            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9706            // delete the partially installed application. the data directory will have to be
9707            // restored if it was already existing
9708            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9709                // remove package from internal structures.  Note that we want deletePackageX to
9710                // delete the package data and cache directories that it created in
9711                // scanPackageLocked, unless those directories existed before we even tried to
9712                // install.
9713                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9714                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9715                                res.removedInfo, true);
9716            }
9717        }
9718    }
9719
9720    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9721        // Upgrade keysets are being used.  Determine if new package has a superset of the
9722        // required keys.
9723        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9724        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9725        Set<Long> newSigningKeyIds = new ArraySet<Long>();
9726        for (PublicKey pk : newPkg.mSigningKeys) {
9727            newSigningKeyIds.add(ksms.getIdForPublicKey(pk));
9728        }
9729        //remove PUBLIC_KEY_NOT_FOUND, although not necessary
9730        newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND);
9731        for (int i = 0; i < upgradeKeySets.length; i++) {
9732            if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) {
9733                return true;
9734            }
9735        }
9736        return false;
9737    }
9738
9739    private void replacePackageLI(PackageParser.Package pkg,
9740            int parseFlags, int scanMode, UserHandle user,
9741            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9742        PackageParser.Package oldPackage;
9743        String pkgName = pkg.packageName;
9744        int[] allUsers;
9745        boolean[] perUserInstalled;
9746
9747        // First find the old package info and check signatures
9748        synchronized(mPackages) {
9749            oldPackage = mPackages.get(pkgName);
9750            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9751            PackageSetting ps = mSettings.mPackages.get(pkgName);
9752            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9753                // default to original signature matching
9754                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9755                    != PackageManager.SIGNATURE_MATCH) {
9756                    Slog.w(TAG, "New package has a different signature: " + pkgName);
9757                    res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9758                    return;
9759                }
9760            } else {
9761                if(!checkUpgradeKeySetLP(ps, pkg)) {
9762                    Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: "
9763                           + pkgName);
9764                    res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9765                    return;
9766                }
9767            }
9768
9769            // In case of rollback, remember per-user/profile install state
9770            allUsers = sUserManager.getUserIds();
9771            perUserInstalled = new boolean[allUsers.length];
9772            for (int i = 0; i < allUsers.length; i++) {
9773                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9774            }
9775        }
9776        boolean sysPkg = (isSystemApp(oldPackage));
9777        if (sysPkg) {
9778            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9779                    user, allUsers, perUserInstalled, installerPackageName, res,
9780                    abiOverride);
9781        } else {
9782            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9783                    user, allUsers, perUserInstalled, installerPackageName, res,
9784                    abiOverride);
9785        }
9786    }
9787
9788    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9789            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9790            int[] allUsers, boolean[] perUserInstalled,
9791            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9792        PackageParser.Package newPackage = null;
9793        String pkgName = deletedPackage.packageName;
9794        boolean deletedPkg = true;
9795        boolean updatedSettings = false;
9796
9797        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9798                + deletedPackage);
9799        long origUpdateTime;
9800        if (pkg.mExtras != null) {
9801            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9802        } else {
9803            origUpdateTime = 0;
9804        }
9805
9806        // First delete the existing package while retaining the data directory
9807        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9808                res.removedInfo, true)) {
9809            // If the existing package wasn't successfully deleted
9810            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9811            deletedPkg = false;
9812        } else {
9813            // Successfully deleted the old package. Now proceed with re-installation
9814            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9815            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9816                    System.currentTimeMillis(), user, abiOverride);
9817            if (newPackage == null) {
9818                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9819                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9820                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9821                }
9822            } else {
9823                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9824                updatedSettings = true;
9825            }
9826        }
9827
9828        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9829            // remove package from internal structures.  Note that we want deletePackageX to
9830            // delete the package data and cache directories that it created in
9831            // scanPackageLocked, unless those directories existed before we even tried to
9832            // install.
9833            if(updatedSettings) {
9834                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9835                deletePackageLI(
9836                        pkgName, null, true, allUsers, perUserInstalled,
9837                        PackageManager.DELETE_KEEP_DATA,
9838                                res.removedInfo, true);
9839            }
9840            // Since we failed to install the new package we need to restore the old
9841            // package that we deleted.
9842            if (deletedPkg) {
9843                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9844                File restoreFile = new File(deletedPackage.codePath);
9845                // Parse old package
9846                boolean oldOnSd = isExternal(deletedPackage);
9847                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9848                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9849                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9850                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9851                        | SCAN_UPDATE_TIME;
9852                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9853                        origUpdateTime, null, null) == null) {
9854                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9855                    return;
9856                }
9857                // Restore of old package succeeded. Update permissions.
9858                // writer
9859                synchronized (mPackages) {
9860                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9861                            UPDATE_PERMISSIONS_ALL);
9862                    // can downgrade to reader
9863                    mSettings.writeLPr();
9864                }
9865                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9866            }
9867        }
9868    }
9869
9870    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9871            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9872            int[] allUsers, boolean[] perUserInstalled,
9873            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9874        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9875                + ", old=" + deletedPackage);
9876        PackageParser.Package newPackage = null;
9877        boolean updatedSettings = false;
9878        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9879                PackageParser.PARSE_IS_SYSTEM;
9880        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9881            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9882        }
9883        String packageName = deletedPackage.packageName;
9884        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9885        if (packageName == null) {
9886            Slog.w(TAG, "Attempt to delete null packageName.");
9887            return;
9888        }
9889        PackageParser.Package oldPkg;
9890        PackageSetting oldPkgSetting;
9891        // reader
9892        synchronized (mPackages) {
9893            oldPkg = mPackages.get(packageName);
9894            oldPkgSetting = mSettings.mPackages.get(packageName);
9895            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9896                    (oldPkgSetting == null)) {
9897                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9898                return;
9899            }
9900        }
9901
9902        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9903
9904        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9905        res.removedInfo.removedPackage = packageName;
9906        // Remove existing system package
9907        removePackageLI(oldPkgSetting, true);
9908        // writer
9909        synchronized (mPackages) {
9910            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9911                // We didn't need to disable the .apk as a current system package,
9912                // which means we are replacing another update that is already
9913                // installed.  We need to make sure to delete the older one's .apk.
9914                res.removedInfo.args = createInstallArgsForExisting(0,
9915                        deletedPackage.applicationInfo.getCodePath(),
9916                        deletedPackage.applicationInfo.getResourcePath(),
9917                        deletedPackage.applicationInfo.nativeLibraryDir,
9918                        getAppInstructionSet(deletedPackage.applicationInfo));
9919            } else {
9920                res.removedInfo.args = null;
9921            }
9922        }
9923
9924        // Successfully disabled the old package. Now proceed with re-installation
9925        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9926        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9927        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
9928        if (newPackage == null) {
9929            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9930            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9931                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9932            }
9933        } else {
9934            if (newPackage.mExtras != null) {
9935                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9936                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9937                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9938
9939                // is the update attempting to change shared user? that isn't going to work...
9940                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9941                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9942                            + " to " + newPkgSetting.sharedUser);
9943                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9944                    updatedSettings = true;
9945                }
9946            }
9947
9948            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9949                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9950                updatedSettings = true;
9951            }
9952        }
9953
9954        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9955            // Re installation failed. Restore old information
9956            // Remove new pkg information
9957            if (newPackage != null) {
9958                removeInstalledPackageLI(newPackage, true);
9959            }
9960            // Add back the old system package
9961            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
9962            // Restore the old system information in Settings
9963            synchronized(mPackages) {
9964                if (updatedSettings) {
9965                    mSettings.enableSystemPackageLPw(packageName);
9966                    mSettings.setInstallerPackageName(packageName,
9967                            oldPkgSetting.installerPackageName);
9968                }
9969                mSettings.writeLPr();
9970            }
9971        }
9972    }
9973
9974    // Utility method used to move dex files during install.
9975    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
9976        // TODO: extend to move split APK dex files
9977        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9978            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
9979            int retCode = mInstaller.movedex(oldCodePath, newPackage.baseCodePath,
9980                                             instructionSet);
9981            if (retCode != 0) {
9982                /*
9983                 * Programs may be lazily run through dexopt, so the
9984                 * source may not exist. However, something seems to
9985                 * have gone wrong, so note that dexopt needs to be
9986                 * run again and remove the source file. In addition,
9987                 * remove the target to make sure there isn't a stale
9988                 * file from a previous version of the package.
9989                 */
9990                newPackage.mDexOptNeeded = true;
9991                mInstaller.rmdex(oldCodePath, instructionSet);
9992                mInstaller.rmdex(newPackage.baseCodePath, instructionSet);
9993            }
9994        }
9995        return PackageManager.INSTALL_SUCCEEDED;
9996    }
9997
9998    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9999            int[] allUsers, boolean[] perUserInstalled,
10000            PackageInstalledInfo res) {
10001        String pkgName = newPackage.packageName;
10002        synchronized (mPackages) {
10003            //write settings. the installStatus will be incomplete at this stage.
10004            //note that the new package setting would have already been
10005            //added to mPackages. It hasn't been persisted yet.
10006            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10007            mSettings.writeLPr();
10008        }
10009
10010        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10011
10012        synchronized (mPackages) {
10013            updatePermissionsLPw(newPackage.packageName, newPackage,
10014                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10015                            ? UPDATE_PERMISSIONS_ALL : 0));
10016            // For system-bundled packages, we assume that installing an upgraded version
10017            // of the package implies that the user actually wants to run that new code,
10018            // so we enable the package.
10019            if (isSystemApp(newPackage)) {
10020                // NB: implicit assumption that system package upgrades apply to all users
10021                if (DEBUG_INSTALL) {
10022                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10023                }
10024                PackageSetting ps = mSettings.mPackages.get(pkgName);
10025                if (ps != null) {
10026                    if (res.origUsers != null) {
10027                        for (int userHandle : res.origUsers) {
10028                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10029                                    userHandle, installerPackageName);
10030                        }
10031                    }
10032                    // Also convey the prior install/uninstall state
10033                    if (allUsers != null && perUserInstalled != null) {
10034                        for (int i = 0; i < allUsers.length; i++) {
10035                            if (DEBUG_INSTALL) {
10036                                Slog.d(TAG, "    user " + allUsers[i]
10037                                        + " => " + perUserInstalled[i]);
10038                            }
10039                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10040                        }
10041                        // these install state changes will be persisted in the
10042                        // upcoming call to mSettings.writeLPr().
10043                    }
10044                }
10045            }
10046            res.name = pkgName;
10047            res.uid = newPackage.applicationInfo.uid;
10048            res.pkg = newPackage;
10049            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10050            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10051            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10052            //to update install status
10053            mSettings.writeLPr();
10054        }
10055    }
10056
10057    private void installPackageLI(InstallArgs args, boolean newInstall, PackageInstalledInfo res) {
10058        int pFlags = args.flags;
10059        String installerPackageName = args.installerPackageName;
10060        File tmpPackageFile = new File(args.getCodePath());
10061        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10062        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10063        boolean replace = false;
10064        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10065                | (newInstall ? SCAN_NEW_INSTALL : 0);
10066        // Result object to be returned
10067        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10068
10069        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10070        // Retrieve PackageSettings and parse package
10071        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10072                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10073                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10074        PackageParser pp = new PackageParser();
10075        pp.setSeparateProcesses(mSeparateProcesses);
10076        pp.setDisplayMetrics(mMetrics);
10077
10078        final PackageParser.Package pkg;
10079        try {
10080            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10081        } catch (PackageParserException e) {
10082            res.returnCode = e.error;
10083            return;
10084        }
10085
10086        String pkgName = res.name = pkg.packageName;
10087        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10088            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10089                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10090                return;
10091            }
10092        }
10093
10094        try {
10095            pp.collectCertificates(pkg, parseFlags);
10096            pp.collectManifestDigest(pkg);
10097        } catch (PackageParserException e) {
10098            res.returnCode = e.error;
10099            return;
10100        }
10101
10102        /* If the installer passed in a manifest digest, compare it now. */
10103        if (args.manifestDigest != null) {
10104            if (DEBUG_INSTALL) {
10105                final String parsedManifest = pkg.manifestDigest == null ? "null"
10106                        : pkg.manifestDigest.toString();
10107                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10108                        + parsedManifest);
10109            }
10110
10111            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10112                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10113                return;
10114            }
10115        } else if (DEBUG_INSTALL) {
10116            final String parsedManifest = pkg.manifestDigest == null
10117                    ? "null" : pkg.manifestDigest.toString();
10118            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10119        }
10120
10121        // Get rid of all references to package scan path via parser.
10122        pp = null;
10123        String oldCodePath = null;
10124        boolean systemApp = false;
10125        synchronized (mPackages) {
10126            // Check whether the newly-scanned package wants to define an already-defined perm
10127            int N = pkg.permissions.size();
10128            for (int i = N-1; i >= 0; i--) {
10129                PackageParser.Permission perm = pkg.permissions.get(i);
10130                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10131                if (bp != null) {
10132                    // If the defining package is signed with our cert, it's okay.  This
10133                    // also includes the "updating the same package" case, of course.
10134                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10135                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10136                        // If the owning package is the system itself, we log but allow
10137                        // install to proceed; we fail the install on all other permission
10138                        // redefinitions.
10139                        if (!bp.sourcePackage.equals("android")) {
10140                            Slog.w(TAG, "Package " + pkg.packageName
10141                                    + " attempting to redeclare permission " + perm.info.name
10142                                    + " already owned by " + bp.sourcePackage);
10143                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10144                            res.origPermission = perm.info.name;
10145                            res.origPackage = bp.sourcePackage;
10146                            return;
10147                        } else {
10148                            Slog.w(TAG, "Package " + pkg.packageName
10149                                    + " attempting to redeclare system permission "
10150                                    + perm.info.name + "; ignoring new declaration");
10151                            pkg.permissions.remove(i);
10152                        }
10153                    }
10154                }
10155            }
10156
10157            // Check if installing already existing package
10158            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10159                String oldName = mSettings.mRenamedPackages.get(pkgName);
10160                if (pkg.mOriginalPackages != null
10161                        && pkg.mOriginalPackages.contains(oldName)
10162                        && mPackages.containsKey(oldName)) {
10163                    // This package is derived from an original package,
10164                    // and this device has been updating from that original
10165                    // name.  We must continue using the original name, so
10166                    // rename the new package here.
10167                    pkg.setPackageName(oldName);
10168                    pkgName = pkg.packageName;
10169                    replace = true;
10170                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10171                            + oldName + " pkgName=" + pkgName);
10172                } else if (mPackages.containsKey(pkgName)) {
10173                    // This package, under its official name, already exists
10174                    // on the device; we should replace it.
10175                    replace = true;
10176                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10177                }
10178            }
10179            PackageSetting ps = mSettings.mPackages.get(pkgName);
10180            if (ps != null) {
10181                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10182                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10183                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10184                    systemApp = (ps.pkg.applicationInfo.flags &
10185                            ApplicationInfo.FLAG_SYSTEM) != 0;
10186                }
10187                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10188            }
10189        }
10190
10191        if (systemApp && onSd) {
10192            // Disable updates to system apps on sdcard
10193            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10194            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10195            return;
10196        }
10197
10198        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10199            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10200            return;
10201        }
10202
10203        if (replace) {
10204            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10205                    installerPackageName, res, args.abiOverride);
10206        } else {
10207            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10208                    installerPackageName, res, args.abiOverride);
10209        }
10210        synchronized (mPackages) {
10211            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10212            if (ps != null) {
10213                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10214            }
10215        }
10216    }
10217
10218    private static boolean isForwardLocked(PackageParser.Package pkg) {
10219        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10220    }
10221
10222
10223    private boolean isForwardLocked(PackageSetting ps) {
10224        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10225    }
10226
10227    private static boolean isExternal(PackageParser.Package pkg) {
10228        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10229    }
10230
10231    private static boolean isExternal(PackageSetting ps) {
10232        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10233    }
10234
10235    private static boolean isSystemApp(PackageParser.Package pkg) {
10236        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10237    }
10238
10239    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10240        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10241    }
10242
10243    private static boolean isSystemApp(ApplicationInfo info) {
10244        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10245    }
10246
10247    private static boolean isSystemApp(PackageSetting ps) {
10248        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10249    }
10250
10251    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10252        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10253    }
10254
10255    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10256        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10257    }
10258
10259    private int packageFlagsToInstallFlags(PackageSetting ps) {
10260        int installFlags = 0;
10261        if (isExternal(ps)) {
10262            installFlags |= PackageManager.INSTALL_EXTERNAL;
10263        }
10264        if (isForwardLocked(ps)) {
10265            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10266        }
10267        return installFlags;
10268    }
10269
10270    private void deleteTempPackageFiles() {
10271        final FilenameFilter filter = new FilenameFilter() {
10272            public boolean accept(File dir, String name) {
10273                return name.startsWith("vmdl") && name.endsWith(".tmp");
10274            }
10275        };
10276        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10277        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10278    }
10279
10280    private static final void deleteTempPackageFilesInDirectory(File directory,
10281            FilenameFilter filter) {
10282        final File[] files = directory.listFiles(filter);
10283        if (!ArrayUtils.isEmpty(files)) {
10284            for (File file : files) {
10285                if (file.isDirectory()) {
10286                    FileUtils.deleteContents(file);
10287                    file.delete();
10288                } else if (file.isFile()) {
10289                    file.delete();
10290                }
10291            }
10292        }
10293    }
10294
10295    private File createTempPackageDir(File installDir) throws IOException {
10296        int n = 0;
10297        while (n++ < 32) {
10298            final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp");
10299            try {
10300                Os.mkdir(file.getAbsolutePath(), 0755);
10301                Os.chmod(file.getAbsolutePath(), 0755);
10302                if (!SELinux.restorecon(file)) {
10303                    throw new IOException("Failed to restorecon");
10304                }
10305                return file;
10306            } catch (ErrnoException e) {
10307                if (e.errno == EEXIST) continue;
10308                throw e.rethrowAsIOException();
10309            }
10310        }
10311        throw new IOException("Failed to create temp directory");
10312    }
10313
10314    private File createTempPackageFile(File installDir) throws IOException {
10315        int n = 0;
10316        while (n++ < 32) {
10317            final File file = new File(installDir, "vmdl" + mTempFileRandom.nextInt() + ".tmp");
10318            try {
10319                final FileDescriptor fd = Os.open(file.getAbsolutePath(),
10320                        O_RDWR | O_CREAT | O_EXCL, 0644);
10321                IoUtils.closeQuietly(fd);
10322                Os.chmod(file.getAbsolutePath(), 0644);
10323                if (!SELinux.restorecon(file)) {
10324                    throw new IOException("Failed to restorecon");
10325                }
10326                return file;
10327            } catch (ErrnoException e) {
10328                if (e.errno == EEXIST) continue;
10329                throw e.rethrowAsIOException();
10330            }
10331        }
10332        throw new IOException("Failed to create temp file");
10333    }
10334
10335    @Override
10336    public void deletePackageAsUser(final String packageName,
10337                                    final IPackageDeleteObserver observer,
10338                                    final int userId, final int flags) {
10339        mContext.enforceCallingOrSelfPermission(
10340                android.Manifest.permission.DELETE_PACKAGES, null);
10341        final int uid = Binder.getCallingUid();
10342        if (UserHandle.getUserId(uid) != userId) {
10343            mContext.enforceCallingPermission(
10344                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10345                    "deletePackage for user " + userId);
10346        }
10347        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10348            try {
10349                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10350            } catch (RemoteException re) {
10351            }
10352            return;
10353        }
10354
10355        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10356        // Queue up an async operation since the package deletion may take a little while.
10357        mHandler.post(new Runnable() {
10358            public void run() {
10359                mHandler.removeCallbacks(this);
10360                final int returnCode = deletePackageX(packageName, userId, flags);
10361                if (observer != null) {
10362                    try {
10363                        observer.packageDeleted(packageName, returnCode);
10364                    } catch (RemoteException e) {
10365                        Log.i(TAG, "Observer no longer exists.");
10366                    } //end catch
10367                } //end if
10368            } //end run
10369        });
10370    }
10371
10372    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10373        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10374                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10375        try {
10376            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10377                    || dpm.isDeviceOwner(packageName))) {
10378                return true;
10379            }
10380        } catch (RemoteException e) {
10381        }
10382        return false;
10383    }
10384
10385    /**
10386     *  This method is an internal method that could be get invoked either
10387     *  to delete an installed package or to clean up a failed installation.
10388     *  After deleting an installed package, a broadcast is sent to notify any
10389     *  listeners that the package has been installed. For cleaning up a failed
10390     *  installation, the broadcast is not necessary since the package's
10391     *  installation wouldn't have sent the initial broadcast either
10392     *  The key steps in deleting a package are
10393     *  deleting the package information in internal structures like mPackages,
10394     *  deleting the packages base directories through installd
10395     *  updating mSettings to reflect current status
10396     *  persisting settings for later use
10397     *  sending a broadcast if necessary
10398     */
10399    private int deletePackageX(String packageName, int userId, int flags) {
10400        final PackageRemovedInfo info = new PackageRemovedInfo();
10401        final boolean res;
10402
10403        if (isPackageDeviceAdmin(packageName, userId)) {
10404            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10405            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10406        }
10407
10408        boolean removedForAllUsers = false;
10409        boolean systemUpdate = false;
10410
10411        // for the uninstall-updates case and restricted profiles, remember the per-
10412        // userhandle installed state
10413        int[] allUsers;
10414        boolean[] perUserInstalled;
10415        synchronized (mPackages) {
10416            PackageSetting ps = mSettings.mPackages.get(packageName);
10417            allUsers = sUserManager.getUserIds();
10418            perUserInstalled = new boolean[allUsers.length];
10419            for (int i = 0; i < allUsers.length; i++) {
10420                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10421            }
10422        }
10423
10424        synchronized (mInstallLock) {
10425            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10426            res = deletePackageLI(packageName,
10427                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10428                            ? UserHandle.ALL : new UserHandle(userId),
10429                    true, allUsers, perUserInstalled,
10430                    flags | REMOVE_CHATTY, info, true);
10431            systemUpdate = info.isRemovedPackageSystemUpdate;
10432            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10433                removedForAllUsers = true;
10434            }
10435            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10436                    + " removedForAllUsers=" + removedForAllUsers);
10437        }
10438
10439        if (res) {
10440            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10441
10442            // If the removed package was a system update, the old system package
10443            // was re-enabled; we need to broadcast this information
10444            if (systemUpdate) {
10445                Bundle extras = new Bundle(1);
10446                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10447                        ? info.removedAppId : info.uid);
10448                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10449
10450                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10451                        extras, null, null, null);
10452                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10453                        extras, null, null, null);
10454                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10455                        null, packageName, null, null);
10456            }
10457        }
10458        // Force a gc here.
10459        Runtime.getRuntime().gc();
10460        // Delete the resources here after sending the broadcast to let
10461        // other processes clean up before deleting resources.
10462        if (info.args != null) {
10463            synchronized (mInstallLock) {
10464                info.args.doPostDeleteLI(true);
10465            }
10466        }
10467
10468        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10469    }
10470
10471    static class PackageRemovedInfo {
10472        String removedPackage;
10473        int uid = -1;
10474        int removedAppId = -1;
10475        int[] removedUsers = null;
10476        boolean isRemovedPackageSystemUpdate = false;
10477        // Clean up resources deleted packages.
10478        InstallArgs args = null;
10479
10480        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10481            Bundle extras = new Bundle(1);
10482            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10483            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10484            if (replacing) {
10485                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10486            }
10487            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10488            if (removedPackage != null) {
10489                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10490                        extras, null, null, removedUsers);
10491                if (fullRemove && !replacing) {
10492                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10493                            extras, null, null, removedUsers);
10494                }
10495            }
10496            if (removedAppId >= 0) {
10497                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10498                        removedUsers);
10499            }
10500        }
10501    }
10502
10503    /*
10504     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10505     * flag is not set, the data directory is removed as well.
10506     * make sure this flag is set for partially installed apps. If not its meaningless to
10507     * delete a partially installed application.
10508     */
10509    private void removePackageDataLI(PackageSetting ps,
10510            int[] allUserHandles, boolean[] perUserInstalled,
10511            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10512        String packageName = ps.name;
10513        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10514        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10515        // Retrieve object to delete permissions for shared user later on
10516        final PackageSetting deletedPs;
10517        // reader
10518        synchronized (mPackages) {
10519            deletedPs = mSettings.mPackages.get(packageName);
10520            if (outInfo != null) {
10521                outInfo.removedPackage = packageName;
10522                outInfo.removedUsers = deletedPs != null
10523                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10524                        : null;
10525            }
10526        }
10527        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10528            removeDataDirsLI(packageName);
10529            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10530        }
10531        // writer
10532        synchronized (mPackages) {
10533            if (deletedPs != null) {
10534                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10535                    if (outInfo != null) {
10536                        mSettings.mKeySetManagerService.removeAppKeySetData(packageName);
10537                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10538                    }
10539                    if (deletedPs != null) {
10540                        updatePermissionsLPw(deletedPs.name, null, 0);
10541                        if (deletedPs.sharedUser != null) {
10542                            // remove permissions associated with package
10543                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10544                        }
10545                    }
10546                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10547                }
10548                // make sure to preserve per-user disabled state if this removal was just
10549                // a downgrade of a system app to the factory package
10550                if (allUserHandles != null && perUserInstalled != null) {
10551                    if (DEBUG_REMOVE) {
10552                        Slog.d(TAG, "Propagating install state across downgrade");
10553                    }
10554                    for (int i = 0; i < allUserHandles.length; i++) {
10555                        if (DEBUG_REMOVE) {
10556                            Slog.d(TAG, "    user " + allUserHandles[i]
10557                                    + " => " + perUserInstalled[i]);
10558                        }
10559                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10560                    }
10561                }
10562            }
10563            // can downgrade to reader
10564            if (writeSettings) {
10565                // Save settings now
10566                mSettings.writeLPr();
10567            }
10568        }
10569        if (outInfo != null) {
10570            // A user ID was deleted here. Go through all users and remove it
10571            // from KeyStore.
10572            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10573        }
10574    }
10575
10576    static boolean locationIsPrivileged(File path) {
10577        try {
10578            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10579                    .getCanonicalPath();
10580            return path.getCanonicalPath().startsWith(privilegedAppDir);
10581        } catch (IOException e) {
10582            Slog.e(TAG, "Unable to access code path " + path);
10583        }
10584        return false;
10585    }
10586
10587    /*
10588     * Tries to delete system package.
10589     */
10590    private boolean deleteSystemPackageLI(PackageSetting newPs,
10591            int[] allUserHandles, boolean[] perUserInstalled,
10592            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10593        final boolean applyUserRestrictions
10594                = (allUserHandles != null) && (perUserInstalled != null);
10595        PackageSetting disabledPs = null;
10596        // Confirm if the system package has been updated
10597        // An updated system app can be deleted. This will also have to restore
10598        // the system pkg from system partition
10599        // reader
10600        synchronized (mPackages) {
10601            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10602        }
10603        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10604                + " disabledPs=" + disabledPs);
10605        if (disabledPs == null) {
10606            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10607            return false;
10608        } else if (DEBUG_REMOVE) {
10609            Slog.d(TAG, "Deleting system pkg from data partition");
10610        }
10611        if (DEBUG_REMOVE) {
10612            if (applyUserRestrictions) {
10613                Slog.d(TAG, "Remembering install states:");
10614                for (int i = 0; i < allUserHandles.length; i++) {
10615                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10616                }
10617            }
10618        }
10619        // Delete the updated package
10620        outInfo.isRemovedPackageSystemUpdate = true;
10621        if (disabledPs.versionCode < newPs.versionCode) {
10622            // Delete data for downgrades
10623            flags &= ~PackageManager.DELETE_KEEP_DATA;
10624        } else {
10625            // Preserve data by setting flag
10626            flags |= PackageManager.DELETE_KEEP_DATA;
10627        }
10628        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10629                allUserHandles, perUserInstalled, outInfo, writeSettings);
10630        if (!ret) {
10631            return false;
10632        }
10633        // writer
10634        synchronized (mPackages) {
10635            // Reinstate the old system package
10636            mSettings.enableSystemPackageLPw(newPs.name);
10637            // Remove any native libraries from the upgraded package.
10638            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10639        }
10640        // Install the system package
10641        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10642        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10643        if (locationIsPrivileged(disabledPs.codePath)) {
10644            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10645        }
10646        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10647                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10648
10649        if (newPkg == null) {
10650            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10651                    + " with error:" + mLastScanError);
10652            return false;
10653        }
10654        // writer
10655        synchronized (mPackages) {
10656            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10657            setInternalAppNativeLibraryPath(newPkg, ps);
10658            updatePermissionsLPw(newPkg.packageName, newPkg,
10659                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10660            if (applyUserRestrictions) {
10661                if (DEBUG_REMOVE) {
10662                    Slog.d(TAG, "Propagating install state across reinstall");
10663                }
10664                for (int i = 0; i < allUserHandles.length; i++) {
10665                    if (DEBUG_REMOVE) {
10666                        Slog.d(TAG, "    user " + allUserHandles[i]
10667                                + " => " + perUserInstalled[i]);
10668                    }
10669                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10670                }
10671                // Regardless of writeSettings we need to ensure that this restriction
10672                // state propagation is persisted
10673                mSettings.writeAllUsersPackageRestrictionsLPr();
10674            }
10675            // can downgrade to reader here
10676            if (writeSettings) {
10677                mSettings.writeLPr();
10678            }
10679        }
10680        return true;
10681    }
10682
10683    private boolean deleteInstalledPackageLI(PackageSetting ps,
10684            boolean deleteCodeAndResources, int flags,
10685            int[] allUserHandles, boolean[] perUserInstalled,
10686            PackageRemovedInfo outInfo, boolean writeSettings) {
10687        if (outInfo != null) {
10688            outInfo.uid = ps.appId;
10689        }
10690
10691        // Delete package data from internal structures and also remove data if flag is set
10692        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10693
10694        // Delete application code and resources
10695        if (deleteCodeAndResources && (outInfo != null)) {
10696            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10697                    ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
10698                    getAppInstructionSetFromSettings(ps));
10699        }
10700        return true;
10701    }
10702
10703    @Override
10704    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10705            int userId) {
10706        mContext.enforceCallingOrSelfPermission(
10707                android.Manifest.permission.DELETE_PACKAGES, null);
10708        synchronized (mPackages) {
10709            PackageSetting ps = mSettings.mPackages.get(packageName);
10710            if (ps == null) {
10711                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10712                return false;
10713            }
10714            if (!ps.getInstalled(userId)) {
10715                // Can't block uninstall for an app that is not installed or enabled.
10716                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10717                return false;
10718            }
10719            ps.setBlockUninstall(blockUninstall, userId);
10720            mSettings.writePackageRestrictionsLPr(userId);
10721        }
10722        return true;
10723    }
10724
10725    @Override
10726    public boolean getBlockUninstallForUser(String packageName, int userId) {
10727        synchronized (mPackages) {
10728            PackageSetting ps = mSettings.mPackages.get(packageName);
10729            if (ps == null) {
10730                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10731                return false;
10732            }
10733            return ps.getBlockUninstall(userId);
10734        }
10735    }
10736
10737    /*
10738     * This method handles package deletion in general
10739     */
10740    private boolean deletePackageLI(String packageName, UserHandle user,
10741            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10742            int flags, PackageRemovedInfo outInfo,
10743            boolean writeSettings) {
10744        if (packageName == null) {
10745            Slog.w(TAG, "Attempt to delete null packageName.");
10746            return false;
10747        }
10748        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10749        PackageSetting ps;
10750        boolean dataOnly = false;
10751        int removeUser = -1;
10752        int appId = -1;
10753        synchronized (mPackages) {
10754            ps = mSettings.mPackages.get(packageName);
10755            if (ps == null) {
10756                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10757                return false;
10758            }
10759            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10760                    && user.getIdentifier() != UserHandle.USER_ALL) {
10761                // The caller is asking that the package only be deleted for a single
10762                // user.  To do this, we just mark its uninstalled state and delete
10763                // its data.  If this is a system app, we only allow this to happen if
10764                // they have set the special DELETE_SYSTEM_APP which requests different
10765                // semantics than normal for uninstalling system apps.
10766                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10767                ps.setUserState(user.getIdentifier(),
10768                        COMPONENT_ENABLED_STATE_DEFAULT,
10769                        false, //installed
10770                        true,  //stopped
10771                        true,  //notLaunched
10772                        false, //blocked
10773                        null, null, null,
10774                        false // blockUninstall
10775                        );
10776                if (!isSystemApp(ps)) {
10777                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10778                        // Other user still have this package installed, so all
10779                        // we need to do is clear this user's data and save that
10780                        // it is uninstalled.
10781                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10782                        removeUser = user.getIdentifier();
10783                        appId = ps.appId;
10784                        mSettings.writePackageRestrictionsLPr(removeUser);
10785                    } else {
10786                        // We need to set it back to 'installed' so the uninstall
10787                        // broadcasts will be sent correctly.
10788                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10789                        ps.setInstalled(true, user.getIdentifier());
10790                    }
10791                } else {
10792                    // This is a system app, so we assume that the
10793                    // other users still have this package installed, so all
10794                    // we need to do is clear this user's data and save that
10795                    // it is uninstalled.
10796                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10797                    removeUser = user.getIdentifier();
10798                    appId = ps.appId;
10799                    mSettings.writePackageRestrictionsLPr(removeUser);
10800                }
10801            }
10802        }
10803
10804        if (removeUser >= 0) {
10805            // From above, we determined that we are deleting this only
10806            // for a single user.  Continue the work here.
10807            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10808            if (outInfo != null) {
10809                outInfo.removedPackage = packageName;
10810                outInfo.removedAppId = appId;
10811                outInfo.removedUsers = new int[] {removeUser};
10812            }
10813            mInstaller.clearUserData(packageName, removeUser);
10814            removeKeystoreDataIfNeeded(removeUser, appId);
10815            schedulePackageCleaning(packageName, removeUser, false);
10816            return true;
10817        }
10818
10819        if (dataOnly) {
10820            // Delete application data first
10821            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10822            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10823            return true;
10824        }
10825
10826        boolean ret = false;
10827        if (isSystemApp(ps)) {
10828            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10829            // When an updated system application is deleted we delete the existing resources as well and
10830            // fall back to existing code in system partition
10831            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10832                    flags, outInfo, writeSettings);
10833        } else {
10834            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10835            // Kill application pre-emptively especially for apps on sd.
10836            killApplication(packageName, ps.appId, "uninstall pkg");
10837            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10838                    allUserHandles, perUserInstalled,
10839                    outInfo, writeSettings);
10840        }
10841
10842        return ret;
10843    }
10844
10845    private final class ClearStorageConnection implements ServiceConnection {
10846        IMediaContainerService mContainerService;
10847
10848        @Override
10849        public void onServiceConnected(ComponentName name, IBinder service) {
10850            synchronized (this) {
10851                mContainerService = IMediaContainerService.Stub.asInterface(service);
10852                notifyAll();
10853            }
10854        }
10855
10856        @Override
10857        public void onServiceDisconnected(ComponentName name) {
10858        }
10859    }
10860
10861    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10862        final boolean mounted;
10863        if (Environment.isExternalStorageEmulated()) {
10864            mounted = true;
10865        } else {
10866            final String status = Environment.getExternalStorageState();
10867
10868            mounted = status.equals(Environment.MEDIA_MOUNTED)
10869                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10870        }
10871
10872        if (!mounted) {
10873            return;
10874        }
10875
10876        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10877        int[] users;
10878        if (userId == UserHandle.USER_ALL) {
10879            users = sUserManager.getUserIds();
10880        } else {
10881            users = new int[] { userId };
10882        }
10883        final ClearStorageConnection conn = new ClearStorageConnection();
10884        if (mContext.bindServiceAsUser(
10885                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10886            try {
10887                for (int curUser : users) {
10888                    long timeout = SystemClock.uptimeMillis() + 5000;
10889                    synchronized (conn) {
10890                        long now = SystemClock.uptimeMillis();
10891                        while (conn.mContainerService == null && now < timeout) {
10892                            try {
10893                                conn.wait(timeout - now);
10894                            } catch (InterruptedException e) {
10895                            }
10896                        }
10897                    }
10898                    if (conn.mContainerService == null) {
10899                        return;
10900                    }
10901
10902                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10903                    clearDirectory(conn.mContainerService,
10904                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10905                    if (allData) {
10906                        clearDirectory(conn.mContainerService,
10907                                userEnv.buildExternalStorageAppDataDirs(packageName));
10908                        clearDirectory(conn.mContainerService,
10909                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10910                    }
10911                }
10912            } finally {
10913                mContext.unbindService(conn);
10914            }
10915        }
10916    }
10917
10918    @Override
10919    public void clearApplicationUserData(final String packageName,
10920            final IPackageDataObserver observer, final int userId) {
10921        mContext.enforceCallingOrSelfPermission(
10922                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10923        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10924        // Queue up an async operation since the package deletion may take a little while.
10925        mHandler.post(new Runnable() {
10926            public void run() {
10927                mHandler.removeCallbacks(this);
10928                final boolean succeeded;
10929                synchronized (mInstallLock) {
10930                    succeeded = clearApplicationUserDataLI(packageName, userId);
10931                }
10932                clearExternalStorageDataSync(packageName, userId, true);
10933                if (succeeded) {
10934                    // invoke DeviceStorageMonitor's update method to clear any notifications
10935                    DeviceStorageMonitorInternal
10936                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10937                    if (dsm != null) {
10938                        dsm.checkMemory();
10939                    }
10940                }
10941                if(observer != null) {
10942                    try {
10943                        observer.onRemoveCompleted(packageName, succeeded);
10944                    } catch (RemoteException e) {
10945                        Log.i(TAG, "Observer no longer exists.");
10946                    }
10947                } //end if observer
10948            } //end run
10949        });
10950    }
10951
10952    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10953        if (packageName == null) {
10954            Slog.w(TAG, "Attempt to delete null packageName.");
10955            return false;
10956        }
10957        PackageParser.Package p;
10958        boolean dataOnly = false;
10959        final int appId;
10960        synchronized (mPackages) {
10961            p = mPackages.get(packageName);
10962            if (p == null) {
10963                dataOnly = true;
10964                PackageSetting ps = mSettings.mPackages.get(packageName);
10965                if ((ps == null) || (ps.pkg == null)) {
10966                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10967                    return false;
10968                }
10969                p = ps.pkg;
10970            }
10971            if (!dataOnly) {
10972                // need to check this only for fully installed applications
10973                if (p == null) {
10974                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10975                    return false;
10976                }
10977                final ApplicationInfo applicationInfo = p.applicationInfo;
10978                if (applicationInfo == null) {
10979                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10980                    return false;
10981                }
10982            }
10983            if (p != null && p.applicationInfo != null) {
10984                appId = p.applicationInfo.uid;
10985            } else {
10986                appId = -1;
10987            }
10988        }
10989        int retCode = mInstaller.clearUserData(packageName, userId);
10990        if (retCode < 0) {
10991            Slog.w(TAG, "Couldn't remove cache files for package: "
10992                    + packageName);
10993            return false;
10994        }
10995        removeKeystoreDataIfNeeded(userId, appId);
10996        return true;
10997    }
10998
10999    /**
11000     * Remove entries from the keystore daemon. Will only remove it if the
11001     * {@code appId} is valid.
11002     */
11003    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11004        if (appId < 0) {
11005            return;
11006        }
11007
11008        final KeyStore keyStore = KeyStore.getInstance();
11009        if (keyStore != null) {
11010            if (userId == UserHandle.USER_ALL) {
11011                for (final int individual : sUserManager.getUserIds()) {
11012                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11013                }
11014            } else {
11015                keyStore.clearUid(UserHandle.getUid(userId, appId));
11016            }
11017        } else {
11018            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11019        }
11020    }
11021
11022    @Override
11023    public void deleteApplicationCacheFiles(final String packageName,
11024            final IPackageDataObserver observer) {
11025        mContext.enforceCallingOrSelfPermission(
11026                android.Manifest.permission.DELETE_CACHE_FILES, null);
11027        // Queue up an async operation since the package deletion may take a little while.
11028        final int userId = UserHandle.getCallingUserId();
11029        mHandler.post(new Runnable() {
11030            public void run() {
11031                mHandler.removeCallbacks(this);
11032                final boolean succeded;
11033                synchronized (mInstallLock) {
11034                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11035                }
11036                clearExternalStorageDataSync(packageName, userId, false);
11037                if(observer != null) {
11038                    try {
11039                        observer.onRemoveCompleted(packageName, succeded);
11040                    } catch (RemoteException e) {
11041                        Log.i(TAG, "Observer no longer exists.");
11042                    }
11043                } //end if observer
11044            } //end run
11045        });
11046    }
11047
11048    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11049        if (packageName == null) {
11050            Slog.w(TAG, "Attempt to delete null packageName.");
11051            return false;
11052        }
11053        PackageParser.Package p;
11054        synchronized (mPackages) {
11055            p = mPackages.get(packageName);
11056        }
11057        if (p == null) {
11058            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11059            return false;
11060        }
11061        final ApplicationInfo applicationInfo = p.applicationInfo;
11062        if (applicationInfo == null) {
11063            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11064            return false;
11065        }
11066        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11067        if (retCode < 0) {
11068            Slog.w(TAG, "Couldn't remove cache files for package: "
11069                       + packageName + " u" + userId);
11070            return false;
11071        }
11072        return true;
11073    }
11074
11075    @Override
11076    public void getPackageSizeInfo(final String packageName, int userHandle,
11077            final IPackageStatsObserver observer) {
11078        mContext.enforceCallingOrSelfPermission(
11079                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11080        if (packageName == null) {
11081            throw new IllegalArgumentException("Attempt to get size of null packageName");
11082        }
11083
11084        PackageStats stats = new PackageStats(packageName, userHandle);
11085
11086        /*
11087         * Queue up an async operation since the package measurement may take a
11088         * little while.
11089         */
11090        Message msg = mHandler.obtainMessage(INIT_COPY);
11091        msg.obj = new MeasureParams(stats, observer);
11092        mHandler.sendMessage(msg);
11093    }
11094
11095    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11096            PackageStats pStats) {
11097        if (packageName == null) {
11098            Slog.w(TAG, "Attempt to get size of null packageName.");
11099            return false;
11100        }
11101        PackageParser.Package p;
11102        boolean dataOnly = false;
11103        String libDirPath = null;
11104        String asecPath = null;
11105        PackageSetting ps = null;
11106        synchronized (mPackages) {
11107            p = mPackages.get(packageName);
11108            ps = mSettings.mPackages.get(packageName);
11109            if(p == null) {
11110                dataOnly = true;
11111                if((ps == null) || (ps.pkg == null)) {
11112                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11113                    return false;
11114                }
11115                p = ps.pkg;
11116            }
11117            if (ps != null) {
11118                libDirPath = ps.nativeLibraryPathString;
11119            }
11120            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11121                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11122                if (secureContainerId != null) {
11123                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11124                }
11125            }
11126        }
11127        String publicSrcDir = null;
11128        if(!dataOnly) {
11129            final ApplicationInfo applicationInfo = p.applicationInfo;
11130            if (applicationInfo == null) {
11131                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11132                return false;
11133            }
11134            if (isForwardLocked(p)) {
11135                publicSrcDir = applicationInfo.getBaseResourcePath();
11136            }
11137        }
11138        // TODO: extend to measure size of split APKs
11139        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath,
11140                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11141                pStats);
11142        if (res < 0) {
11143            return false;
11144        }
11145
11146        // Fix-up for forward-locked applications in ASEC containers.
11147        if (!isExternal(p)) {
11148            pStats.codeSize += pStats.externalCodeSize;
11149            pStats.externalCodeSize = 0L;
11150        }
11151
11152        return true;
11153    }
11154
11155
11156    @Override
11157    public void addPackageToPreferred(String packageName) {
11158        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11159    }
11160
11161    @Override
11162    public void removePackageFromPreferred(String packageName) {
11163        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11164    }
11165
11166    @Override
11167    public List<PackageInfo> getPreferredPackages(int flags) {
11168        return new ArrayList<PackageInfo>();
11169    }
11170
11171    private int getUidTargetSdkVersionLockedLPr(int uid) {
11172        Object obj = mSettings.getUserIdLPr(uid);
11173        if (obj instanceof SharedUserSetting) {
11174            final SharedUserSetting sus = (SharedUserSetting) obj;
11175            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11176            final Iterator<PackageSetting> it = sus.packages.iterator();
11177            while (it.hasNext()) {
11178                final PackageSetting ps = it.next();
11179                if (ps.pkg != null) {
11180                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11181                    if (v < vers) vers = v;
11182                }
11183            }
11184            return vers;
11185        } else if (obj instanceof PackageSetting) {
11186            final PackageSetting ps = (PackageSetting) obj;
11187            if (ps.pkg != null) {
11188                return ps.pkg.applicationInfo.targetSdkVersion;
11189            }
11190        }
11191        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11192    }
11193
11194    @Override
11195    public void addPreferredActivity(IntentFilter filter, int match,
11196            ComponentName[] set, ComponentName activity, int userId) {
11197        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11198    }
11199
11200    private void addPreferredActivityInternal(IntentFilter filter, int match,
11201            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11202        // writer
11203        int callingUid = Binder.getCallingUid();
11204        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11205        if (filter.countActions() == 0) {
11206            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11207            return;
11208        }
11209        synchronized (mPackages) {
11210            if (mContext.checkCallingOrSelfPermission(
11211                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11212                    != PackageManager.PERMISSION_GRANTED) {
11213                if (getUidTargetSdkVersionLockedLPr(callingUid)
11214                        < Build.VERSION_CODES.FROYO) {
11215                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11216                            + callingUid);
11217                    return;
11218                }
11219                mContext.enforceCallingOrSelfPermission(
11220                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11221            }
11222
11223            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11224            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11225            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11226                    new PreferredActivity(filter, match, set, activity, always));
11227            mSettings.writePackageRestrictionsLPr(userId);
11228        }
11229    }
11230
11231    @Override
11232    public void replacePreferredActivity(IntentFilter filter, int match,
11233            ComponentName[] set, ComponentName activity) {
11234        if (filter.countActions() != 1) {
11235            throw new IllegalArgumentException(
11236                    "replacePreferredActivity expects filter to have only 1 action.");
11237        }
11238        if (filter.countDataAuthorities() != 0
11239                || filter.countDataPaths() != 0
11240                || filter.countDataSchemes() > 1
11241                || filter.countDataTypes() != 0) {
11242            throw new IllegalArgumentException(
11243                    "replacePreferredActivity expects filter to have no data authorities, " +
11244                    "paths, or types; and at most one scheme.");
11245        }
11246        synchronized (mPackages) {
11247            if (mContext.checkCallingOrSelfPermission(
11248                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11249                    != PackageManager.PERMISSION_GRANTED) {
11250                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11251                        < Build.VERSION_CODES.FROYO) {
11252                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11253                            + Binder.getCallingUid());
11254                    return;
11255                }
11256                mContext.enforceCallingOrSelfPermission(
11257                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11258            }
11259
11260            final int callingUserId = UserHandle.getCallingUserId();
11261            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11262            if (pir != null) {
11263                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11264                if (filter.countDataSchemes() == 1) {
11265                    Uri.Builder builder = new Uri.Builder();
11266                    builder.scheme(filter.getDataScheme(0));
11267                    intent.setData(builder.build());
11268                }
11269                List<PreferredActivity> matches = pir.queryIntent(
11270                        intent, null, true, callingUserId);
11271                if (DEBUG_PREFERRED) {
11272                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11273                }
11274                for (int i = 0; i < matches.size(); i++) {
11275                    PreferredActivity pa = matches.get(i);
11276                    if (DEBUG_PREFERRED) {
11277                        Slog.i(TAG, "Removing preferred activity "
11278                                + pa.mPref.mComponent + ":");
11279                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11280                    }
11281                    pir.removeFilter(pa);
11282                }
11283            }
11284            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11285        }
11286    }
11287
11288    @Override
11289    public void clearPackagePreferredActivities(String packageName) {
11290        final int uid = Binder.getCallingUid();
11291        // writer
11292        synchronized (mPackages) {
11293            PackageParser.Package pkg = mPackages.get(packageName);
11294            if (pkg == null || pkg.applicationInfo.uid != uid) {
11295                if (mContext.checkCallingOrSelfPermission(
11296                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11297                        != PackageManager.PERMISSION_GRANTED) {
11298                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11299                            < Build.VERSION_CODES.FROYO) {
11300                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11301                                + Binder.getCallingUid());
11302                        return;
11303                    }
11304                    mContext.enforceCallingOrSelfPermission(
11305                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11306                }
11307            }
11308
11309            int user = UserHandle.getCallingUserId();
11310            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11311                mSettings.writePackageRestrictionsLPr(user);
11312                scheduleWriteSettingsLocked();
11313            }
11314        }
11315    }
11316
11317    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11318    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11319        ArrayList<PreferredActivity> removed = null;
11320        boolean changed = false;
11321        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11322            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11323            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11324            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11325                continue;
11326            }
11327            Iterator<PreferredActivity> it = pir.filterIterator();
11328            while (it.hasNext()) {
11329                PreferredActivity pa = it.next();
11330                // Mark entry for removal only if it matches the package name
11331                // and the entry is of type "always".
11332                if (packageName == null ||
11333                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11334                                && pa.mPref.mAlways)) {
11335                    if (removed == null) {
11336                        removed = new ArrayList<PreferredActivity>();
11337                    }
11338                    removed.add(pa);
11339                }
11340            }
11341            if (removed != null) {
11342                for (int j=0; j<removed.size(); j++) {
11343                    PreferredActivity pa = removed.get(j);
11344                    pir.removeFilter(pa);
11345                }
11346                changed = true;
11347            }
11348        }
11349        return changed;
11350    }
11351
11352    @Override
11353    public void resetPreferredActivities(int userId) {
11354        mContext.enforceCallingOrSelfPermission(
11355                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11356        // writer
11357        synchronized (mPackages) {
11358            int user = UserHandle.getCallingUserId();
11359            clearPackagePreferredActivitiesLPw(null, user);
11360            mSettings.readDefaultPreferredAppsLPw(this, user);
11361            mSettings.writePackageRestrictionsLPr(user);
11362            scheduleWriteSettingsLocked();
11363        }
11364    }
11365
11366    @Override
11367    public int getPreferredActivities(List<IntentFilter> outFilters,
11368            List<ComponentName> outActivities, String packageName) {
11369
11370        int num = 0;
11371        final int userId = UserHandle.getCallingUserId();
11372        // reader
11373        synchronized (mPackages) {
11374            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11375            if (pir != null) {
11376                final Iterator<PreferredActivity> it = pir.filterIterator();
11377                while (it.hasNext()) {
11378                    final PreferredActivity pa = it.next();
11379                    if (packageName == null
11380                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11381                                    && pa.mPref.mAlways)) {
11382                        if (outFilters != null) {
11383                            outFilters.add(new IntentFilter(pa));
11384                        }
11385                        if (outActivities != null) {
11386                            outActivities.add(pa.mPref.mComponent);
11387                        }
11388                    }
11389                }
11390            }
11391        }
11392
11393        return num;
11394    }
11395
11396    @Override
11397    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11398            int userId) {
11399        int callingUid = Binder.getCallingUid();
11400        if (callingUid != Process.SYSTEM_UID) {
11401            throw new SecurityException(
11402                    "addPersistentPreferredActivity can only be run by the system");
11403        }
11404        if (filter.countActions() == 0) {
11405            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11406            return;
11407        }
11408        synchronized (mPackages) {
11409            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11410                    " :");
11411            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11412            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11413                    new PersistentPreferredActivity(filter, activity));
11414            mSettings.writePackageRestrictionsLPr(userId);
11415        }
11416    }
11417
11418    @Override
11419    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11420        int callingUid = Binder.getCallingUid();
11421        if (callingUid != Process.SYSTEM_UID) {
11422            throw new SecurityException(
11423                    "clearPackagePersistentPreferredActivities can only be run by the system");
11424        }
11425        ArrayList<PersistentPreferredActivity> removed = null;
11426        boolean changed = false;
11427        synchronized (mPackages) {
11428            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11429                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11430                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11431                        .valueAt(i);
11432                if (userId != thisUserId) {
11433                    continue;
11434                }
11435                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11436                while (it.hasNext()) {
11437                    PersistentPreferredActivity ppa = it.next();
11438                    // Mark entry for removal only if it matches the package name.
11439                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11440                        if (removed == null) {
11441                            removed = new ArrayList<PersistentPreferredActivity>();
11442                        }
11443                        removed.add(ppa);
11444                    }
11445                }
11446                if (removed != null) {
11447                    for (int j=0; j<removed.size(); j++) {
11448                        PersistentPreferredActivity ppa = removed.get(j);
11449                        ppir.removeFilter(ppa);
11450                    }
11451                    changed = true;
11452                }
11453            }
11454
11455            if (changed) {
11456                mSettings.writePackageRestrictionsLPr(userId);
11457            }
11458        }
11459    }
11460
11461    @Override
11462    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11463            int targetUserId, int flags) {
11464        mContext.enforceCallingOrSelfPermission(
11465                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11466        if (intentFilter.countActions() == 0) {
11467            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11468            return;
11469        }
11470        synchronized (mPackages) {
11471            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11472                    targetUserId, flags);
11473            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11474            mSettings.writePackageRestrictionsLPr(sourceUserId);
11475        }
11476    }
11477
11478    public void addCrossProfileIntentsForPackage(String packageName,
11479            int sourceUserId, int targetUserId) {
11480        mContext.enforceCallingOrSelfPermission(
11481                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11482        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11483        mSettings.writePackageRestrictionsLPr(sourceUserId);
11484    }
11485
11486    public void removeCrossProfileIntentsForPackage(String packageName,
11487            int sourceUserId, int targetUserId) {
11488        mContext.enforceCallingOrSelfPermission(
11489                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11490        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11491        mSettings.writePackageRestrictionsLPr(sourceUserId);
11492    }
11493
11494    @Override
11495    public void clearCrossProfileIntentFilters(int sourceUserId) {
11496        mContext.enforceCallingOrSelfPermission(
11497                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11498        synchronized (mPackages) {
11499            CrossProfileIntentResolver resolver =
11500                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11501            HashSet<CrossProfileIntentFilter> set =
11502                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11503            for (CrossProfileIntentFilter filter : set) {
11504                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11505                    resolver.removeFilter(filter);
11506                }
11507            }
11508            mSettings.writePackageRestrictionsLPr(sourceUserId);
11509        }
11510    }
11511
11512    @Override
11513    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11514        Intent intent = new Intent(Intent.ACTION_MAIN);
11515        intent.addCategory(Intent.CATEGORY_HOME);
11516
11517        final int callingUserId = UserHandle.getCallingUserId();
11518        List<ResolveInfo> list = queryIntentActivities(intent, null,
11519                PackageManager.GET_META_DATA, callingUserId);
11520        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11521                true, false, false, callingUserId);
11522
11523        allHomeCandidates.clear();
11524        if (list != null) {
11525            for (ResolveInfo ri : list) {
11526                allHomeCandidates.add(ri);
11527            }
11528        }
11529        return (preferred == null || preferred.activityInfo == null)
11530                ? null
11531                : new ComponentName(preferred.activityInfo.packageName,
11532                        preferred.activityInfo.name);
11533    }
11534
11535    @Override
11536    public void setApplicationEnabledSetting(String appPackageName,
11537            int newState, int flags, int userId, String callingPackage) {
11538        if (!sUserManager.exists(userId)) return;
11539        if (callingPackage == null) {
11540            callingPackage = Integer.toString(Binder.getCallingUid());
11541        }
11542        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11543    }
11544
11545    @Override
11546    public void setComponentEnabledSetting(ComponentName componentName,
11547            int newState, int flags, int userId) {
11548        if (!sUserManager.exists(userId)) return;
11549        setEnabledSetting(componentName.getPackageName(),
11550                componentName.getClassName(), newState, flags, userId, null);
11551    }
11552
11553    private void setEnabledSetting(final String packageName, String className, int newState,
11554            final int flags, int userId, String callingPackage) {
11555        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11556              || newState == COMPONENT_ENABLED_STATE_ENABLED
11557              || newState == COMPONENT_ENABLED_STATE_DISABLED
11558              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11559              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11560            throw new IllegalArgumentException("Invalid new component state: "
11561                    + newState);
11562        }
11563        PackageSetting pkgSetting;
11564        final int uid = Binder.getCallingUid();
11565        final int permission = mContext.checkCallingOrSelfPermission(
11566                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11567        enforceCrossUserPermission(uid, userId, false, "set enabled");
11568        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11569        boolean sendNow = false;
11570        boolean isApp = (className == null);
11571        String componentName = isApp ? packageName : className;
11572        int packageUid = -1;
11573        ArrayList<String> components;
11574
11575        // writer
11576        synchronized (mPackages) {
11577            pkgSetting = mSettings.mPackages.get(packageName);
11578            if (pkgSetting == null) {
11579                if (className == null) {
11580                    throw new IllegalArgumentException(
11581                            "Unknown package: " + packageName);
11582                }
11583                throw new IllegalArgumentException(
11584                        "Unknown component: " + packageName
11585                        + "/" + className);
11586            }
11587            // Allow root and verify that userId is not being specified by a different user
11588            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11589                throw new SecurityException(
11590                        "Permission Denial: attempt to change component state from pid="
11591                        + Binder.getCallingPid()
11592                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11593            }
11594            if (className == null) {
11595                // We're dealing with an application/package level state change
11596                if (pkgSetting.getEnabled(userId) == newState) {
11597                    // Nothing to do
11598                    return;
11599                }
11600                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11601                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11602                    // Don't care about who enables an app.
11603                    callingPackage = null;
11604                }
11605                pkgSetting.setEnabled(newState, userId, callingPackage);
11606                // pkgSetting.pkg.mSetEnabled = newState;
11607            } else {
11608                // We're dealing with a component level state change
11609                // First, verify that this is a valid class name.
11610                PackageParser.Package pkg = pkgSetting.pkg;
11611                if (pkg == null || !pkg.hasComponentClassName(className)) {
11612                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11613                        throw new IllegalArgumentException("Component class " + className
11614                                + " does not exist in " + packageName);
11615                    } else {
11616                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11617                                + className + " does not exist in " + packageName);
11618                    }
11619                }
11620                switch (newState) {
11621                case COMPONENT_ENABLED_STATE_ENABLED:
11622                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11623                        return;
11624                    }
11625                    break;
11626                case COMPONENT_ENABLED_STATE_DISABLED:
11627                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11628                        return;
11629                    }
11630                    break;
11631                case COMPONENT_ENABLED_STATE_DEFAULT:
11632                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11633                        return;
11634                    }
11635                    break;
11636                default:
11637                    Slog.e(TAG, "Invalid new component state: " + newState);
11638                    return;
11639                }
11640            }
11641            mSettings.writePackageRestrictionsLPr(userId);
11642            components = mPendingBroadcasts.get(userId, packageName);
11643            final boolean newPackage = components == null;
11644            if (newPackage) {
11645                components = new ArrayList<String>();
11646            }
11647            if (!components.contains(componentName)) {
11648                components.add(componentName);
11649            }
11650            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11651                sendNow = true;
11652                // Purge entry from pending broadcast list if another one exists already
11653                // since we are sending one right away.
11654                mPendingBroadcasts.remove(userId, packageName);
11655            } else {
11656                if (newPackage) {
11657                    mPendingBroadcasts.put(userId, packageName, components);
11658                }
11659                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11660                    // Schedule a message
11661                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11662                }
11663            }
11664        }
11665
11666        long callingId = Binder.clearCallingIdentity();
11667        try {
11668            if (sendNow) {
11669                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11670                sendPackageChangedBroadcast(packageName,
11671                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11672            }
11673        } finally {
11674            Binder.restoreCallingIdentity(callingId);
11675        }
11676    }
11677
11678    private void sendPackageChangedBroadcast(String packageName,
11679            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11680        if (DEBUG_INSTALL)
11681            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11682                    + componentNames);
11683        Bundle extras = new Bundle(4);
11684        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11685        String nameList[] = new String[componentNames.size()];
11686        componentNames.toArray(nameList);
11687        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11688        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11689        extras.putInt(Intent.EXTRA_UID, packageUid);
11690        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11691                new int[] {UserHandle.getUserId(packageUid)});
11692    }
11693
11694    @Override
11695    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11696        if (!sUserManager.exists(userId)) return;
11697        final int uid = Binder.getCallingUid();
11698        final int permission = mContext.checkCallingOrSelfPermission(
11699                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11700        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11701        enforceCrossUserPermission(uid, userId, true, "stop package");
11702        // writer
11703        synchronized (mPackages) {
11704            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11705                    uid, userId)) {
11706                scheduleWritePackageRestrictionsLocked(userId);
11707            }
11708        }
11709    }
11710
11711    @Override
11712    public String getInstallerPackageName(String packageName) {
11713        // reader
11714        synchronized (mPackages) {
11715            return mSettings.getInstallerPackageNameLPr(packageName);
11716        }
11717    }
11718
11719    @Override
11720    public int getApplicationEnabledSetting(String packageName, int userId) {
11721        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11722        int uid = Binder.getCallingUid();
11723        enforceCrossUserPermission(uid, userId, false, "get enabled");
11724        // reader
11725        synchronized (mPackages) {
11726            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11727        }
11728    }
11729
11730    @Override
11731    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11732        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11733        int uid = Binder.getCallingUid();
11734        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11735        // reader
11736        synchronized (mPackages) {
11737            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11738        }
11739    }
11740
11741    @Override
11742    public void enterSafeMode() {
11743        enforceSystemOrRoot("Only the system can request entering safe mode");
11744
11745        if (!mSystemReady) {
11746            mSafeMode = true;
11747        }
11748    }
11749
11750    @Override
11751    public void systemReady() {
11752        mSystemReady = true;
11753
11754        // Read the compatibilty setting when the system is ready.
11755        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11756                mContext.getContentResolver(),
11757                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11758        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11759        if (DEBUG_SETTINGS) {
11760            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11761        }
11762
11763        synchronized (mPackages) {
11764            // Verify that all of the preferred activity components actually
11765            // exist.  It is possible for applications to be updated and at
11766            // that point remove a previously declared activity component that
11767            // had been set as a preferred activity.  We try to clean this up
11768            // the next time we encounter that preferred activity, but it is
11769            // possible for the user flow to never be able to return to that
11770            // situation so here we do a sanity check to make sure we haven't
11771            // left any junk around.
11772            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11773            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11774                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11775                removed.clear();
11776                for (PreferredActivity pa : pir.filterSet()) {
11777                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11778                        removed.add(pa);
11779                    }
11780                }
11781                if (removed.size() > 0) {
11782                    for (int r=0; r<removed.size(); r++) {
11783                        PreferredActivity pa = removed.get(r);
11784                        Slog.w(TAG, "Removing dangling preferred activity: "
11785                                + pa.mPref.mComponent);
11786                        pir.removeFilter(pa);
11787                    }
11788                    mSettings.writePackageRestrictionsLPr(
11789                            mSettings.mPreferredActivities.keyAt(i));
11790                }
11791            }
11792        }
11793        sUserManager.systemReady();
11794    }
11795
11796    @Override
11797    public boolean isSafeMode() {
11798        return mSafeMode;
11799    }
11800
11801    @Override
11802    public boolean hasSystemUidErrors() {
11803        return mHasSystemUidErrors;
11804    }
11805
11806    static String arrayToString(int[] array) {
11807        StringBuffer buf = new StringBuffer(128);
11808        buf.append('[');
11809        if (array != null) {
11810            for (int i=0; i<array.length; i++) {
11811                if (i > 0) buf.append(", ");
11812                buf.append(array[i]);
11813            }
11814        }
11815        buf.append(']');
11816        return buf.toString();
11817    }
11818
11819    static class DumpState {
11820        public static final int DUMP_LIBS = 1 << 0;
11821
11822        public static final int DUMP_FEATURES = 1 << 1;
11823
11824        public static final int DUMP_RESOLVERS = 1 << 2;
11825
11826        public static final int DUMP_PERMISSIONS = 1 << 3;
11827
11828        public static final int DUMP_PACKAGES = 1 << 4;
11829
11830        public static final int DUMP_SHARED_USERS = 1 << 5;
11831
11832        public static final int DUMP_MESSAGES = 1 << 6;
11833
11834        public static final int DUMP_PROVIDERS = 1 << 7;
11835
11836        public static final int DUMP_VERIFIERS = 1 << 8;
11837
11838        public static final int DUMP_PREFERRED = 1 << 9;
11839
11840        public static final int DUMP_PREFERRED_XML = 1 << 10;
11841
11842        public static final int DUMP_KEYSETS = 1 << 11;
11843
11844        public static final int DUMP_VERSION = 1 << 12;
11845
11846        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11847
11848        private int mTypes;
11849
11850        private int mOptions;
11851
11852        private boolean mTitlePrinted;
11853
11854        private SharedUserSetting mSharedUser;
11855
11856        public boolean isDumping(int type) {
11857            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11858                return true;
11859            }
11860
11861            return (mTypes & type) != 0;
11862        }
11863
11864        public void setDump(int type) {
11865            mTypes |= type;
11866        }
11867
11868        public boolean isOptionEnabled(int option) {
11869            return (mOptions & option) != 0;
11870        }
11871
11872        public void setOptionEnabled(int option) {
11873            mOptions |= option;
11874        }
11875
11876        public boolean onTitlePrinted() {
11877            final boolean printed = mTitlePrinted;
11878            mTitlePrinted = true;
11879            return printed;
11880        }
11881
11882        public boolean getTitlePrinted() {
11883            return mTitlePrinted;
11884        }
11885
11886        public void setTitlePrinted(boolean enabled) {
11887            mTitlePrinted = enabled;
11888        }
11889
11890        public SharedUserSetting getSharedUser() {
11891            return mSharedUser;
11892        }
11893
11894        public void setSharedUser(SharedUserSetting user) {
11895            mSharedUser = user;
11896        }
11897    }
11898
11899    @Override
11900    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11901        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11902                != PackageManager.PERMISSION_GRANTED) {
11903            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11904                    + Binder.getCallingPid()
11905                    + ", uid=" + Binder.getCallingUid()
11906                    + " without permission "
11907                    + android.Manifest.permission.DUMP);
11908            return;
11909        }
11910
11911        DumpState dumpState = new DumpState();
11912        boolean fullPreferred = false;
11913        boolean checkin = false;
11914
11915        String packageName = null;
11916
11917        int opti = 0;
11918        while (opti < args.length) {
11919            String opt = args[opti];
11920            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11921                break;
11922            }
11923            opti++;
11924            if ("-a".equals(opt)) {
11925                // Right now we only know how to print all.
11926            } else if ("-h".equals(opt)) {
11927                pw.println("Package manager dump options:");
11928                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11929                pw.println("    --checkin: dump for a checkin");
11930                pw.println("    -f: print details of intent filters");
11931                pw.println("    -h: print this help");
11932                pw.println("  cmd may be one of:");
11933                pw.println("    l[ibraries]: list known shared libraries");
11934                pw.println("    f[ibraries]: list device features");
11935                pw.println("    k[eysets]: print known keysets");
11936                pw.println("    r[esolvers]: dump intent resolvers");
11937                pw.println("    perm[issions]: dump permissions");
11938                pw.println("    pref[erred]: print preferred package settings");
11939                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11940                pw.println("    prov[iders]: dump content providers");
11941                pw.println("    p[ackages]: dump installed packages");
11942                pw.println("    s[hared-users]: dump shared user IDs");
11943                pw.println("    m[essages]: print collected runtime messages");
11944                pw.println("    v[erifiers]: print package verifier info");
11945                pw.println("    version: print database version info");
11946                pw.println("    write: write current settings now");
11947                pw.println("    <package.name>: info about given package");
11948                return;
11949            } else if ("--checkin".equals(opt)) {
11950                checkin = true;
11951            } else if ("-f".equals(opt)) {
11952                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11953            } else {
11954                pw.println("Unknown argument: " + opt + "; use -h for help");
11955            }
11956        }
11957
11958        // Is the caller requesting to dump a particular piece of data?
11959        if (opti < args.length) {
11960            String cmd = args[opti];
11961            opti++;
11962            // Is this a package name?
11963            if ("android".equals(cmd) || cmd.contains(".")) {
11964                packageName = cmd;
11965                // When dumping a single package, we always dump all of its
11966                // filter information since the amount of data will be reasonable.
11967                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11968            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11969                dumpState.setDump(DumpState.DUMP_LIBS);
11970            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11971                dumpState.setDump(DumpState.DUMP_FEATURES);
11972            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11973                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11974            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11975                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11976            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11977                dumpState.setDump(DumpState.DUMP_PREFERRED);
11978            } else if ("preferred-xml".equals(cmd)) {
11979                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11980                if (opti < args.length && "--full".equals(args[opti])) {
11981                    fullPreferred = true;
11982                    opti++;
11983                }
11984            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11985                dumpState.setDump(DumpState.DUMP_PACKAGES);
11986            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11987                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11988            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11989                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11990            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11991                dumpState.setDump(DumpState.DUMP_MESSAGES);
11992            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11993                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11994            } else if ("version".equals(cmd)) {
11995                dumpState.setDump(DumpState.DUMP_VERSION);
11996            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11997                dumpState.setDump(DumpState.DUMP_KEYSETS);
11998            } else if ("write".equals(cmd)) {
11999                synchronized (mPackages) {
12000                    mSettings.writeLPr();
12001                    pw.println("Settings written.");
12002                    return;
12003                }
12004            }
12005        }
12006
12007        if (checkin) {
12008            pw.println("vers,1");
12009        }
12010
12011        // reader
12012        synchronized (mPackages) {
12013            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12014                if (!checkin) {
12015                    if (dumpState.onTitlePrinted())
12016                        pw.println();
12017                    pw.println("Database versions:");
12018                    pw.print("  SDK Version:");
12019                    pw.print(" internal=");
12020                    pw.print(mSettings.mInternalSdkPlatform);
12021                    pw.print(" external=");
12022                    pw.println(mSettings.mExternalSdkPlatform);
12023                    pw.print("  DB Version:");
12024                    pw.print(" internal=");
12025                    pw.print(mSettings.mInternalDatabaseVersion);
12026                    pw.print(" external=");
12027                    pw.println(mSettings.mExternalDatabaseVersion);
12028                }
12029            }
12030
12031            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12032                if (!checkin) {
12033                    if (dumpState.onTitlePrinted())
12034                        pw.println();
12035                    pw.println("Verifiers:");
12036                    pw.print("  Required: ");
12037                    pw.print(mRequiredVerifierPackage);
12038                    pw.print(" (uid=");
12039                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12040                    pw.println(")");
12041                } else if (mRequiredVerifierPackage != null) {
12042                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12043                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12044                }
12045            }
12046
12047            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12048                boolean printedHeader = false;
12049                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12050                while (it.hasNext()) {
12051                    String name = it.next();
12052                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12053                    if (!checkin) {
12054                        if (!printedHeader) {
12055                            if (dumpState.onTitlePrinted())
12056                                pw.println();
12057                            pw.println("Libraries:");
12058                            printedHeader = true;
12059                        }
12060                        pw.print("  ");
12061                    } else {
12062                        pw.print("lib,");
12063                    }
12064                    pw.print(name);
12065                    if (!checkin) {
12066                        pw.print(" -> ");
12067                    }
12068                    if (ent.path != null) {
12069                        if (!checkin) {
12070                            pw.print("(jar) ");
12071                            pw.print(ent.path);
12072                        } else {
12073                            pw.print(",jar,");
12074                            pw.print(ent.path);
12075                        }
12076                    } else {
12077                        if (!checkin) {
12078                            pw.print("(apk) ");
12079                            pw.print(ent.apk);
12080                        } else {
12081                            pw.print(",apk,");
12082                            pw.print(ent.apk);
12083                        }
12084                    }
12085                    pw.println();
12086                }
12087            }
12088
12089            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12090                if (dumpState.onTitlePrinted())
12091                    pw.println();
12092                if (!checkin) {
12093                    pw.println("Features:");
12094                }
12095                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12096                while (it.hasNext()) {
12097                    String name = it.next();
12098                    if (!checkin) {
12099                        pw.print("  ");
12100                    } else {
12101                        pw.print("feat,");
12102                    }
12103                    pw.println(name);
12104                }
12105            }
12106
12107            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12108                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12109                        : "Activity Resolver Table:", "  ", packageName,
12110                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12111                    dumpState.setTitlePrinted(true);
12112                }
12113                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12114                        : "Receiver Resolver Table:", "  ", packageName,
12115                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12116                    dumpState.setTitlePrinted(true);
12117                }
12118                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12119                        : "Service Resolver Table:", "  ", packageName,
12120                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12121                    dumpState.setTitlePrinted(true);
12122                }
12123                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12124                        : "Provider Resolver Table:", "  ", packageName,
12125                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12126                    dumpState.setTitlePrinted(true);
12127                }
12128            }
12129
12130            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12131                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12132                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12133                    int user = mSettings.mPreferredActivities.keyAt(i);
12134                    if (pir.dump(pw,
12135                            dumpState.getTitlePrinted()
12136                                ? "\nPreferred Activities User " + user + ":"
12137                                : "Preferred Activities User " + user + ":", "  ",
12138                            packageName, true)) {
12139                        dumpState.setTitlePrinted(true);
12140                    }
12141                }
12142            }
12143
12144            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12145                pw.flush();
12146                FileOutputStream fout = new FileOutputStream(fd);
12147                BufferedOutputStream str = new BufferedOutputStream(fout);
12148                XmlSerializer serializer = new FastXmlSerializer();
12149                try {
12150                    serializer.setOutput(str, "utf-8");
12151                    serializer.startDocument(null, true);
12152                    serializer.setFeature(
12153                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12154                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12155                    serializer.endDocument();
12156                    serializer.flush();
12157                } catch (IllegalArgumentException e) {
12158                    pw.println("Failed writing: " + e);
12159                } catch (IllegalStateException e) {
12160                    pw.println("Failed writing: " + e);
12161                } catch (IOException e) {
12162                    pw.println("Failed writing: " + e);
12163                }
12164            }
12165
12166            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12167                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12168            }
12169
12170            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12171                boolean printedSomething = false;
12172                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12173                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12174                        continue;
12175                    }
12176                    if (!printedSomething) {
12177                        if (dumpState.onTitlePrinted())
12178                            pw.println();
12179                        pw.println("Registered ContentProviders:");
12180                        printedSomething = true;
12181                    }
12182                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12183                    pw.print("    "); pw.println(p.toString());
12184                }
12185                printedSomething = false;
12186                for (Map.Entry<String, PackageParser.Provider> entry :
12187                        mProvidersByAuthority.entrySet()) {
12188                    PackageParser.Provider p = entry.getValue();
12189                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12190                        continue;
12191                    }
12192                    if (!printedSomething) {
12193                        if (dumpState.onTitlePrinted())
12194                            pw.println();
12195                        pw.println("ContentProvider Authorities:");
12196                        printedSomething = true;
12197                    }
12198                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12199                    pw.print("    "); pw.println(p.toString());
12200                    if (p.info != null && p.info.applicationInfo != null) {
12201                        final String appInfo = p.info.applicationInfo.toString();
12202                        pw.print("      applicationInfo="); pw.println(appInfo);
12203                    }
12204                }
12205            }
12206
12207            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12208                mSettings.mKeySetManagerService.dump(pw, packageName, dumpState);
12209            }
12210
12211            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12212                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12213            }
12214
12215            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12216                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12217            }
12218
12219            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12220                if (dumpState.onTitlePrinted())
12221                    pw.println();
12222                mSettings.dumpReadMessagesLPr(pw, dumpState);
12223
12224                pw.println();
12225                pw.println("Package warning messages:");
12226                final File fname = getSettingsProblemFile();
12227                FileInputStream in = null;
12228                try {
12229                    in = new FileInputStream(fname);
12230                    final int avail = in.available();
12231                    final byte[] data = new byte[avail];
12232                    in.read(data);
12233                    pw.print(new String(data));
12234                } catch (FileNotFoundException e) {
12235                } catch (IOException e) {
12236                } finally {
12237                    if (in != null) {
12238                        try {
12239                            in.close();
12240                        } catch (IOException e) {
12241                        }
12242                    }
12243                }
12244            }
12245        }
12246    }
12247
12248    // ------- apps on sdcard specific code -------
12249    static final boolean DEBUG_SD_INSTALL = false;
12250
12251    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12252
12253    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12254
12255    private boolean mMediaMounted = false;
12256
12257    private String getEncryptKey() {
12258        try {
12259            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12260                    SD_ENCRYPTION_KEYSTORE_NAME);
12261            if (sdEncKey == null) {
12262                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12263                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12264                if (sdEncKey == null) {
12265                    Slog.e(TAG, "Failed to create encryption keys");
12266                    return null;
12267                }
12268            }
12269            return sdEncKey;
12270        } catch (NoSuchAlgorithmException nsae) {
12271            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12272            return null;
12273        } catch (IOException ioe) {
12274            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12275            return null;
12276        }
12277
12278    }
12279
12280    /* package */static String getTempContainerId() {
12281        int tmpIdx = 1;
12282        String list[] = PackageHelper.getSecureContainerList();
12283        if (list != null) {
12284            for (final String name : list) {
12285                // Ignore null and non-temporary container entries
12286                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12287                    continue;
12288                }
12289
12290                String subStr = name.substring(mTempContainerPrefix.length());
12291                try {
12292                    int cid = Integer.parseInt(subStr);
12293                    if (cid >= tmpIdx) {
12294                        tmpIdx = cid + 1;
12295                    }
12296                } catch (NumberFormatException e) {
12297                }
12298            }
12299        }
12300        return mTempContainerPrefix + tmpIdx;
12301    }
12302
12303    /*
12304     * Update media status on PackageManager.
12305     */
12306    @Override
12307    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12308        int callingUid = Binder.getCallingUid();
12309        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12310            throw new SecurityException("Media status can only be updated by the system");
12311        }
12312        // reader; this apparently protects mMediaMounted, but should probably
12313        // be a different lock in that case.
12314        synchronized (mPackages) {
12315            Log.i(TAG, "Updating external media status from "
12316                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12317                    + (mediaStatus ? "mounted" : "unmounted"));
12318            if (DEBUG_SD_INSTALL)
12319                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12320                        + ", mMediaMounted=" + mMediaMounted);
12321            if (mediaStatus == mMediaMounted) {
12322                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12323                        : 0, -1);
12324                mHandler.sendMessage(msg);
12325                return;
12326            }
12327            mMediaMounted = mediaStatus;
12328        }
12329        // Queue up an async operation since the package installation may take a
12330        // little while.
12331        mHandler.post(new Runnable() {
12332            public void run() {
12333                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12334            }
12335        });
12336    }
12337
12338    /**
12339     * Called by MountService when the initial ASECs to scan are available.
12340     * Should block until all the ASEC containers are finished being scanned.
12341     */
12342    public void scanAvailableAsecs() {
12343        updateExternalMediaStatusInner(true, false, false);
12344        if (mShouldRestoreconData) {
12345            SELinuxMMAC.setRestoreconDone();
12346            mShouldRestoreconData = false;
12347        }
12348    }
12349
12350    /*
12351     * Collect information of applications on external media, map them against
12352     * existing containers and update information based on current mount status.
12353     * Please note that we always have to report status if reportStatus has been
12354     * set to true especially when unloading packages.
12355     */
12356    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12357            boolean externalStorage) {
12358        // Collection of uids
12359        int uidArr[] = null;
12360        // Collection of stale containers
12361        HashSet<String> removeCids = new HashSet<String>();
12362        // Collection of packages on external media with valid containers.
12363        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12364        // Get list of secure containers.
12365        final String list[] = PackageHelper.getSecureContainerList();
12366        if (list == null || list.length == 0) {
12367            Log.i(TAG, "No secure containers on sdcard");
12368        } else {
12369            // Process list of secure containers and categorize them
12370            // as active or stale based on their package internal state.
12371            int uidList[] = new int[list.length];
12372            int num = 0;
12373            // reader
12374            synchronized (mPackages) {
12375                for (String cid : list) {
12376                    if (DEBUG_SD_INSTALL)
12377                        Log.i(TAG, "Processing container " + cid);
12378                    String pkgName = getAsecPackageName(cid);
12379                    if (pkgName == null) {
12380                        if (DEBUG_SD_INSTALL)
12381                            Log.i(TAG, "Container : " + cid + " stale");
12382                        removeCids.add(cid);
12383                        continue;
12384                    }
12385                    if (DEBUG_SD_INSTALL)
12386                        Log.i(TAG, "Looking for pkg : " + pkgName);
12387
12388                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12389                    if (ps == null) {
12390                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12391                        removeCids.add(cid);
12392                        continue;
12393                    }
12394
12395                    /*
12396                     * Skip packages that are not external if we're unmounting
12397                     * external storage.
12398                     */
12399                    if (externalStorage && !isMounted && !isExternal(ps)) {
12400                        continue;
12401                    }
12402
12403                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12404                            getAppInstructionSetFromSettings(ps),
12405                            isForwardLocked(ps));
12406                    // The package status is changed only if the code path
12407                    // matches between settings and the container id.
12408                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12409                        if (DEBUG_SD_INSTALL) {
12410                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12411                                    + " at code path: " + ps.codePathString);
12412                        }
12413
12414                        // We do have a valid package installed on sdcard
12415                        processCids.put(args, ps.codePathString);
12416                        final int uid = ps.appId;
12417                        if (uid != -1) {
12418                            uidList[num++] = uid;
12419                        }
12420                    } else {
12421                        Log.i(TAG, "Deleting stale container for " + cid);
12422                        removeCids.add(cid);
12423                    }
12424                }
12425            }
12426
12427            if (num > 0) {
12428                // Sort uid list
12429                Arrays.sort(uidList, 0, num);
12430                // Throw away duplicates
12431                uidArr = new int[num];
12432                uidArr[0] = uidList[0];
12433                int di = 0;
12434                for (int i = 1; i < num; i++) {
12435                    if (uidList[i - 1] != uidList[i]) {
12436                        uidArr[di++] = uidList[i];
12437                    }
12438                }
12439            }
12440        }
12441        // Process packages with valid entries.
12442        if (isMounted) {
12443            if (DEBUG_SD_INSTALL)
12444                Log.i(TAG, "Loading packages");
12445            loadMediaPackages(processCids, uidArr, removeCids);
12446            startCleaningPackages();
12447        } else {
12448            if (DEBUG_SD_INSTALL)
12449                Log.i(TAG, "Unloading packages");
12450            unloadMediaPackages(processCids, uidArr, reportStatus);
12451        }
12452    }
12453
12454   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12455           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12456        int size = pkgList.size();
12457        if (size > 0) {
12458            // Send broadcasts here
12459            Bundle extras = new Bundle();
12460            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12461                    .toArray(new String[size]));
12462            if (uidArr != null) {
12463                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12464            }
12465            if (replacing) {
12466                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12467            }
12468            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12469                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12470            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12471        }
12472    }
12473
12474   /*
12475     * Look at potentially valid container ids from processCids If package
12476     * information doesn't match the one on record or package scanning fails,
12477     * the cid is added to list of removeCids. We currently don't delete stale
12478     * containers.
12479     */
12480   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12481            HashSet<String> removeCids) {
12482        ArrayList<String> pkgList = new ArrayList<String>();
12483        Set<AsecInstallArgs> keys = processCids.keySet();
12484        boolean doGc = false;
12485        for (AsecInstallArgs args : keys) {
12486            String codePath = processCids.get(args);
12487            if (DEBUG_SD_INSTALL)
12488                Log.i(TAG, "Loading container : " + args.cid);
12489            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12490            try {
12491                // Make sure there are no container errors first.
12492                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12493                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12494                            + " when installing from sdcard");
12495                    continue;
12496                }
12497                // Check code path here.
12498                if (codePath == null || !codePath.equals(args.getCodePath())) {
12499                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12500                            + " does not match one in settings " + codePath);
12501                    continue;
12502                }
12503                // Parse package
12504                int parseFlags = mDefParseFlags;
12505                if (args.isExternal()) {
12506                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12507                }
12508                if (args.isFwdLocked()) {
12509                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12510                }
12511
12512                doGc = true;
12513                synchronized (mInstallLock) {
12514                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12515                            0, 0, null, null);
12516                    // Scan the package
12517                    if (pkg != null) {
12518                        /*
12519                         * TODO why is the lock being held? doPostInstall is
12520                         * called in other places without the lock. This needs
12521                         * to be straightened out.
12522                         */
12523                        // writer
12524                        synchronized (mPackages) {
12525                            retCode = PackageManager.INSTALL_SUCCEEDED;
12526                            pkgList.add(pkg.packageName);
12527                            // Post process args
12528                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12529                                    pkg.applicationInfo.uid);
12530                        }
12531                    } else {
12532                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12533                    }
12534                }
12535
12536            } finally {
12537                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12538                    // Don't destroy container here. Wait till gc clears things
12539                    // up.
12540                    removeCids.add(args.cid);
12541                }
12542            }
12543        }
12544        // writer
12545        synchronized (mPackages) {
12546            // If the platform SDK has changed since the last time we booted,
12547            // we need to re-grant app permission to catch any new ones that
12548            // appear. This is really a hack, and means that apps can in some
12549            // cases get permissions that the user didn't initially explicitly
12550            // allow... it would be nice to have some better way to handle
12551            // this situation.
12552            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12553            if (regrantPermissions)
12554                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12555                        + mSdkVersion + "; regranting permissions for external storage");
12556            mSettings.mExternalSdkPlatform = mSdkVersion;
12557
12558            // Make sure group IDs have been assigned, and any permission
12559            // changes in other apps are accounted for
12560            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12561                    | (regrantPermissions
12562                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12563                            : 0));
12564
12565            mSettings.updateExternalDatabaseVersion();
12566
12567            // can downgrade to reader
12568            // Persist settings
12569            mSettings.writeLPr();
12570        }
12571        // Send a broadcast to let everyone know we are done processing
12572        if (pkgList.size() > 0) {
12573            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12574        }
12575        // Force gc to avoid any stale parser references that we might have.
12576        if (doGc) {
12577            Runtime.getRuntime().gc();
12578        }
12579        // List stale containers and destroy stale temporary containers.
12580        if (removeCids != null) {
12581            for (String cid : removeCids) {
12582                if (cid.startsWith(mTempContainerPrefix)) {
12583                    Log.i(TAG, "Destroying stale temporary container " + cid);
12584                    PackageHelper.destroySdDir(cid);
12585                } else {
12586                    Log.w(TAG, "Container " + cid + " is stale");
12587               }
12588           }
12589        }
12590    }
12591
12592   /*
12593     * Utility method to unload a list of specified containers
12594     */
12595    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12596        // Just unmount all valid containers.
12597        for (AsecInstallArgs arg : cidArgs) {
12598            synchronized (mInstallLock) {
12599                arg.doPostDeleteLI(false);
12600           }
12601       }
12602   }
12603
12604    /*
12605     * Unload packages mounted on external media. This involves deleting package
12606     * data from internal structures, sending broadcasts about diabled packages,
12607     * gc'ing to free up references, unmounting all secure containers
12608     * corresponding to packages on external media, and posting a
12609     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12610     * that we always have to post this message if status has been requested no
12611     * matter what.
12612     */
12613    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12614            final boolean reportStatus) {
12615        if (DEBUG_SD_INSTALL)
12616            Log.i(TAG, "unloading media packages");
12617        ArrayList<String> pkgList = new ArrayList<String>();
12618        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12619        final Set<AsecInstallArgs> keys = processCids.keySet();
12620        for (AsecInstallArgs args : keys) {
12621            String pkgName = args.getPackageName();
12622            if (DEBUG_SD_INSTALL)
12623                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12624            // Delete package internally
12625            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12626            synchronized (mInstallLock) {
12627                boolean res = deletePackageLI(pkgName, null, false, null, null,
12628                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12629                if (res) {
12630                    pkgList.add(pkgName);
12631                } else {
12632                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12633                    failedList.add(args);
12634                }
12635            }
12636        }
12637
12638        // reader
12639        synchronized (mPackages) {
12640            // We didn't update the settings after removing each package;
12641            // write them now for all packages.
12642            mSettings.writeLPr();
12643        }
12644
12645        // We have to absolutely send UPDATED_MEDIA_STATUS only
12646        // after confirming that all the receivers processed the ordered
12647        // broadcast when packages get disabled, force a gc to clean things up.
12648        // and unload all the containers.
12649        if (pkgList.size() > 0) {
12650            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12651                    new IIntentReceiver.Stub() {
12652                public void performReceive(Intent intent, int resultCode, String data,
12653                        Bundle extras, boolean ordered, boolean sticky,
12654                        int sendingUser) throws RemoteException {
12655                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12656                            reportStatus ? 1 : 0, 1, keys);
12657                    mHandler.sendMessage(msg);
12658                }
12659            });
12660        } else {
12661            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12662                    keys);
12663            mHandler.sendMessage(msg);
12664        }
12665    }
12666
12667    /** Binder call */
12668    @Override
12669    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12670            final int flags) {
12671        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12672        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12673        int returnCode = PackageManager.MOVE_SUCCEEDED;
12674        int currFlags = 0;
12675        int newFlags = 0;
12676        // reader
12677        synchronized (mPackages) {
12678            PackageParser.Package pkg = mPackages.get(packageName);
12679            if (pkg == null) {
12680                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12681            } else {
12682                // Disable moving fwd locked apps and system packages
12683                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12684                    Slog.w(TAG, "Cannot move system application");
12685                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12686                } else if (pkg.mOperationPending) {
12687                    Slog.w(TAG, "Attempt to move package which has pending operations");
12688                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12689                } else {
12690                    // Find install location first
12691                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12692                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12693                        Slog.w(TAG, "Ambigous flags specified for move location.");
12694                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12695                    } else {
12696                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12697                                : PackageManager.INSTALL_INTERNAL;
12698                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12699                                : PackageManager.INSTALL_INTERNAL;
12700
12701                        if (newFlags == currFlags) {
12702                            Slog.w(TAG, "No move required. Trying to move to same location");
12703                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12704                        } else {
12705                            if (isForwardLocked(pkg)) {
12706                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12707                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12708                            }
12709                        }
12710                    }
12711                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12712                        pkg.mOperationPending = true;
12713                    }
12714                }
12715            }
12716
12717            /*
12718             * TODO this next block probably shouldn't be inside the lock. We
12719             * can't guarantee these won't change after this is fired off
12720             * anyway.
12721             */
12722            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12723                processPendingMove(new MoveParams(null, observer, 0, packageName, null, -1, user),
12724                        returnCode);
12725            } else {
12726                Message msg = mHandler.obtainMessage(INIT_COPY);
12727                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12728                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12729                        pkg.applicationInfo.getCodePath(), pkg.applicationInfo.getResourcePath(),
12730                        pkg.applicationInfo.nativeLibraryDir, instructionSet);
12731                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12732                        instructionSet, pkg.applicationInfo.uid, user);
12733                msg.obj = mp;
12734                mHandler.sendMessage(msg);
12735            }
12736        }
12737    }
12738
12739    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12740        // Queue up an async operation since the package deletion may take a
12741        // little while.
12742        mHandler.post(new Runnable() {
12743            public void run() {
12744                // TODO fix this; this does nothing.
12745                mHandler.removeCallbacks(this);
12746                int returnCode = currentStatus;
12747                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12748                    int uidArr[] = null;
12749                    ArrayList<String> pkgList = null;
12750                    synchronized (mPackages) {
12751                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12752                        if (pkg == null) {
12753                            Slog.w(TAG, " Package " + mp.packageName
12754                                    + " doesn't exist. Aborting move");
12755                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12756                        } else if (!mp.srcArgs.getCodePath().equals(
12757                                pkg.applicationInfo.getCodePath())) {
12758                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12759                                    + mp.srcArgs.getCodePath() + " to "
12760                                    + pkg.applicationInfo.getCodePath()
12761                                    + " Aborting move and returning error");
12762                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12763                        } else {
12764                            uidArr = new int[] {
12765                                pkg.applicationInfo.uid
12766                            };
12767                            pkgList = new ArrayList<String>();
12768                            pkgList.add(mp.packageName);
12769                        }
12770                    }
12771                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12772                        // Send resources unavailable broadcast
12773                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12774                        // Update package code and resource paths
12775                        synchronized (mInstallLock) {
12776                            synchronized (mPackages) {
12777                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12778                                // Recheck for package again.
12779                                if (pkg == null) {
12780                                    Slog.w(TAG, " Package " + mp.packageName
12781                                            + " doesn't exist. Aborting move");
12782                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12783                                } else if (!mp.srcArgs.getCodePath().equals(
12784                                        pkg.applicationInfo.getCodePath())) {
12785                                    Slog.w(TAG, "Package " + mp.packageName
12786                                            + " code path changed from " + mp.srcArgs.getCodePath()
12787                                            + " to " + pkg.applicationInfo.getCodePath()
12788                                            + " Aborting move and returning error");
12789                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12790                                } else {
12791                                    final String oldCodePath = pkg.codePath;
12792                                    final String newCodePath = mp.targetArgs.getCodePath();
12793                                    final String newResPath = mp.targetArgs.getResourcePath();
12794                                    final String newNativePath = mp.targetArgs
12795                                            .getNativeLibraryPath();
12796
12797                                    final File newNativeDir = new File(newNativePath);
12798
12799                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12800                                        NativeLibraryHelper.Handle handle = null;
12801                                        try {
12802                                            handle = NativeLibraryHelper.Handle.create(
12803                                                    new File(newCodePath));
12804                                            final int abi = NativeLibraryHelper.findSupportedAbi(
12805                                                    handle, Build.SUPPORTED_ABIS);
12806                                            if (abi >= 0) {
12807                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12808                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12809                                            }
12810                                        } catch (IOException ioe) {
12811                                            Slog.w(TAG, "Unable to extract native libs for package :"
12812                                                    + mp.packageName, ioe);
12813                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12814                                        } finally {
12815                                            IoUtils.closeQuietly(handle);
12816                                        }
12817                                    }
12818                                    final int[] users = sUserManager.getUserIds();
12819                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12820                                        for (int user : users) {
12821                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12822                                                    newNativePath, user) < 0) {
12823                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12824                                            }
12825                                        }
12826                                    }
12827
12828                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12829                                        pkg.codePath = newCodePath;
12830                                        pkg.baseCodePath = newCodePath;
12831                                        // Move dex files around
12832                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
12833                                            // Moving of dex files failed. Set
12834                                            // error code and abort move.
12835                                            pkg.codePath = oldCodePath;
12836                                            pkg.baseCodePath = oldCodePath;
12837                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12838                                        }
12839                                    }
12840
12841                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12842                                        pkg.applicationInfo.setCodePath(newCodePath);
12843                                        pkg.applicationInfo.setBaseCodePath(newCodePath);
12844                                        pkg.applicationInfo.setSplitCodePaths(null);
12845                                        pkg.applicationInfo.setResourcePath(newResPath);
12846                                        pkg.applicationInfo.setBaseResourcePath(newResPath);
12847                                        pkg.applicationInfo.setSplitResourcePaths(null);
12848                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12849
12850                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12851                                        ps.codePath = new File(pkg.applicationInfo.getCodePath());
12852                                        ps.codePathString = ps.codePath.getPath();
12853                                        ps.resourcePath = new File(
12854                                                pkg.applicationInfo.getResourcePath());
12855                                        ps.resourcePathString = ps.resourcePath.getPath();
12856                                        ps.nativeLibraryPathString = newNativePath;
12857                                        // Set the application info flag
12858                                        // correctly.
12859                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12860                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12861                                        } else {
12862                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12863                                        }
12864                                        ps.setFlags(pkg.applicationInfo.flags);
12865                                        mAppDirs.remove(oldCodePath);
12866                                        mAppDirs.put(newCodePath, pkg);
12867                                        // Persist settings
12868                                        mSettings.writeLPr();
12869                                    }
12870                                }
12871                            }
12872                        }
12873                        // Send resources available broadcast
12874                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12875                    }
12876                }
12877                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12878                    // Clean up failed installation
12879                    if (mp.targetArgs != null) {
12880                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12881                                -1);
12882                    }
12883                } else {
12884                    // Force a gc to clear things up.
12885                    Runtime.getRuntime().gc();
12886                    // Delete older code
12887                    synchronized (mInstallLock) {
12888                        mp.srcArgs.doPostDeleteLI(true);
12889                    }
12890                }
12891
12892                // Allow more operations on this file if we didn't fail because
12893                // an operation was already pending for this package.
12894                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12895                    synchronized (mPackages) {
12896                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12897                        if (pkg != null) {
12898                            pkg.mOperationPending = false;
12899                       }
12900                   }
12901                }
12902
12903                IPackageMoveObserver observer = mp.observer;
12904                if (observer != null) {
12905                    try {
12906                        observer.packageMoved(mp.packageName, returnCode);
12907                    } catch (RemoteException e) {
12908                        Log.i(TAG, "Observer no longer exists.");
12909                    }
12910                }
12911            }
12912        });
12913    }
12914
12915    @Override
12916    public boolean setInstallLocation(int loc) {
12917        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12918                null);
12919        if (getInstallLocation() == loc) {
12920            return true;
12921        }
12922        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12923                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12924            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12925                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12926            return true;
12927        }
12928        return false;
12929   }
12930
12931    @Override
12932    public int getInstallLocation() {
12933        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12934                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12935                PackageHelper.APP_INSTALL_AUTO);
12936    }
12937
12938    /** Called by UserManagerService */
12939    void cleanUpUserLILPw(int userHandle) {
12940        mDirtyUsers.remove(userHandle);
12941        mSettings.removeUserLPr(userHandle);
12942        mPendingBroadcasts.remove(userHandle);
12943        if (mInstaller != null) {
12944            // Technically, we shouldn't be doing this with the package lock
12945            // held.  However, this is very rare, and there is already so much
12946            // other disk I/O going on, that we'll let it slide for now.
12947            mInstaller.removeUserDataDirs(userHandle);
12948        }
12949        mUserNeedsBadging.delete(userHandle);
12950    }
12951
12952    /** Called by UserManagerService */
12953    void createNewUserLILPw(int userHandle, File path) {
12954        if (mInstaller != null) {
12955            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12956        }
12957    }
12958
12959    @Override
12960    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12961        mContext.enforceCallingOrSelfPermission(
12962                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12963                "Only package verification agents can read the verifier device identity");
12964
12965        synchronized (mPackages) {
12966            return mSettings.getVerifierDeviceIdentityLPw();
12967        }
12968    }
12969
12970    @Override
12971    public void setPermissionEnforced(String permission, boolean enforced) {
12972        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12973        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12974            synchronized (mPackages) {
12975                if (mSettings.mReadExternalStorageEnforced == null
12976                        || mSettings.mReadExternalStorageEnforced != enforced) {
12977                    mSettings.mReadExternalStorageEnforced = enforced;
12978                    mSettings.writeLPr();
12979                }
12980            }
12981            // kill any non-foreground processes so we restart them and
12982            // grant/revoke the GID.
12983            final IActivityManager am = ActivityManagerNative.getDefault();
12984            if (am != null) {
12985                final long token = Binder.clearCallingIdentity();
12986                try {
12987                    am.killProcessesBelowForeground("setPermissionEnforcement");
12988                } catch (RemoteException e) {
12989                } finally {
12990                    Binder.restoreCallingIdentity(token);
12991                }
12992            }
12993        } else {
12994            throw new IllegalArgumentException("No selective enforcement for " + permission);
12995        }
12996    }
12997
12998    @Override
12999    @Deprecated
13000    public boolean isPermissionEnforced(String permission) {
13001        return true;
13002    }
13003
13004    @Override
13005    public boolean isStorageLow() {
13006        final long token = Binder.clearCallingIdentity();
13007        try {
13008            final DeviceStorageMonitorInternal
13009                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13010            if (dsm != null) {
13011                return dsm.isMemoryLow();
13012            } else {
13013                return false;
13014            }
13015        } finally {
13016            Binder.restoreCallingIdentity(token);
13017        }
13018    }
13019
13020    @Override
13021    public IPackageInstaller getPackageInstaller() {
13022        return mInstallerService;
13023    }
13024
13025    private boolean userNeedsBadging(int userId) {
13026        int index = mUserNeedsBadging.indexOfKey(userId);
13027        if (index < 0) {
13028            final UserInfo userInfo;
13029            final long token = Binder.clearCallingIdentity();
13030            try {
13031                userInfo = sUserManager.getUserInfo(userId);
13032            } finally {
13033                Binder.restoreCallingIdentity(token);
13034            }
13035            final boolean b;
13036            if (userInfo != null && userInfo.isManagedProfile()) {
13037                b = true;
13038            } else {
13039                b = false;
13040            }
13041            mUserNeedsBadging.put(userId, b);
13042            return b;
13043        }
13044        return mUserNeedsBadging.valueAt(index);
13045    }
13046}
13047