PackageManagerService.java revision ace27915d2cc5073bcbe9cc151a5c61683bdcd1a
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageParser;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.storage.StorageManager;
141import android.os.Debug;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.File;
179import java.io.FileDescriptor;
180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.FilenameFilter;
184import java.io.IOException;
185import java.io.InputStream;
186import java.io.PrintWriter;
187import java.nio.charset.StandardCharsets;
188import java.security.NoSuchAlgorithmException;
189import java.security.PublicKey;
190import java.security.cert.CertificateEncodingException;
191import java.security.cert.CertificateException;
192import java.text.SimpleDateFormat;
193import java.util.ArrayList;
194import java.util.Arrays;
195import java.util.Collection;
196import java.util.Collections;
197import java.util.Comparator;
198import java.util.Date;
199import java.util.HashMap;
200import java.util.HashSet;
201import java.util.Iterator;
202import java.util.List;
203import java.util.Map;
204import java.util.Set;
205import java.util.concurrent.atomic.AtomicBoolean;
206import java.util.concurrent.atomic.AtomicLong;
207
208import dalvik.system.DexFile;
209import dalvik.system.StaleDexCacheError;
210import dalvik.system.VMRuntime;
211
212import libcore.io.IoUtils;
213import libcore.util.EmptyArray;
214
215/**
216 * Keep track of all those .apks everywhere.
217 *
218 * This is very central to the platform's security; please run the unit
219 * tests whenever making modifications here:
220 *
221mmm frameworks/base/tests/AndroidTests
222adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
223adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
224 *
225 * {@hide}
226 */
227public class PackageManagerService extends IPackageManager.Stub {
228    static final String TAG = "PackageManager";
229    static final boolean DEBUG_SETTINGS = false;
230    static final boolean DEBUG_PREFERRED = false;
231    static final boolean DEBUG_UPGRADE = false;
232    private static final boolean DEBUG_INSTALL = false;
233    private static final boolean DEBUG_REMOVE = false;
234    private static final boolean DEBUG_BROADCASTS = false;
235    private static final boolean DEBUG_SHOW_INFO = false;
236    private static final boolean DEBUG_PACKAGE_INFO = false;
237    private static final boolean DEBUG_INTENT_MATCHING = false;
238    private static final boolean DEBUG_PACKAGE_SCANNING = false;
239    private static final boolean DEBUG_VERIFY = false;
240    private static final boolean DEBUG_DEXOPT = false;
241    private static final boolean DEBUG_ABI_SELECTION = false;
242
243    private static final int RADIO_UID = Process.PHONE_UID;
244    private static final int LOG_UID = Process.LOG_UID;
245    private static final int NFC_UID = Process.NFC_UID;
246    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
247    private static final int SHELL_UID = Process.SHELL_UID;
248
249    // Cap the size of permission trees that 3rd party apps can define
250    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
251
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_NO_DEX = 1<<1;
257    static final int SCAN_FORCE_DEX = 1<<2;
258    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
259    static final int SCAN_NEW_INSTALL = 1<<4;
260    static final int SCAN_NO_PATHS = 1<<5;
261    static final int SCAN_UPDATE_TIME = 1<<6;
262    static final int SCAN_DEFER_DEX = 1<<7;
263    static final int SCAN_BOOTING = 1<<8;
264    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
265    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
266    static final int SCAN_REPLACING = 1<<11;
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 VENDOR_OVERLAY_DIR = "/vendor/overlay";
306
307    private static String sPreferredInstructionSet;
308
309    final ServiceThread mHandlerThread;
310
311    private static final String IDMAP_PREFIX = "/data/resource-cache/";
312    private static final String IDMAP_SUFFIX = "@idmap";
313
314    final PackageHandler mHandler;
315
316    /**
317     * Messages for {@link #mHandler} that need to wait for system ready before
318     * being dispatched.
319     */
320    private ArrayList<Message> mPostSystemReadyMessages;
321
322    final int mSdkVersion = Build.VERSION.SDK_INT;
323
324    final Context mContext;
325    final boolean mFactoryTest;
326    final boolean mOnlyCore;
327    final boolean mLazyDexOpt;
328    final DisplayMetrics mMetrics;
329    final int mDefParseFlags;
330    final String[] mSeparateProcesses;
331
332    // This is where all application persistent data goes.
333    final File mAppDataDir;
334
335    // This is where all application persistent data goes for secondary users.
336    final File mUserAppDataDir;
337
338    /** The location for ASEC container files on internal storage. */
339    final String mAsecInternalPath;
340
341    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
342    // LOCK HELD.  Can be called with mInstallLock held.
343    final Installer mInstaller;
344
345    /** Directory where installed third-party apps stored */
346    final File mAppInstallDir;
347
348    /**
349     * Directory to which applications installed internally have their
350     * 32 bit native libraries copied.
351     */
352    private File mAppLib32InstallDir;
353
354    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
355    // apps.
356    final File mDrmAppPrivateInstallDir;
357
358    // ----------------------------------------------------------------
359
360    // Lock for state used when installing and doing other long running
361    // operations.  Methods that must be called with this lock held have
362    // the suffix "LI".
363    final Object mInstallLock = new Object();
364
365    // ----------------------------------------------------------------
366
367    // Keys are String (package name), values are Package.  This also serves
368    // as the lock for the global state.  Methods that must be called with
369    // this lock held have the prefix "LP".
370    final HashMap<String, PackageParser.Package> mPackages =
371            new HashMap<String, PackageParser.Package>();
372
373    // Tracks available target package names -> overlay package paths.
374    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
375        new HashMap<String, HashMap<String, PackageParser.Package>>();
376
377    final Settings mSettings;
378    boolean mRestoredSettings;
379
380    // System configuration read by SystemConfig.
381    final int[] mGlobalGids;
382    final SparseArray<HashSet<String>> mSystemPermissions;
383    final HashMap<String, FeatureInfo> mAvailableFeatures;
384
385    // If mac_permissions.xml was found for seinfo labeling.
386    boolean mFoundPolicyFile;
387
388    // If a recursive restorecon of /data/data/<pkg> is needed.
389    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
390
391    public static final class SharedLibraryEntry {
392        public final String path;
393        public final String apk;
394
395        SharedLibraryEntry(String _path, String _apk) {
396            path = _path;
397            apk = _apk;
398        }
399    }
400
401    // Currently known shared libraries.
402    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
403            new HashMap<String, SharedLibraryEntry>();
404
405    // All available activities, for your resolving pleasure.
406    final ActivityIntentResolver mActivities =
407            new ActivityIntentResolver();
408
409    // All available receivers, for your resolving pleasure.
410    final ActivityIntentResolver mReceivers =
411            new ActivityIntentResolver();
412
413    // All available services, for your resolving pleasure.
414    final ServiceIntentResolver mServices = new ServiceIntentResolver();
415
416    // All available providers, for your resolving pleasure.
417    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
418
419    // Mapping from provider base names (first directory in content URI codePath)
420    // to the provider information.
421    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
422            new HashMap<String, PackageParser.Provider>();
423
424    // Mapping from instrumentation class names to info about them.
425    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
426            new HashMap<ComponentName, PackageParser.Instrumentation>();
427
428    // Mapping from permission names to info about them.
429    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
430            new HashMap<String, PackageParser.PermissionGroup>();
431
432    // Packages whose data we have transfered into another package, thus
433    // should no longer exist.
434    final HashSet<String> mTransferedPackages = new HashSet<String>();
435
436    // Broadcast actions that are only available to the system.
437    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
438
439    /** List of packages waiting for verification. */
440    final SparseArray<PackageVerificationState> mPendingVerification
441            = new SparseArray<PackageVerificationState>();
442
443    /** Set of packages associated with each app op permission. */
444    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
445
446    final PackageInstallerService mInstallerService;
447
448    HashSet<PackageParser.Package> mDeferredDexOpt = null;
449
450    // Cache of users who need badging.
451    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
452
453    /** Token for keys in mPendingVerification. */
454    private int mPendingVerificationToken = 0;
455
456    volatile boolean mSystemReady;
457    volatile boolean mSafeMode;
458    volatile boolean mHasSystemUidErrors;
459
460    ApplicationInfo mAndroidApplication;
461    final ActivityInfo mResolveActivity = new ActivityInfo();
462    final ResolveInfo mResolveInfo = new ResolveInfo();
463    ComponentName mResolveComponentName;
464    PackageParser.Package mPlatformPackage;
465    ComponentName mCustomResolverComponentName;
466
467    boolean mResolverReplaced = false;
468
469    // Set of pending broadcasts for aggregating enable/disable of components.
470    static class PendingPackageBroadcasts {
471        // for each user id, a map of <package name -> components within that package>
472        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
473
474        public PendingPackageBroadcasts() {
475            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
476        }
477
478        public ArrayList<String> get(int userId, String packageName) {
479            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
480            return packages.get(packageName);
481        }
482
483        public void put(int userId, String packageName, ArrayList<String> components) {
484            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
485            packages.put(packageName, components);
486        }
487
488        public void remove(int userId, String packageName) {
489            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
490            if (packages != null) {
491                packages.remove(packageName);
492            }
493        }
494
495        public void remove(int userId) {
496            mUidMap.remove(userId);
497        }
498
499        public int userIdCount() {
500            return mUidMap.size();
501        }
502
503        public int userIdAt(int n) {
504            return mUidMap.keyAt(n);
505        }
506
507        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
508            return mUidMap.get(userId);
509        }
510
511        public int size() {
512            // total number of pending broadcast entries across all userIds
513            int num = 0;
514            for (int i = 0; i< mUidMap.size(); i++) {
515                num += mUidMap.valueAt(i).size();
516            }
517            return num;
518        }
519
520        public void clear() {
521            mUidMap.clear();
522        }
523
524        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
525            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
526            if (map == null) {
527                map = new HashMap<String, ArrayList<String>>();
528                mUidMap.put(userId, map);
529            }
530            return map;
531        }
532    }
533    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
534
535    // Service Connection to remote media container service to copy
536    // package uri's from external media onto secure containers
537    // or internal storage.
538    private IMediaContainerService mContainerService = null;
539
540    static final int SEND_PENDING_BROADCAST = 1;
541    static final int MCS_BOUND = 3;
542    static final int END_COPY = 4;
543    static final int INIT_COPY = 5;
544    static final int MCS_UNBIND = 6;
545    static final int START_CLEANING_PACKAGE = 7;
546    static final int FIND_INSTALL_LOC = 8;
547    static final int POST_INSTALL = 9;
548    static final int MCS_RECONNECT = 10;
549    static final int MCS_GIVE_UP = 11;
550    static final int UPDATED_MEDIA_STATUS = 12;
551    static final int WRITE_SETTINGS = 13;
552    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
553    static final int PACKAGE_VERIFIED = 15;
554    static final int CHECK_PENDING_VERIFICATION = 16;
555
556    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
557
558    // Delay time in millisecs
559    static final int BROADCAST_DELAY = 10 * 1000;
560
561    static UserManagerService sUserManager;
562
563    // Stores a list of users whose package restrictions file needs to be updated
564    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
565
566    final private DefaultContainerConnection mDefContainerConn =
567            new DefaultContainerConnection();
568    class DefaultContainerConnection implements ServiceConnection {
569        public void onServiceConnected(ComponentName name, IBinder service) {
570            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
571            IMediaContainerService imcs =
572                IMediaContainerService.Stub.asInterface(service);
573            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
574        }
575
576        public void onServiceDisconnected(ComponentName name) {
577            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
578        }
579    };
580
581    // Recordkeeping of restore-after-install operations that are currently in flight
582    // between the Package Manager and the Backup Manager
583    class PostInstallData {
584        public InstallArgs args;
585        public PackageInstalledInfo res;
586
587        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
588            args = _a;
589            res = _r;
590        }
591    };
592    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
593    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
594
595    private final String mRequiredVerifierPackage;
596
597    private final PackageUsage mPackageUsage = new PackageUsage();
598
599    private class PackageUsage {
600        private static final int WRITE_INTERVAL
601            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
602
603        private final Object mFileLock = new Object();
604        private final AtomicLong mLastWritten = new AtomicLong(0);
605        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
606
607        private boolean mIsHistoricalPackageUsageAvailable = true;
608
609        boolean isHistoricalPackageUsageAvailable() {
610            return mIsHistoricalPackageUsageAvailable;
611        }
612
613        void write(boolean force) {
614            if (force) {
615                writeInternal();
616                return;
617            }
618            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
619                && !DEBUG_DEXOPT) {
620                return;
621            }
622            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
623                new Thread("PackageUsage_DiskWriter") {
624                    @Override
625                    public void run() {
626                        try {
627                            writeInternal();
628                        } finally {
629                            mBackgroundWriteRunning.set(false);
630                        }
631                    }
632                }.start();
633            }
634        }
635
636        private void writeInternal() {
637            synchronized (mPackages) {
638                synchronized (mFileLock) {
639                    AtomicFile file = getFile();
640                    FileOutputStream f = null;
641                    try {
642                        f = file.startWrite();
643                        BufferedOutputStream out = new BufferedOutputStream(f);
644                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
645                        StringBuilder sb = new StringBuilder();
646                        for (PackageParser.Package pkg : mPackages.values()) {
647                            if (pkg.mLastPackageUsageTimeInMills == 0) {
648                                continue;
649                            }
650                            sb.setLength(0);
651                            sb.append(pkg.packageName);
652                            sb.append(' ');
653                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
654                            sb.append('\n');
655                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
656                        }
657                        out.flush();
658                        file.finishWrite(f);
659                    } catch (IOException e) {
660                        if (f != null) {
661                            file.failWrite(f);
662                        }
663                        Log.e(TAG, "Failed to write package usage times", e);
664                    }
665                }
666            }
667            mLastWritten.set(SystemClock.elapsedRealtime());
668        }
669
670        void readLP() {
671            synchronized (mFileLock) {
672                AtomicFile file = getFile();
673                BufferedInputStream in = null;
674                try {
675                    in = new BufferedInputStream(file.openRead());
676                    StringBuffer sb = new StringBuffer();
677                    while (true) {
678                        String packageName = readToken(in, sb, ' ');
679                        if (packageName == null) {
680                            break;
681                        }
682                        String timeInMillisString = readToken(in, sb, '\n');
683                        if (timeInMillisString == null) {
684                            throw new IOException("Failed to find last usage time for package "
685                                                  + packageName);
686                        }
687                        PackageParser.Package pkg = mPackages.get(packageName);
688                        if (pkg == null) {
689                            continue;
690                        }
691                        long timeInMillis;
692                        try {
693                            timeInMillis = Long.parseLong(timeInMillisString.toString());
694                        } catch (NumberFormatException e) {
695                            throw new IOException("Failed to parse " + timeInMillisString
696                                                  + " as a long.", e);
697                        }
698                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
699                    }
700                } catch (FileNotFoundException expected) {
701                    mIsHistoricalPackageUsageAvailable = false;
702                } catch (IOException e) {
703                    Log.w(TAG, "Failed to read package usage times", e);
704                } finally {
705                    IoUtils.closeQuietly(in);
706                }
707            }
708            mLastWritten.set(SystemClock.elapsedRealtime());
709        }
710
711        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
712                throws IOException {
713            sb.setLength(0);
714            while (true) {
715                int ch = in.read();
716                if (ch == -1) {
717                    if (sb.length() == 0) {
718                        return null;
719                    }
720                    throw new IOException("Unexpected EOF");
721                }
722                if (ch == endOfToken) {
723                    return sb.toString();
724                }
725                sb.append((char)ch);
726            }
727        }
728
729        private AtomicFile getFile() {
730            File dataDir = Environment.getDataDirectory();
731            File systemDir = new File(dataDir, "system");
732            File fname = new File(systemDir, "package-usage.list");
733            return new AtomicFile(fname);
734        }
735    }
736
737    class PackageHandler extends Handler {
738        private boolean mBound = false;
739        final ArrayList<HandlerParams> mPendingInstalls =
740            new ArrayList<HandlerParams>();
741
742        private boolean connectToService() {
743            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
744                    " DefaultContainerService");
745            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
746            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
747            if (mContext.bindServiceAsUser(service, mDefContainerConn,
748                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
749                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
750                mBound = true;
751                return true;
752            }
753            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754            return false;
755        }
756
757        private void disconnectService() {
758            mContainerService = null;
759            mBound = false;
760            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
761            mContext.unbindService(mDefContainerConn);
762            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
763        }
764
765        PackageHandler(Looper looper) {
766            super(looper);
767        }
768
769        public void handleMessage(Message msg) {
770            try {
771                doHandleMessage(msg);
772            } finally {
773                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
774            }
775        }
776
777        void doHandleMessage(Message msg) {
778            switch (msg.what) {
779                case INIT_COPY: {
780                    HandlerParams params = (HandlerParams) msg.obj;
781                    int idx = mPendingInstalls.size();
782                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
783                    // If a bind was already initiated we dont really
784                    // need to do anything. The pending install
785                    // will be processed later on.
786                    if (!mBound) {
787                        // If this is the only one pending we might
788                        // have to bind to the service again.
789                        if (!connectToService()) {
790                            Slog.e(TAG, "Failed to bind to media container service");
791                            params.serviceError();
792                            return;
793                        } else {
794                            // Once we bind to the service, the first
795                            // pending request will be processed.
796                            mPendingInstalls.add(idx, params);
797                        }
798                    } else {
799                        mPendingInstalls.add(idx, params);
800                        // Already bound to the service. Just make
801                        // sure we trigger off processing the first request.
802                        if (idx == 0) {
803                            mHandler.sendEmptyMessage(MCS_BOUND);
804                        }
805                    }
806                    break;
807                }
808                case MCS_BOUND: {
809                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
810                    if (msg.obj != null) {
811                        mContainerService = (IMediaContainerService) msg.obj;
812                    }
813                    if (mContainerService == null) {
814                        // Something seriously wrong. Bail out
815                        Slog.e(TAG, "Cannot bind to media container service");
816                        for (HandlerParams params : mPendingInstalls) {
817                            // Indicate service bind error
818                            params.serviceError();
819                        }
820                        mPendingInstalls.clear();
821                    } else if (mPendingInstalls.size() > 0) {
822                        HandlerParams params = mPendingInstalls.get(0);
823                        if (params != null) {
824                            if (params.startCopy()) {
825                                // We are done...  look for more work or to
826                                // go idle.
827                                if (DEBUG_SD_INSTALL) Log.i(TAG,
828                                        "Checking for more work or unbind...");
829                                // Delete pending install
830                                if (mPendingInstalls.size() > 0) {
831                                    mPendingInstalls.remove(0);
832                                }
833                                if (mPendingInstalls.size() == 0) {
834                                    if (mBound) {
835                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
836                                                "Posting delayed MCS_UNBIND");
837                                        removeMessages(MCS_UNBIND);
838                                        Message ubmsg = obtainMessage(MCS_UNBIND);
839                                        // Unbind after a little delay, to avoid
840                                        // continual thrashing.
841                                        sendMessageDelayed(ubmsg, 10000);
842                                    }
843                                } else {
844                                    // There are more pending requests in queue.
845                                    // Just post MCS_BOUND message to trigger processing
846                                    // of next pending install.
847                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
848                                            "Posting MCS_BOUND for next work");
849                                    mHandler.sendEmptyMessage(MCS_BOUND);
850                                }
851                            }
852                        }
853                    } else {
854                        // Should never happen ideally.
855                        Slog.w(TAG, "Empty queue");
856                    }
857                    break;
858                }
859                case MCS_RECONNECT: {
860                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
861                    if (mPendingInstalls.size() > 0) {
862                        if (mBound) {
863                            disconnectService();
864                        }
865                        if (!connectToService()) {
866                            Slog.e(TAG, "Failed to bind to media container service");
867                            for (HandlerParams params : mPendingInstalls) {
868                                // Indicate service bind error
869                                params.serviceError();
870                            }
871                            mPendingInstalls.clear();
872                        }
873                    }
874                    break;
875                }
876                case MCS_UNBIND: {
877                    // If there is no actual work left, then time to unbind.
878                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
879
880                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
881                        if (mBound) {
882                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
883
884                            disconnectService();
885                        }
886                    } else if (mPendingInstalls.size() > 0) {
887                        // There are more pending requests in queue.
888                        // Just post MCS_BOUND message to trigger processing
889                        // of next pending install.
890                        mHandler.sendEmptyMessage(MCS_BOUND);
891                    }
892
893                    break;
894                }
895                case MCS_GIVE_UP: {
896                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
897                    mPendingInstalls.remove(0);
898                    break;
899                }
900                case SEND_PENDING_BROADCAST: {
901                    String packages[];
902                    ArrayList<String> components[];
903                    int size = 0;
904                    int uids[];
905                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
906                    synchronized (mPackages) {
907                        if (mPendingBroadcasts == null) {
908                            return;
909                        }
910                        size = mPendingBroadcasts.size();
911                        if (size <= 0) {
912                            // Nothing to be done. Just return
913                            return;
914                        }
915                        packages = new String[size];
916                        components = new ArrayList[size];
917                        uids = new int[size];
918                        int i = 0;  // filling out the above arrays
919
920                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
921                            int packageUserId = mPendingBroadcasts.userIdAt(n);
922                            Iterator<Map.Entry<String, ArrayList<String>>> it
923                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
924                                            .entrySet().iterator();
925                            while (it.hasNext() && i < size) {
926                                Map.Entry<String, ArrayList<String>> ent = it.next();
927                                packages[i] = ent.getKey();
928                                components[i] = ent.getValue();
929                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
930                                uids[i] = (ps != null)
931                                        ? UserHandle.getUid(packageUserId, ps.appId)
932                                        : -1;
933                                i++;
934                            }
935                        }
936                        size = i;
937                        mPendingBroadcasts.clear();
938                    }
939                    // Send broadcasts
940                    for (int i = 0; i < size; i++) {
941                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
942                    }
943                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
944                    break;
945                }
946                case START_CLEANING_PACKAGE: {
947                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
948                    final String packageName = (String)msg.obj;
949                    final int userId = msg.arg1;
950                    final boolean andCode = msg.arg2 != 0;
951                    synchronized (mPackages) {
952                        if (userId == UserHandle.USER_ALL) {
953                            int[] users = sUserManager.getUserIds();
954                            for (int user : users) {
955                                mSettings.addPackageToCleanLPw(
956                                        new PackageCleanItem(user, packageName, andCode));
957                            }
958                        } else {
959                            mSettings.addPackageToCleanLPw(
960                                    new PackageCleanItem(userId, packageName, andCode));
961                        }
962                    }
963                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
964                    startCleaningPackages();
965                } break;
966                case POST_INSTALL: {
967                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
968                    PostInstallData data = mRunningInstalls.get(msg.arg1);
969                    mRunningInstalls.delete(msg.arg1);
970                    boolean deleteOld = false;
971
972                    if (data != null) {
973                        InstallArgs args = data.args;
974                        PackageInstalledInfo res = data.res;
975
976                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
977                            res.removedInfo.sendBroadcast(false, true, false);
978                            Bundle extras = new Bundle(1);
979                            extras.putInt(Intent.EXTRA_UID, res.uid);
980                            // Determine the set of users who are adding this
981                            // package for the first time vs. those who are seeing
982                            // an update.
983                            int[] firstUsers;
984                            int[] updateUsers = new int[0];
985                            if (res.origUsers == null || res.origUsers.length == 0) {
986                                firstUsers = res.newUsers;
987                            } else {
988                                firstUsers = new int[0];
989                                for (int i=0; i<res.newUsers.length; i++) {
990                                    int user = res.newUsers[i];
991                                    boolean isNew = true;
992                                    for (int j=0; j<res.origUsers.length; j++) {
993                                        if (res.origUsers[j] == user) {
994                                            isNew = false;
995                                            break;
996                                        }
997                                    }
998                                    if (isNew) {
999                                        int[] newFirst = new int[firstUsers.length+1];
1000                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1001                                                firstUsers.length);
1002                                        newFirst[firstUsers.length] = user;
1003                                        firstUsers = newFirst;
1004                                    } else {
1005                                        int[] newUpdate = new int[updateUsers.length+1];
1006                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1007                                                updateUsers.length);
1008                                        newUpdate[updateUsers.length] = user;
1009                                        updateUsers = newUpdate;
1010                                    }
1011                                }
1012                            }
1013                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1014                                    res.pkg.applicationInfo.packageName,
1015                                    extras, null, null, firstUsers);
1016                            final boolean update = res.removedInfo.removedPackage != null;
1017                            if (update) {
1018                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1019                            }
1020                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1021                                    res.pkg.applicationInfo.packageName,
1022                                    extras, null, null, updateUsers);
1023                            if (update) {
1024                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1025                                        res.pkg.applicationInfo.packageName,
1026                                        extras, null, null, updateUsers);
1027                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1028                                        null, null,
1029                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1030
1031                                // treat asec-hosted packages like removable media on upgrade
1032                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1033                                    if (DEBUG_INSTALL) {
1034                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1035                                                + " is ASEC-hosted -> AVAILABLE");
1036                                    }
1037                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1038                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1039                                    pkgList.add(res.pkg.applicationInfo.packageName);
1040                                    sendResourcesChangedBroadcast(true, true,
1041                                            pkgList,uidArray, null);
1042                                }
1043                            }
1044                            if (res.removedInfo.args != null) {
1045                                // Remove the replaced package's older resources safely now
1046                                deleteOld = true;
1047                            }
1048
1049                            // Log current value of "unknown sources" setting
1050                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1051                                getUnknownSourcesSettings());
1052                        }
1053                        // Force a gc to clear up things
1054                        Runtime.getRuntime().gc();
1055                        // We delete after a gc for applications  on sdcard.
1056                        if (deleteOld) {
1057                            synchronized (mInstallLock) {
1058                                res.removedInfo.args.doPostDeleteLI(true);
1059                            }
1060                        }
1061                        if (args.observer != null) {
1062                            try {
1063                                Bundle extras = extrasForInstallResult(res);
1064                                args.observer.onPackageInstalled(res.name, res.returnCode,
1065                                        res.returnMsg, extras);
1066                            } catch (RemoteException e) {
1067                                Slog.i(TAG, "Observer no longer exists.");
1068                            }
1069                        }
1070                    } else {
1071                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1072                    }
1073                } break;
1074                case UPDATED_MEDIA_STATUS: {
1075                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1076                    boolean reportStatus = msg.arg1 == 1;
1077                    boolean doGc = msg.arg2 == 1;
1078                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1079                    if (doGc) {
1080                        // Force a gc to clear up stale containers.
1081                        Runtime.getRuntime().gc();
1082                    }
1083                    if (msg.obj != null) {
1084                        @SuppressWarnings("unchecked")
1085                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1086                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1087                        // Unload containers
1088                        unloadAllContainers(args);
1089                    }
1090                    if (reportStatus) {
1091                        try {
1092                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1093                            PackageHelper.getMountService().finishMediaUpdate();
1094                        } catch (RemoteException e) {
1095                            Log.e(TAG, "MountService not running?");
1096                        }
1097                    }
1098                } break;
1099                case WRITE_SETTINGS: {
1100                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1101                    synchronized (mPackages) {
1102                        removeMessages(WRITE_SETTINGS);
1103                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1104                        mSettings.writeLPr();
1105                        mDirtyUsers.clear();
1106                    }
1107                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1108                } break;
1109                case WRITE_PACKAGE_RESTRICTIONS: {
1110                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1111                    synchronized (mPackages) {
1112                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1113                        for (int userId : mDirtyUsers) {
1114                            mSettings.writePackageRestrictionsLPr(userId);
1115                        }
1116                        mDirtyUsers.clear();
1117                    }
1118                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1119                } break;
1120                case CHECK_PENDING_VERIFICATION: {
1121                    final int verificationId = msg.arg1;
1122                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1123
1124                    if ((state != null) && !state.timeoutExtended()) {
1125                        final InstallArgs args = state.getInstallArgs();
1126                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1127
1128                        Slog.i(TAG, "Verification timed out for " + originUri);
1129                        mPendingVerification.remove(verificationId);
1130
1131                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1132
1133                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1134                            Slog.i(TAG, "Continuing with installation of " + originUri);
1135                            state.setVerifierResponse(Binder.getCallingUid(),
1136                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1137                            broadcastPackageVerified(verificationId, originUri,
1138                                    PackageManager.VERIFICATION_ALLOW,
1139                                    state.getInstallArgs().getUser());
1140                            try {
1141                                ret = args.copyApk(mContainerService, true);
1142                            } catch (RemoteException e) {
1143                                Slog.e(TAG, "Could not contact the ContainerService");
1144                            }
1145                        } else {
1146                            broadcastPackageVerified(verificationId, originUri,
1147                                    PackageManager.VERIFICATION_REJECT,
1148                                    state.getInstallArgs().getUser());
1149                        }
1150
1151                        processPendingInstall(args, ret);
1152                        mHandler.sendEmptyMessage(MCS_UNBIND);
1153                    }
1154                    break;
1155                }
1156                case PACKAGE_VERIFIED: {
1157                    final int verificationId = msg.arg1;
1158
1159                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1160                    if (state == null) {
1161                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1162                        break;
1163                    }
1164
1165                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1166
1167                    state.setVerifierResponse(response.callerUid, response.code);
1168
1169                    if (state.isVerificationComplete()) {
1170                        mPendingVerification.remove(verificationId);
1171
1172                        final InstallArgs args = state.getInstallArgs();
1173                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1174
1175                        int ret;
1176                        if (state.isInstallAllowed()) {
1177                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1178                            broadcastPackageVerified(verificationId, originUri,
1179                                    response.code, state.getInstallArgs().getUser());
1180                            try {
1181                                ret = args.copyApk(mContainerService, true);
1182                            } catch (RemoteException e) {
1183                                Slog.e(TAG, "Could not contact the ContainerService");
1184                            }
1185                        } else {
1186                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1187                        }
1188
1189                        processPendingInstall(args, ret);
1190
1191                        mHandler.sendEmptyMessage(MCS_UNBIND);
1192                    }
1193
1194                    break;
1195                }
1196            }
1197        }
1198    }
1199
1200    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1201        Bundle extras = null;
1202        switch (res.returnCode) {
1203            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1204                extras = new Bundle();
1205                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1206                        res.origPermission);
1207                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1208                        res.origPackage);
1209                break;
1210            }
1211        }
1212        return extras;
1213    }
1214
1215    void scheduleWriteSettingsLocked() {
1216        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1217            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1218        }
1219    }
1220
1221    void scheduleWritePackageRestrictionsLocked(int userId) {
1222        if (!sUserManager.exists(userId)) return;
1223        mDirtyUsers.add(userId);
1224        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1225            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1226        }
1227    }
1228
1229    public static final PackageManagerService main(Context context, Installer installer,
1230            boolean factoryTest, boolean onlyCore) {
1231        PackageManagerService m = new PackageManagerService(context, installer,
1232                factoryTest, onlyCore);
1233        ServiceManager.addService("package", m);
1234        return m;
1235    }
1236
1237    static String[] splitString(String str, char sep) {
1238        int count = 1;
1239        int i = 0;
1240        while ((i=str.indexOf(sep, i)) >= 0) {
1241            count++;
1242            i++;
1243        }
1244
1245        String[] res = new String[count];
1246        i=0;
1247        count = 0;
1248        int lastI=0;
1249        while ((i=str.indexOf(sep, i)) >= 0) {
1250            res[count] = str.substring(lastI, i);
1251            count++;
1252            i++;
1253            lastI = i;
1254        }
1255        res[count] = str.substring(lastI, str.length());
1256        return res;
1257    }
1258
1259    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1260        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1261                Context.DISPLAY_SERVICE);
1262        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1263    }
1264
1265    public PackageManagerService(Context context, Installer installer,
1266            boolean factoryTest, boolean onlyCore) {
1267        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1268                SystemClock.uptimeMillis());
1269
1270        if (mSdkVersion <= 0) {
1271            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1272        }
1273
1274        mContext = context;
1275        mFactoryTest = factoryTest;
1276        mOnlyCore = onlyCore;
1277        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1278        mMetrics = new DisplayMetrics();
1279        mSettings = new Settings(context);
1280        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1281                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1282        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1283                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1284        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1285                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1287                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1288        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1289                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1290        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1291                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1292
1293        String separateProcesses = SystemProperties.get("debug.separate_processes");
1294        if (separateProcesses != null && separateProcesses.length() > 0) {
1295            if ("*".equals(separateProcesses)) {
1296                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1297                mSeparateProcesses = null;
1298                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1299            } else {
1300                mDefParseFlags = 0;
1301                mSeparateProcesses = separateProcesses.split(",");
1302                Slog.w(TAG, "Running with debug.separate_processes: "
1303                        + separateProcesses);
1304            }
1305        } else {
1306            mDefParseFlags = 0;
1307            mSeparateProcesses = null;
1308        }
1309
1310        mInstaller = installer;
1311
1312        getDefaultDisplayMetrics(context, mMetrics);
1313
1314        SystemConfig systemConfig = SystemConfig.getInstance();
1315        mGlobalGids = systemConfig.getGlobalGids();
1316        mSystemPermissions = systemConfig.getSystemPermissions();
1317        mAvailableFeatures = systemConfig.getAvailableFeatures();
1318
1319        synchronized (mInstallLock) {
1320        // writer
1321        synchronized (mPackages) {
1322            mHandlerThread = new ServiceThread(TAG,
1323                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1324            mHandlerThread.start();
1325            mHandler = new PackageHandler(mHandlerThread.getLooper());
1326            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1327
1328            File dataDir = Environment.getDataDirectory();
1329            mAppDataDir = new File(dataDir, "data");
1330            mAppInstallDir = new File(dataDir, "app");
1331            mAppLib32InstallDir = new File(dataDir, "app-lib");
1332            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1333            mUserAppDataDir = new File(dataDir, "user");
1334            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1335
1336            sUserManager = new UserManagerService(context, this,
1337                    mInstallLock, mPackages);
1338
1339            // Propagate permission configuration in to package manager.
1340            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1341                    = systemConfig.getPermissions();
1342            for (int i=0; i<permConfig.size(); i++) {
1343                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1344                BasePermission bp = mSettings.mPermissions.get(perm.name);
1345                if (bp == null) {
1346                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1347                    mSettings.mPermissions.put(perm.name, bp);
1348                }
1349                if (perm.gids != null) {
1350                    bp.gids = appendInts(bp.gids, perm.gids);
1351                }
1352            }
1353
1354            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1355            for (int i=0; i<libConfig.size(); i++) {
1356                mSharedLibraries.put(libConfig.keyAt(i),
1357                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1358            }
1359
1360            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1361
1362            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1363                    mSdkVersion, mOnlyCore);
1364
1365            String customResolverActivity = Resources.getSystem().getString(
1366                    R.string.config_customResolverActivity);
1367            if (TextUtils.isEmpty(customResolverActivity)) {
1368                customResolverActivity = null;
1369            } else {
1370                mCustomResolverComponentName = ComponentName.unflattenFromString(
1371                        customResolverActivity);
1372            }
1373
1374            long startTime = SystemClock.uptimeMillis();
1375
1376            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1377                    startTime);
1378
1379            // Set flag to monitor and not change apk file paths when
1380            // scanning install directories.
1381            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1382
1383            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1384
1385            /**
1386             * Add everything in the in the boot class path to the
1387             * list of process files because dexopt will have been run
1388             * if necessary during zygote startup.
1389             */
1390            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1391            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1392
1393            if (bootClassPath != null) {
1394                String[] bootClassPathElements = splitString(bootClassPath, ':');
1395                for (String element : bootClassPathElements) {
1396                    alreadyDexOpted.add(element);
1397                }
1398            } else {
1399                Slog.w(TAG, "No BOOTCLASSPATH found!");
1400            }
1401
1402            if (systemServerClassPath != null) {
1403                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1404                for (String element : systemServerClassPathElements) {
1405                    alreadyDexOpted.add(element);
1406                }
1407            } else {
1408                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1409            }
1410
1411            boolean didDexOptLibraryOrTool = false;
1412
1413            final List<String> allInstructionSets = getAllInstructionSets();
1414            final String[] dexCodeInstructionSets =
1415                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1416
1417            /**
1418             * Ensure all external libraries have had dexopt run on them.
1419             */
1420            if (mSharedLibraries.size() > 0) {
1421                // NOTE: For now, we're compiling these system "shared libraries"
1422                // (and framework jars) into all available architectures. It's possible
1423                // to compile them only when we come across an app that uses them (there's
1424                // already logic for that in scanPackageLI) but that adds some complexity.
1425                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1426                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1427                        final String lib = libEntry.path;
1428                        if (lib == null) {
1429                            continue;
1430                        }
1431
1432                        try {
1433                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1434                                                                                 dexCodeInstructionSet,
1435                                                                                 false);
1436                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1437                                alreadyDexOpted.add(lib);
1438
1439                                // The list of "shared libraries" we have at this point is
1440                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1441                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1442                                } else {
1443                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1444                                }
1445                                didDexOptLibraryOrTool = true;
1446                            }
1447                        } catch (FileNotFoundException e) {
1448                            Slog.w(TAG, "Library not found: " + lib);
1449                        } catch (IOException e) {
1450                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1451                                    + e.getMessage());
1452                        }
1453                    }
1454                }
1455            }
1456
1457            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1458
1459            // Gross hack for now: we know this file doesn't contain any
1460            // code, so don't dexopt it to avoid the resulting log spew.
1461            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1462
1463            // Gross hack for now: we know this file is only part of
1464            // the boot class path for art, so don't dexopt it to
1465            // avoid the resulting log spew.
1466            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1467
1468            /**
1469             * And there are a number of commands implemented in Java, which
1470             * we currently need to do the dexopt on so that they can be
1471             * run from a non-root shell.
1472             */
1473            String[] frameworkFiles = frameworkDir.list();
1474            if (frameworkFiles != null) {
1475                // TODO: We could compile these only for the most preferred ABI. We should
1476                // first double check that the dex files for these commands are not referenced
1477                // by other system apps.
1478                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1479                    for (int i=0; i<frameworkFiles.length; i++) {
1480                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1481                        String path = libPath.getPath();
1482                        // Skip the file if we already did it.
1483                        if (alreadyDexOpted.contains(path)) {
1484                            continue;
1485                        }
1486                        // Skip the file if it is not a type we want to dexopt.
1487                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1488                            continue;
1489                        }
1490                        try {
1491                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1492                                                                                 dexCodeInstructionSet,
1493                                                                                 false);
1494                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1495                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1496                                didDexOptLibraryOrTool = true;
1497                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1498                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1499                                didDexOptLibraryOrTool = true;
1500                            }
1501                        } catch (FileNotFoundException e) {
1502                            Slog.w(TAG, "Jar not found: " + path);
1503                        } catch (IOException e) {
1504                            Slog.w(TAG, "Exception reading jar: " + path, e);
1505                        }
1506                    }
1507                }
1508            }
1509
1510            // Collect vendor overlay packages.
1511            // (Do this before scanning any apps.)
1512            // For security and version matching reason, only consider
1513            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1514            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1515            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1516                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1517
1518            // Find base frameworks (resource packages without code).
1519            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1520                    | PackageParser.PARSE_IS_SYSTEM_DIR
1521                    | PackageParser.PARSE_IS_PRIVILEGED,
1522                    scanFlags | SCAN_NO_DEX, 0);
1523
1524            // Collected privileged system packages.
1525            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1526            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1527                    | PackageParser.PARSE_IS_SYSTEM_DIR
1528                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1529
1530            // Collect ordinary system packages.
1531            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1532            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1533                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1534
1535            // Collect all vendor packages.
1536            File vendorAppDir = new File("/vendor/app");
1537            try {
1538                vendorAppDir = vendorAppDir.getCanonicalFile();
1539            } catch (IOException e) {
1540                // failed to look up canonical path, continue with original one
1541            }
1542            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1543                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1544
1545            // Collect all OEM packages.
1546            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1547            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1548                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1549
1550            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1551            mInstaller.moveFiles();
1552
1553            // Prune any system packages that no longer exist.
1554            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1555            if (!mOnlyCore) {
1556                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1557                while (psit.hasNext()) {
1558                    PackageSetting ps = psit.next();
1559
1560                    /*
1561                     * If this is not a system app, it can't be a
1562                     * disable system app.
1563                     */
1564                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1565                        continue;
1566                    }
1567
1568                    /*
1569                     * If the package is scanned, it's not erased.
1570                     */
1571                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1572                    if (scannedPkg != null) {
1573                        /*
1574                         * If the system app is both scanned and in the
1575                         * disabled packages list, then it must have been
1576                         * added via OTA. Remove it from the currently
1577                         * scanned package so the previously user-installed
1578                         * application can be scanned.
1579                         */
1580                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1581                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1582                                    + "; removing system app");
1583                            removePackageLI(ps, true);
1584                        }
1585
1586                        continue;
1587                    }
1588
1589                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1590                        psit.remove();
1591                        String msg = "System package " + ps.name
1592                                + " no longer exists; wiping its data";
1593                        reportSettingsProblem(Log.WARN, msg);
1594                        removeDataDirsLI(ps.name);
1595                    } else {
1596                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1597                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1598                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1599                        }
1600                    }
1601                }
1602            }
1603
1604            //look for any incomplete package installations
1605            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1606            //clean up list
1607            for(int i = 0; i < deletePkgsList.size(); i++) {
1608                //clean up here
1609                cleanupInstallFailedPackage(deletePkgsList.get(i));
1610            }
1611            //delete tmp files
1612            deleteTempPackageFiles();
1613
1614            // Remove any shared userIDs that have no associated packages
1615            mSettings.pruneSharedUsersLPw();
1616
1617            if (!mOnlyCore) {
1618                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1619                        SystemClock.uptimeMillis());
1620                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1621
1622                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1623                        scanFlags, 0);
1624
1625                /**
1626                 * Remove disable package settings for any updated system
1627                 * apps that were removed via an OTA. If they're not a
1628                 * previously-updated app, remove them completely.
1629                 * Otherwise, just revoke their system-level permissions.
1630                 */
1631                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1632                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1633                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1634
1635                    String msg;
1636                    if (deletedPkg == null) {
1637                        msg = "Updated system package " + deletedAppName
1638                                + " no longer exists; wiping its data";
1639                        removeDataDirsLI(deletedAppName);
1640                    } else {
1641                        msg = "Updated system app + " + deletedAppName
1642                                + " no longer present; removing system privileges for "
1643                                + deletedAppName;
1644
1645                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1646
1647                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1648                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1649                    }
1650                    reportSettingsProblem(Log.WARN, msg);
1651                }
1652            }
1653
1654            // Now that we know all of the shared libraries, update all clients to have
1655            // the correct library paths.
1656            updateAllSharedLibrariesLPw();
1657
1658            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1659                // NOTE: We ignore potential failures here during a system scan (like
1660                // the rest of the commands above) because there's precious little we
1661                // can do about it. A settings error is reported, though.
1662                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1663                        false /* force dexopt */, false /* defer dexopt */);
1664            }
1665
1666            // Now that we know all the packages we are keeping,
1667            // read and update their last usage times.
1668            mPackageUsage.readLP();
1669
1670            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1671                    SystemClock.uptimeMillis());
1672            Slog.i(TAG, "Time to scan packages: "
1673                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1674                    + " seconds");
1675
1676            // If the platform SDK has changed since the last time we booted,
1677            // we need to re-grant app permission to catch any new ones that
1678            // appear.  This is really a hack, and means that apps can in some
1679            // cases get permissions that the user didn't initially explicitly
1680            // allow...  it would be nice to have some better way to handle
1681            // this situation.
1682            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1683                    != mSdkVersion;
1684            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1685                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1686                    + "; regranting permissions for internal storage");
1687            mSettings.mInternalSdkPlatform = mSdkVersion;
1688
1689            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1690                    | (regrantPermissions
1691                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1692                            : 0));
1693
1694            // If this is the first boot, and it is a normal boot, then
1695            // we need to initialize the default preferred apps.
1696            if (!mRestoredSettings && !onlyCore) {
1697                mSettings.readDefaultPreferredAppsLPw(this, 0);
1698            }
1699
1700            // If this is first boot after an OTA, and a normal boot, then
1701            // we need to clear code cache directories.
1702            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1703                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1704                for (String pkgName : mSettings.mPackages.keySet()) {
1705                    deleteCodeCacheDirsLI(pkgName);
1706                }
1707                mSettings.mFingerprint = Build.FINGERPRINT;
1708            }
1709
1710            // All the changes are done during package scanning.
1711            mSettings.updateInternalDatabaseVersion();
1712
1713            // can downgrade to reader
1714            mSettings.writeLPr();
1715
1716            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1717                    SystemClock.uptimeMillis());
1718
1719
1720            mRequiredVerifierPackage = getRequiredVerifierLPr();
1721        } // synchronized (mPackages)
1722        } // synchronized (mInstallLock)
1723
1724        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1725
1726        // Now after opening every single application zip, make sure they
1727        // are all flushed.  Not really needed, but keeps things nice and
1728        // tidy.
1729        Runtime.getRuntime().gc();
1730    }
1731
1732    @Override
1733    public boolean isFirstBoot() {
1734        return !mRestoredSettings;
1735    }
1736
1737    @Override
1738    public boolean isOnlyCoreApps() {
1739        return mOnlyCore;
1740    }
1741
1742    private String getRequiredVerifierLPr() {
1743        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1744        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1745                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1746
1747        String requiredVerifier = null;
1748
1749        final int N = receivers.size();
1750        for (int i = 0; i < N; i++) {
1751            final ResolveInfo info = receivers.get(i);
1752
1753            if (info.activityInfo == null) {
1754                continue;
1755            }
1756
1757            final String packageName = info.activityInfo.packageName;
1758
1759            final PackageSetting ps = mSettings.mPackages.get(packageName);
1760            if (ps == null) {
1761                continue;
1762            }
1763
1764            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1765            if (!gp.grantedPermissions
1766                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1767                continue;
1768            }
1769
1770            if (requiredVerifier != null) {
1771                throw new RuntimeException("There can be only one required verifier");
1772            }
1773
1774            requiredVerifier = packageName;
1775        }
1776
1777        return requiredVerifier;
1778    }
1779
1780    @Override
1781    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1782            throws RemoteException {
1783        try {
1784            return super.onTransact(code, data, reply, flags);
1785        } catch (RuntimeException e) {
1786            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1787                Slog.wtf(TAG, "Package Manager Crash", e);
1788            }
1789            throw e;
1790        }
1791    }
1792
1793    void cleanupInstallFailedPackage(PackageSetting ps) {
1794        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1795        removeDataDirsLI(ps.name);
1796        if (ps.codePath != null) {
1797            if (ps.codePath.isDirectory()) {
1798                FileUtils.deleteContents(ps.codePath);
1799            }
1800            ps.codePath.delete();
1801        }
1802        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1803            if (ps.resourcePath.isDirectory()) {
1804                FileUtils.deleteContents(ps.resourcePath);
1805            }
1806            ps.resourcePath.delete();
1807        }
1808        mSettings.removePackageLPw(ps.name);
1809    }
1810
1811    static int[] appendInts(int[] cur, int[] add) {
1812        if (add == null) return cur;
1813        if (cur == null) return add;
1814        final int N = add.length;
1815        for (int i=0; i<N; i++) {
1816            cur = appendInt(cur, add[i]);
1817        }
1818        return cur;
1819    }
1820
1821    static int[] removeInts(int[] cur, int[] rem) {
1822        if (rem == null) return cur;
1823        if (cur == null) return cur;
1824        final int N = rem.length;
1825        for (int i=0; i<N; i++) {
1826            cur = removeInt(cur, rem[i]);
1827        }
1828        return cur;
1829    }
1830
1831    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1832        if (!sUserManager.exists(userId)) return null;
1833        final PackageSetting ps = (PackageSetting) p.mExtras;
1834        if (ps == null) {
1835            return null;
1836        }
1837        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1838        final PackageUserState state = ps.readUserState(userId);
1839        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1840                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1841                state, userId);
1842    }
1843
1844    @Override
1845    public boolean isPackageAvailable(String packageName, int userId) {
1846        if (!sUserManager.exists(userId)) return false;
1847        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1848        synchronized (mPackages) {
1849            PackageParser.Package p = mPackages.get(packageName);
1850            if (p != null) {
1851                final PackageSetting ps = (PackageSetting) p.mExtras;
1852                if (ps != null) {
1853                    final PackageUserState state = ps.readUserState(userId);
1854                    if (state != null) {
1855                        return PackageParser.isAvailable(state);
1856                    }
1857                }
1858            }
1859        }
1860        return false;
1861    }
1862
1863    @Override
1864    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1865        if (!sUserManager.exists(userId)) return null;
1866        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1867        // reader
1868        synchronized (mPackages) {
1869            PackageParser.Package p = mPackages.get(packageName);
1870            if (DEBUG_PACKAGE_INFO)
1871                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1872            if (p != null) {
1873                return generatePackageInfo(p, flags, userId);
1874            }
1875            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1876                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1877            }
1878        }
1879        return null;
1880    }
1881
1882    @Override
1883    public String[] currentToCanonicalPackageNames(String[] names) {
1884        String[] out = new String[names.length];
1885        // reader
1886        synchronized (mPackages) {
1887            for (int i=names.length-1; i>=0; i--) {
1888                PackageSetting ps = mSettings.mPackages.get(names[i]);
1889                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1890            }
1891        }
1892        return out;
1893    }
1894
1895    @Override
1896    public String[] canonicalToCurrentPackageNames(String[] names) {
1897        String[] out = new String[names.length];
1898        // reader
1899        synchronized (mPackages) {
1900            for (int i=names.length-1; i>=0; i--) {
1901                String cur = mSettings.mRenamedPackages.get(names[i]);
1902                out[i] = cur != null ? cur : names[i];
1903            }
1904        }
1905        return out;
1906    }
1907
1908    @Override
1909    public int getPackageUid(String packageName, int userId) {
1910        if (!sUserManager.exists(userId)) return -1;
1911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1912        // reader
1913        synchronized (mPackages) {
1914            PackageParser.Package p = mPackages.get(packageName);
1915            if(p != null) {
1916                return UserHandle.getUid(userId, p.applicationInfo.uid);
1917            }
1918            PackageSetting ps = mSettings.mPackages.get(packageName);
1919            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1920                return -1;
1921            }
1922            p = ps.pkg;
1923            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1924        }
1925    }
1926
1927    @Override
1928    public int[] getPackageGids(String packageName) {
1929        // reader
1930        synchronized (mPackages) {
1931            PackageParser.Package p = mPackages.get(packageName);
1932            if (DEBUG_PACKAGE_INFO)
1933                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1934            if (p != null) {
1935                final PackageSetting ps = (PackageSetting)p.mExtras;
1936                return ps.getGids();
1937            }
1938        }
1939        // stupid thing to indicate an error.
1940        return new int[0];
1941    }
1942
1943    static final PermissionInfo generatePermissionInfo(
1944            BasePermission bp, int flags) {
1945        if (bp.perm != null) {
1946            return PackageParser.generatePermissionInfo(bp.perm, flags);
1947        }
1948        PermissionInfo pi = new PermissionInfo();
1949        pi.name = bp.name;
1950        pi.packageName = bp.sourcePackage;
1951        pi.nonLocalizedLabel = bp.name;
1952        pi.protectionLevel = bp.protectionLevel;
1953        return pi;
1954    }
1955
1956    @Override
1957    public PermissionInfo getPermissionInfo(String name, int flags) {
1958        // reader
1959        synchronized (mPackages) {
1960            final BasePermission p = mSettings.mPermissions.get(name);
1961            if (p != null) {
1962                return generatePermissionInfo(p, flags);
1963            }
1964            return null;
1965        }
1966    }
1967
1968    @Override
1969    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1970        // reader
1971        synchronized (mPackages) {
1972            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1973            for (BasePermission p : mSettings.mPermissions.values()) {
1974                if (group == null) {
1975                    if (p.perm == null || p.perm.info.group == null) {
1976                        out.add(generatePermissionInfo(p, flags));
1977                    }
1978                } else {
1979                    if (p.perm != null && group.equals(p.perm.info.group)) {
1980                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1981                    }
1982                }
1983            }
1984
1985            if (out.size() > 0) {
1986                return out;
1987            }
1988            return mPermissionGroups.containsKey(group) ? out : null;
1989        }
1990    }
1991
1992    @Override
1993    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1994        // reader
1995        synchronized (mPackages) {
1996            return PackageParser.generatePermissionGroupInfo(
1997                    mPermissionGroups.get(name), flags);
1998        }
1999    }
2000
2001    @Override
2002    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2003        // reader
2004        synchronized (mPackages) {
2005            final int N = mPermissionGroups.size();
2006            ArrayList<PermissionGroupInfo> out
2007                    = new ArrayList<PermissionGroupInfo>(N);
2008            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2009                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2010            }
2011            return out;
2012        }
2013    }
2014
2015    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2016            int userId) {
2017        if (!sUserManager.exists(userId)) return null;
2018        PackageSetting ps = mSettings.mPackages.get(packageName);
2019        if (ps != null) {
2020            if (ps.pkg == null) {
2021                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2022                        flags, userId);
2023                if (pInfo != null) {
2024                    return pInfo.applicationInfo;
2025                }
2026                return null;
2027            }
2028            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2029                    ps.readUserState(userId), userId);
2030        }
2031        return null;
2032    }
2033
2034    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2035            int userId) {
2036        if (!sUserManager.exists(userId)) return null;
2037        PackageSetting ps = mSettings.mPackages.get(packageName);
2038        if (ps != null) {
2039            PackageParser.Package pkg = ps.pkg;
2040            if (pkg == null) {
2041                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2042                    return null;
2043                }
2044                // Only data remains, so we aren't worried about code paths
2045                pkg = new PackageParser.Package(packageName);
2046                pkg.applicationInfo.packageName = packageName;
2047                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2048                pkg.applicationInfo.dataDir =
2049                        getDataPathForPackage(packageName, 0).getPath();
2050                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2051                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2052            }
2053            return generatePackageInfo(pkg, flags, userId);
2054        }
2055        return null;
2056    }
2057
2058    @Override
2059    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2060        if (!sUserManager.exists(userId)) return null;
2061        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2062        // writer
2063        synchronized (mPackages) {
2064            PackageParser.Package p = mPackages.get(packageName);
2065            if (DEBUG_PACKAGE_INFO) Log.v(
2066                    TAG, "getApplicationInfo " + packageName
2067                    + ": " + p);
2068            if (p != null) {
2069                PackageSetting ps = mSettings.mPackages.get(packageName);
2070                if (ps == null) return null;
2071                // Note: isEnabledLP() does not apply here - always return info
2072                return PackageParser.generateApplicationInfo(
2073                        p, flags, ps.readUserState(userId), userId);
2074            }
2075            if ("android".equals(packageName)||"system".equals(packageName)) {
2076                return mAndroidApplication;
2077            }
2078            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2079                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2080            }
2081        }
2082        return null;
2083    }
2084
2085
2086    @Override
2087    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2088        mContext.enforceCallingOrSelfPermission(
2089                android.Manifest.permission.CLEAR_APP_CACHE, null);
2090        // Queue up an async operation since clearing cache may take a little while.
2091        mHandler.post(new Runnable() {
2092            public void run() {
2093                mHandler.removeCallbacks(this);
2094                int retCode = -1;
2095                synchronized (mInstallLock) {
2096                    retCode = mInstaller.freeCache(freeStorageSize);
2097                    if (retCode < 0) {
2098                        Slog.w(TAG, "Couldn't clear application caches");
2099                    }
2100                }
2101                if (observer != null) {
2102                    try {
2103                        observer.onRemoveCompleted(null, (retCode >= 0));
2104                    } catch (RemoteException e) {
2105                        Slog.w(TAG, "RemoveException when invoking call back");
2106                    }
2107                }
2108            }
2109        });
2110    }
2111
2112    @Override
2113    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2114        mContext.enforceCallingOrSelfPermission(
2115                android.Manifest.permission.CLEAR_APP_CACHE, null);
2116        // Queue up an async operation since clearing cache may take a little while.
2117        mHandler.post(new Runnable() {
2118            public void run() {
2119                mHandler.removeCallbacks(this);
2120                int retCode = -1;
2121                synchronized (mInstallLock) {
2122                    retCode = mInstaller.freeCache(freeStorageSize);
2123                    if (retCode < 0) {
2124                        Slog.w(TAG, "Couldn't clear application caches");
2125                    }
2126                }
2127                if(pi != null) {
2128                    try {
2129                        // Callback via pending intent
2130                        int code = (retCode >= 0) ? 1 : 0;
2131                        pi.sendIntent(null, code, null,
2132                                null, null);
2133                    } catch (SendIntentException e1) {
2134                        Slog.i(TAG, "Failed to send pending intent");
2135                    }
2136                }
2137            }
2138        });
2139    }
2140
2141    void freeStorage(long freeStorageSize) throws IOException {
2142        synchronized (mInstallLock) {
2143            if (mInstaller.freeCache(freeStorageSize) < 0) {
2144                throw new IOException("Failed to free enough space");
2145            }
2146        }
2147    }
2148
2149    @Override
2150    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2151        if (!sUserManager.exists(userId)) return null;
2152        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2153        synchronized (mPackages) {
2154            PackageParser.Activity a = mActivities.mActivities.get(component);
2155
2156            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2157            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2158                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2159                if (ps == null) return null;
2160                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2161                        userId);
2162            }
2163            if (mResolveComponentName.equals(component)) {
2164                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2165                        new PackageUserState(), userId);
2166            }
2167        }
2168        return null;
2169    }
2170
2171    @Override
2172    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2173            String resolvedType) {
2174        synchronized (mPackages) {
2175            PackageParser.Activity a = mActivities.mActivities.get(component);
2176            if (a == null) {
2177                return false;
2178            }
2179            for (int i=0; i<a.intents.size(); i++) {
2180                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2181                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2182                    return true;
2183                }
2184            }
2185            return false;
2186        }
2187    }
2188
2189    @Override
2190    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2191        if (!sUserManager.exists(userId)) return null;
2192        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2193        synchronized (mPackages) {
2194            PackageParser.Activity a = mReceivers.mActivities.get(component);
2195            if (DEBUG_PACKAGE_INFO) Log.v(
2196                TAG, "getReceiverInfo " + component + ": " + a);
2197            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2198                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2199                if (ps == null) return null;
2200                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2201                        userId);
2202            }
2203        }
2204        return null;
2205    }
2206
2207    @Override
2208    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2209        if (!sUserManager.exists(userId)) return null;
2210        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2211        synchronized (mPackages) {
2212            PackageParser.Service s = mServices.mServices.get(component);
2213            if (DEBUG_PACKAGE_INFO) Log.v(
2214                TAG, "getServiceInfo " + component + ": " + s);
2215            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2216                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2217                if (ps == null) return null;
2218                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2219                        userId);
2220            }
2221        }
2222        return null;
2223    }
2224
2225    @Override
2226    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2227        if (!sUserManager.exists(userId)) return null;
2228        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2229        synchronized (mPackages) {
2230            PackageParser.Provider p = mProviders.mProviders.get(component);
2231            if (DEBUG_PACKAGE_INFO) Log.v(
2232                TAG, "getProviderInfo " + component + ": " + p);
2233            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2234                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2235                if (ps == null) return null;
2236                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2237                        userId);
2238            }
2239        }
2240        return null;
2241    }
2242
2243    @Override
2244    public String[] getSystemSharedLibraryNames() {
2245        Set<String> libSet;
2246        synchronized (mPackages) {
2247            libSet = mSharedLibraries.keySet();
2248            int size = libSet.size();
2249            if (size > 0) {
2250                String[] libs = new String[size];
2251                libSet.toArray(libs);
2252                return libs;
2253            }
2254        }
2255        return null;
2256    }
2257
2258    @Override
2259    public FeatureInfo[] getSystemAvailableFeatures() {
2260        Collection<FeatureInfo> featSet;
2261        synchronized (mPackages) {
2262            featSet = mAvailableFeatures.values();
2263            int size = featSet.size();
2264            if (size > 0) {
2265                FeatureInfo[] features = new FeatureInfo[size+1];
2266                featSet.toArray(features);
2267                FeatureInfo fi = new FeatureInfo();
2268                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2269                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2270                features[size] = fi;
2271                return features;
2272            }
2273        }
2274        return null;
2275    }
2276
2277    @Override
2278    public boolean hasSystemFeature(String name) {
2279        synchronized (mPackages) {
2280            return mAvailableFeatures.containsKey(name);
2281        }
2282    }
2283
2284    private void checkValidCaller(int uid, int userId) {
2285        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2286            return;
2287
2288        throw new SecurityException("Caller uid=" + uid
2289                + " is not privileged to communicate with user=" + userId);
2290    }
2291
2292    @Override
2293    public int checkPermission(String permName, String pkgName) {
2294        synchronized (mPackages) {
2295            PackageParser.Package p = mPackages.get(pkgName);
2296            if (p != null && p.mExtras != null) {
2297                PackageSetting ps = (PackageSetting)p.mExtras;
2298                if (ps.sharedUser != null) {
2299                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2300                        return PackageManager.PERMISSION_GRANTED;
2301                    }
2302                } else if (ps.grantedPermissions.contains(permName)) {
2303                    return PackageManager.PERMISSION_GRANTED;
2304                }
2305            }
2306        }
2307        return PackageManager.PERMISSION_DENIED;
2308    }
2309
2310    @Override
2311    public int checkUidPermission(String permName, int uid) {
2312        synchronized (mPackages) {
2313            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2314            if (obj != null) {
2315                GrantedPermissions gp = (GrantedPermissions)obj;
2316                if (gp.grantedPermissions.contains(permName)) {
2317                    return PackageManager.PERMISSION_GRANTED;
2318                }
2319            } else {
2320                HashSet<String> perms = mSystemPermissions.get(uid);
2321                if (perms != null && perms.contains(permName)) {
2322                    return PackageManager.PERMISSION_GRANTED;
2323                }
2324            }
2325        }
2326        return PackageManager.PERMISSION_DENIED;
2327    }
2328
2329    /**
2330     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2331     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2332     * @param checkShell TODO(yamasani):
2333     * @param message the message to log on security exception
2334     */
2335    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2336            boolean checkShell, String message) {
2337        if (userId < 0) {
2338            throw new IllegalArgumentException("Invalid userId " + userId);
2339        }
2340        if (checkShell) {
2341            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2342        }
2343        if (userId == UserHandle.getUserId(callingUid)) return;
2344        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2345            if (requireFullPermission) {
2346                mContext.enforceCallingOrSelfPermission(
2347                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2348            } else {
2349                try {
2350                    mContext.enforceCallingOrSelfPermission(
2351                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2352                } catch (SecurityException se) {
2353                    mContext.enforceCallingOrSelfPermission(
2354                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2355                }
2356            }
2357        }
2358    }
2359
2360    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2361        if (callingUid == Process.SHELL_UID) {
2362            if (userHandle >= 0
2363                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2364                throw new SecurityException("Shell does not have permission to access user "
2365                        + userHandle);
2366            } else if (userHandle < 0) {
2367                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2368                        + Debug.getCallers(3));
2369            }
2370        }
2371    }
2372
2373    private BasePermission findPermissionTreeLP(String permName) {
2374        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2375            if (permName.startsWith(bp.name) &&
2376                    permName.length() > bp.name.length() &&
2377                    permName.charAt(bp.name.length()) == '.') {
2378                return bp;
2379            }
2380        }
2381        return null;
2382    }
2383
2384    private BasePermission checkPermissionTreeLP(String permName) {
2385        if (permName != null) {
2386            BasePermission bp = findPermissionTreeLP(permName);
2387            if (bp != null) {
2388                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2389                    return bp;
2390                }
2391                throw new SecurityException("Calling uid "
2392                        + Binder.getCallingUid()
2393                        + " is not allowed to add to permission tree "
2394                        + bp.name + " owned by uid " + bp.uid);
2395            }
2396        }
2397        throw new SecurityException("No permission tree found for " + permName);
2398    }
2399
2400    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2401        if (s1 == null) {
2402            return s2 == null;
2403        }
2404        if (s2 == null) {
2405            return false;
2406        }
2407        if (s1.getClass() != s2.getClass()) {
2408            return false;
2409        }
2410        return s1.equals(s2);
2411    }
2412
2413    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2414        if (pi1.icon != pi2.icon) return false;
2415        if (pi1.logo != pi2.logo) return false;
2416        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2417        if (!compareStrings(pi1.name, pi2.name)) return false;
2418        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2419        // We'll take care of setting this one.
2420        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2421        // These are not currently stored in settings.
2422        //if (!compareStrings(pi1.group, pi2.group)) return false;
2423        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2424        //if (pi1.labelRes != pi2.labelRes) return false;
2425        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2426        return true;
2427    }
2428
2429    int permissionInfoFootprint(PermissionInfo info) {
2430        int size = info.name.length();
2431        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2432        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2433        return size;
2434    }
2435
2436    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2437        int size = 0;
2438        for (BasePermission perm : mSettings.mPermissions.values()) {
2439            if (perm.uid == tree.uid) {
2440                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2441            }
2442        }
2443        return size;
2444    }
2445
2446    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2447        // We calculate the max size of permissions defined by this uid and throw
2448        // if that plus the size of 'info' would exceed our stated maximum.
2449        if (tree.uid != Process.SYSTEM_UID) {
2450            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2451            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2452                throw new SecurityException("Permission tree size cap exceeded");
2453            }
2454        }
2455    }
2456
2457    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2458        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2459            throw new SecurityException("Label must be specified in permission");
2460        }
2461        BasePermission tree = checkPermissionTreeLP(info.name);
2462        BasePermission bp = mSettings.mPermissions.get(info.name);
2463        boolean added = bp == null;
2464        boolean changed = true;
2465        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2466        if (added) {
2467            enforcePermissionCapLocked(info, tree);
2468            bp = new BasePermission(info.name, tree.sourcePackage,
2469                    BasePermission.TYPE_DYNAMIC);
2470        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2471            throw new SecurityException(
2472                    "Not allowed to modify non-dynamic permission "
2473                    + info.name);
2474        } else {
2475            if (bp.protectionLevel == fixedLevel
2476                    && bp.perm.owner.equals(tree.perm.owner)
2477                    && bp.uid == tree.uid
2478                    && comparePermissionInfos(bp.perm.info, info)) {
2479                changed = false;
2480            }
2481        }
2482        bp.protectionLevel = fixedLevel;
2483        info = new PermissionInfo(info);
2484        info.protectionLevel = fixedLevel;
2485        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2486        bp.perm.info.packageName = tree.perm.info.packageName;
2487        bp.uid = tree.uid;
2488        if (added) {
2489            mSettings.mPermissions.put(info.name, bp);
2490        }
2491        if (changed) {
2492            if (!async) {
2493                mSettings.writeLPr();
2494            } else {
2495                scheduleWriteSettingsLocked();
2496            }
2497        }
2498        return added;
2499    }
2500
2501    @Override
2502    public boolean addPermission(PermissionInfo info) {
2503        synchronized (mPackages) {
2504            return addPermissionLocked(info, false);
2505        }
2506    }
2507
2508    @Override
2509    public boolean addPermissionAsync(PermissionInfo info) {
2510        synchronized (mPackages) {
2511            return addPermissionLocked(info, true);
2512        }
2513    }
2514
2515    @Override
2516    public void removePermission(String name) {
2517        synchronized (mPackages) {
2518            checkPermissionTreeLP(name);
2519            BasePermission bp = mSettings.mPermissions.get(name);
2520            if (bp != null) {
2521                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2522                    throw new SecurityException(
2523                            "Not allowed to modify non-dynamic permission "
2524                            + name);
2525                }
2526                mSettings.mPermissions.remove(name);
2527                mSettings.writeLPr();
2528            }
2529        }
2530    }
2531
2532    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2533        int index = pkg.requestedPermissions.indexOf(bp.name);
2534        if (index == -1) {
2535            throw new SecurityException("Package " + pkg.packageName
2536                    + " has not requested permission " + bp.name);
2537        }
2538        boolean isNormal =
2539                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2540                        == PermissionInfo.PROTECTION_NORMAL);
2541        boolean isDangerous =
2542                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2543                        == PermissionInfo.PROTECTION_DANGEROUS);
2544        boolean isDevelopment =
2545                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2546
2547        if (!isNormal && !isDangerous && !isDevelopment) {
2548            throw new SecurityException("Permission " + bp.name
2549                    + " is not a changeable permission type");
2550        }
2551
2552        if (isNormal || isDangerous) {
2553            if (pkg.requestedPermissionsRequired.get(index)) {
2554                throw new SecurityException("Can't change " + bp.name
2555                        + ". It is required by the application");
2556            }
2557        }
2558    }
2559
2560    @Override
2561    public void grantPermission(String packageName, String permissionName) {
2562        mContext.enforceCallingOrSelfPermission(
2563                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2564        synchronized (mPackages) {
2565            final PackageParser.Package pkg = mPackages.get(packageName);
2566            if (pkg == null) {
2567                throw new IllegalArgumentException("Unknown package: " + packageName);
2568            }
2569            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2570            if (bp == null) {
2571                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2572            }
2573
2574            checkGrantRevokePermissions(pkg, bp);
2575
2576            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2577            if (ps == null) {
2578                return;
2579            }
2580            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2581            if (gp.grantedPermissions.add(permissionName)) {
2582                if (ps.haveGids) {
2583                    gp.gids = appendInts(gp.gids, bp.gids);
2584                }
2585                mSettings.writeLPr();
2586            }
2587        }
2588    }
2589
2590    @Override
2591    public void revokePermission(String packageName, String permissionName) {
2592        int changedAppId = -1;
2593
2594        synchronized (mPackages) {
2595            final PackageParser.Package pkg = mPackages.get(packageName);
2596            if (pkg == null) {
2597                throw new IllegalArgumentException("Unknown package: " + packageName);
2598            }
2599            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2600                mContext.enforceCallingOrSelfPermission(
2601                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2602            }
2603            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2604            if (bp == null) {
2605                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2606            }
2607
2608            checkGrantRevokePermissions(pkg, bp);
2609
2610            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2611            if (ps == null) {
2612                return;
2613            }
2614            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2615            if (gp.grantedPermissions.remove(permissionName)) {
2616                gp.grantedPermissions.remove(permissionName);
2617                if (ps.haveGids) {
2618                    gp.gids = removeInts(gp.gids, bp.gids);
2619                }
2620                mSettings.writeLPr();
2621                changedAppId = ps.appId;
2622            }
2623        }
2624
2625        if (changedAppId >= 0) {
2626            // We changed the perm on someone, kill its processes.
2627            IActivityManager am = ActivityManagerNative.getDefault();
2628            if (am != null) {
2629                final int callingUserId = UserHandle.getCallingUserId();
2630                final long ident = Binder.clearCallingIdentity();
2631                try {
2632                    //XXX we should only revoke for the calling user's app permissions,
2633                    // but for now we impact all users.
2634                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2635                    //        "revoke " + permissionName);
2636                    int[] users = sUserManager.getUserIds();
2637                    for (int user : users) {
2638                        am.killUid(UserHandle.getUid(user, changedAppId),
2639                                "revoke " + permissionName);
2640                    }
2641                } catch (RemoteException e) {
2642                } finally {
2643                    Binder.restoreCallingIdentity(ident);
2644                }
2645            }
2646        }
2647    }
2648
2649    @Override
2650    public boolean isProtectedBroadcast(String actionName) {
2651        synchronized (mPackages) {
2652            return mProtectedBroadcasts.contains(actionName);
2653        }
2654    }
2655
2656    @Override
2657    public int checkSignatures(String pkg1, String pkg2) {
2658        synchronized (mPackages) {
2659            final PackageParser.Package p1 = mPackages.get(pkg1);
2660            final PackageParser.Package p2 = mPackages.get(pkg2);
2661            if (p1 == null || p1.mExtras == null
2662                    || p2 == null || p2.mExtras == null) {
2663                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2664            }
2665            return compareSignatures(p1.mSignatures, p2.mSignatures);
2666        }
2667    }
2668
2669    @Override
2670    public int checkUidSignatures(int uid1, int uid2) {
2671        // Map to base uids.
2672        uid1 = UserHandle.getAppId(uid1);
2673        uid2 = UserHandle.getAppId(uid2);
2674        // reader
2675        synchronized (mPackages) {
2676            Signature[] s1;
2677            Signature[] s2;
2678            Object obj = mSettings.getUserIdLPr(uid1);
2679            if (obj != null) {
2680                if (obj instanceof SharedUserSetting) {
2681                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2682                } else if (obj instanceof PackageSetting) {
2683                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2684                } else {
2685                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2686                }
2687            } else {
2688                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2689            }
2690            obj = mSettings.getUserIdLPr(uid2);
2691            if (obj != null) {
2692                if (obj instanceof SharedUserSetting) {
2693                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2694                } else if (obj instanceof PackageSetting) {
2695                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2696                } else {
2697                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2698                }
2699            } else {
2700                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2701            }
2702            return compareSignatures(s1, s2);
2703        }
2704    }
2705
2706    /**
2707     * Compares two sets of signatures. Returns:
2708     * <br />
2709     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2710     * <br />
2711     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2712     * <br />
2713     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2714     * <br />
2715     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2716     * <br />
2717     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2718     */
2719    static int compareSignatures(Signature[] s1, Signature[] s2) {
2720        if (s1 == null) {
2721            return s2 == null
2722                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2723                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2724        }
2725
2726        if (s2 == null) {
2727            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2728        }
2729
2730        if (s1.length != s2.length) {
2731            return PackageManager.SIGNATURE_NO_MATCH;
2732        }
2733
2734        // Since both signature sets are of size 1, we can compare without HashSets.
2735        if (s1.length == 1) {
2736            return s1[0].equals(s2[0]) ?
2737                    PackageManager.SIGNATURE_MATCH :
2738                    PackageManager.SIGNATURE_NO_MATCH;
2739        }
2740
2741        HashSet<Signature> set1 = new HashSet<Signature>();
2742        for (Signature sig : s1) {
2743            set1.add(sig);
2744        }
2745        HashSet<Signature> set2 = new HashSet<Signature>();
2746        for (Signature sig : s2) {
2747            set2.add(sig);
2748        }
2749        // Make sure s2 contains all signatures in s1.
2750        if (set1.equals(set2)) {
2751            return PackageManager.SIGNATURE_MATCH;
2752        }
2753        return PackageManager.SIGNATURE_NO_MATCH;
2754    }
2755
2756    /**
2757     * If the database version for this type of package (internal storage or
2758     * external storage) is less than the version where package signatures
2759     * were updated, return true.
2760     */
2761    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2762        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2763                DatabaseVersion.SIGNATURE_END_ENTITY))
2764                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2765                        DatabaseVersion.SIGNATURE_END_ENTITY));
2766    }
2767
2768    /**
2769     * Used for backward compatibility to make sure any packages with
2770     * certificate chains get upgraded to the new style. {@code existingSigs}
2771     * will be in the old format (since they were stored on disk from before the
2772     * system upgrade) and {@code scannedSigs} will be in the newer format.
2773     */
2774    private int compareSignaturesCompat(PackageSignatures existingSigs,
2775            PackageParser.Package scannedPkg) {
2776        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2777            return PackageManager.SIGNATURE_NO_MATCH;
2778        }
2779
2780        HashSet<Signature> existingSet = new HashSet<Signature>();
2781        for (Signature sig : existingSigs.mSignatures) {
2782            existingSet.add(sig);
2783        }
2784        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2785        for (Signature sig : scannedPkg.mSignatures) {
2786            try {
2787                Signature[] chainSignatures = sig.getChainSignatures();
2788                for (Signature chainSig : chainSignatures) {
2789                    scannedCompatSet.add(chainSig);
2790                }
2791            } catch (CertificateEncodingException e) {
2792                scannedCompatSet.add(sig);
2793            }
2794        }
2795        /*
2796         * Make sure the expanded scanned set contains all signatures in the
2797         * existing one.
2798         */
2799        if (scannedCompatSet.equals(existingSet)) {
2800            // Migrate the old signatures to the new scheme.
2801            existingSigs.assignSignatures(scannedPkg.mSignatures);
2802            // The new KeySets will be re-added later in the scanning process.
2803            synchronized (mPackages) {
2804                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2805            }
2806            return PackageManager.SIGNATURE_MATCH;
2807        }
2808        return PackageManager.SIGNATURE_NO_MATCH;
2809    }
2810
2811    @Override
2812    public String[] getPackagesForUid(int uid) {
2813        uid = UserHandle.getAppId(uid);
2814        // reader
2815        synchronized (mPackages) {
2816            Object obj = mSettings.getUserIdLPr(uid);
2817            if (obj instanceof SharedUserSetting) {
2818                final SharedUserSetting sus = (SharedUserSetting) obj;
2819                final int N = sus.packages.size();
2820                final String[] res = new String[N];
2821                final Iterator<PackageSetting> it = sus.packages.iterator();
2822                int i = 0;
2823                while (it.hasNext()) {
2824                    res[i++] = it.next().name;
2825                }
2826                return res;
2827            } else if (obj instanceof PackageSetting) {
2828                final PackageSetting ps = (PackageSetting) obj;
2829                return new String[] { ps.name };
2830            }
2831        }
2832        return null;
2833    }
2834
2835    @Override
2836    public String getNameForUid(int uid) {
2837        // reader
2838        synchronized (mPackages) {
2839            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2840            if (obj instanceof SharedUserSetting) {
2841                final SharedUserSetting sus = (SharedUserSetting) obj;
2842                return sus.name + ":" + sus.userId;
2843            } else if (obj instanceof PackageSetting) {
2844                final PackageSetting ps = (PackageSetting) obj;
2845                return ps.name;
2846            }
2847        }
2848        return null;
2849    }
2850
2851    @Override
2852    public int getUidForSharedUser(String sharedUserName) {
2853        if(sharedUserName == null) {
2854            return -1;
2855        }
2856        // reader
2857        synchronized (mPackages) {
2858            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2859            if (suid == null) {
2860                return -1;
2861            }
2862            return suid.userId;
2863        }
2864    }
2865
2866    @Override
2867    public int getFlagsForUid(int uid) {
2868        synchronized (mPackages) {
2869            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2870            if (obj instanceof SharedUserSetting) {
2871                final SharedUserSetting sus = (SharedUserSetting) obj;
2872                return sus.pkgFlags;
2873            } else if (obj instanceof PackageSetting) {
2874                final PackageSetting ps = (PackageSetting) obj;
2875                return ps.pkgFlags;
2876            }
2877        }
2878        return 0;
2879    }
2880
2881    @Override
2882    public String[] getAppOpPermissionPackages(String permissionName) {
2883        synchronized (mPackages) {
2884            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2885            if (pkgs == null) {
2886                return null;
2887            }
2888            return pkgs.toArray(new String[pkgs.size()]);
2889        }
2890    }
2891
2892    @Override
2893    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2894            int flags, int userId) {
2895        if (!sUserManager.exists(userId)) return null;
2896        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2897        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2898        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2899    }
2900
2901    @Override
2902    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2903            IntentFilter filter, int match, ComponentName activity) {
2904        final int userId = UserHandle.getCallingUserId();
2905        if (DEBUG_PREFERRED) {
2906            Log.v(TAG, "setLastChosenActivity intent=" + intent
2907                + " resolvedType=" + resolvedType
2908                + " flags=" + flags
2909                + " filter=" + filter
2910                + " match=" + match
2911                + " activity=" + activity);
2912            filter.dump(new PrintStreamPrinter(System.out), "    ");
2913        }
2914        intent.setComponent(null);
2915        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2916        // Find any earlier preferred or last chosen entries and nuke them
2917        findPreferredActivity(intent, resolvedType,
2918                flags, query, 0, false, true, false, userId);
2919        // Add the new activity as the last chosen for this filter
2920        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2921                "Setting last chosen");
2922    }
2923
2924    @Override
2925    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2926        final int userId = UserHandle.getCallingUserId();
2927        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2928        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2929        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2930                false, false, false, userId);
2931    }
2932
2933    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2934            int flags, List<ResolveInfo> query, int userId) {
2935        if (query != null) {
2936            final int N = query.size();
2937            if (N == 1) {
2938                return query.get(0);
2939            } else if (N > 1) {
2940                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2941                // If there is more than one activity with the same priority,
2942                // then let the user decide between them.
2943                ResolveInfo r0 = query.get(0);
2944                ResolveInfo r1 = query.get(1);
2945                if (DEBUG_INTENT_MATCHING || debug) {
2946                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2947                            + r1.activityInfo.name + "=" + r1.priority);
2948                }
2949                // If the first activity has a higher priority, or a different
2950                // default, then it is always desireable to pick it.
2951                if (r0.priority != r1.priority
2952                        || r0.preferredOrder != r1.preferredOrder
2953                        || r0.isDefault != r1.isDefault) {
2954                    return query.get(0);
2955                }
2956                // If we have saved a preference for a preferred activity for
2957                // this Intent, use that.
2958                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2959                        flags, query, r0.priority, true, false, debug, userId);
2960                if (ri != null) {
2961                    return ri;
2962                }
2963                if (userId != 0) {
2964                    ri = new ResolveInfo(mResolveInfo);
2965                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2966                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2967                            ri.activityInfo.applicationInfo);
2968                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2969                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2970                    return ri;
2971                }
2972                return mResolveInfo;
2973            }
2974        }
2975        return null;
2976    }
2977
2978    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2979            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2980        final int N = query.size();
2981        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2982                .get(userId);
2983        // Get the list of persistent preferred activities that handle the intent
2984        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2985        List<PersistentPreferredActivity> pprefs = ppir != null
2986                ? ppir.queryIntent(intent, resolvedType,
2987                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2988                : null;
2989        if (pprefs != null && pprefs.size() > 0) {
2990            final int M = pprefs.size();
2991            for (int i=0; i<M; i++) {
2992                final PersistentPreferredActivity ppa = pprefs.get(i);
2993                if (DEBUG_PREFERRED || debug) {
2994                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2995                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2996                            + "\n  component=" + ppa.mComponent);
2997                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2998                }
2999                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3000                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3001                if (DEBUG_PREFERRED || debug) {
3002                    Slog.v(TAG, "Found persistent preferred activity:");
3003                    if (ai != null) {
3004                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3005                    } else {
3006                        Slog.v(TAG, "  null");
3007                    }
3008                }
3009                if (ai == null) {
3010                    // This previously registered persistent preferred activity
3011                    // component is no longer known. Ignore it and do NOT remove it.
3012                    continue;
3013                }
3014                for (int j=0; j<N; j++) {
3015                    final ResolveInfo ri = query.get(j);
3016                    if (!ri.activityInfo.applicationInfo.packageName
3017                            .equals(ai.applicationInfo.packageName)) {
3018                        continue;
3019                    }
3020                    if (!ri.activityInfo.name.equals(ai.name)) {
3021                        continue;
3022                    }
3023                    //  Found a persistent preference that can handle the intent.
3024                    if (DEBUG_PREFERRED || debug) {
3025                        Slog.v(TAG, "Returning persistent preferred activity: " +
3026                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3027                    }
3028                    return ri;
3029                }
3030            }
3031        }
3032        return null;
3033    }
3034
3035    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3036            List<ResolveInfo> query, int priority, boolean always,
3037            boolean removeMatches, boolean debug, int userId) {
3038        if (!sUserManager.exists(userId)) return null;
3039        // writer
3040        synchronized (mPackages) {
3041            if (intent.getSelector() != null) {
3042                intent = intent.getSelector();
3043            }
3044            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3045
3046            // Try to find a matching persistent preferred activity.
3047            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3048                    debug, userId);
3049
3050            // If a persistent preferred activity matched, use it.
3051            if (pri != null) {
3052                return pri;
3053            }
3054
3055            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3056            // Get the list of preferred activities that handle the intent
3057            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3058            List<PreferredActivity> prefs = pir != null
3059                    ? pir.queryIntent(intent, resolvedType,
3060                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3061                    : null;
3062            if (prefs != null && prefs.size() > 0) {
3063                boolean changed = false;
3064                try {
3065                    // First figure out how good the original match set is.
3066                    // We will only allow preferred activities that came
3067                    // from the same match quality.
3068                    int match = 0;
3069
3070                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3071
3072                    final int N = query.size();
3073                    for (int j=0; j<N; j++) {
3074                        final ResolveInfo ri = query.get(j);
3075                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3076                                + ": 0x" + Integer.toHexString(match));
3077                        if (ri.match > match) {
3078                            match = ri.match;
3079                        }
3080                    }
3081
3082                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3083                            + Integer.toHexString(match));
3084
3085                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3086                    final int M = prefs.size();
3087                    for (int i=0; i<M; i++) {
3088                        final PreferredActivity pa = prefs.get(i);
3089                        if (DEBUG_PREFERRED || debug) {
3090                            Slog.v(TAG, "Checking PreferredActivity ds="
3091                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3092                                    + "\n  component=" + pa.mPref.mComponent);
3093                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3094                        }
3095                        if (pa.mPref.mMatch != match) {
3096                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3097                                    + Integer.toHexString(pa.mPref.mMatch));
3098                            continue;
3099                        }
3100                        // If it's not an "always" type preferred activity and that's what we're
3101                        // looking for, skip it.
3102                        if (always && !pa.mPref.mAlways) {
3103                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3104                            continue;
3105                        }
3106                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3107                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3108                        if (DEBUG_PREFERRED || debug) {
3109                            Slog.v(TAG, "Found preferred activity:");
3110                            if (ai != null) {
3111                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3112                            } else {
3113                                Slog.v(TAG, "  null");
3114                            }
3115                        }
3116                        if (ai == null) {
3117                            // This previously registered preferred activity
3118                            // component is no longer known.  Most likely an update
3119                            // to the app was installed and in the new version this
3120                            // component no longer exists.  Clean it up by removing
3121                            // it from the preferred activities list, and skip it.
3122                            Slog.w(TAG, "Removing dangling preferred activity: "
3123                                    + pa.mPref.mComponent);
3124                            pir.removeFilter(pa);
3125                            changed = true;
3126                            continue;
3127                        }
3128                        for (int j=0; j<N; j++) {
3129                            final ResolveInfo ri = query.get(j);
3130                            if (!ri.activityInfo.applicationInfo.packageName
3131                                    .equals(ai.applicationInfo.packageName)) {
3132                                continue;
3133                            }
3134                            if (!ri.activityInfo.name.equals(ai.name)) {
3135                                continue;
3136                            }
3137
3138                            if (removeMatches) {
3139                                pir.removeFilter(pa);
3140                                changed = true;
3141                                if (DEBUG_PREFERRED) {
3142                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3143                                }
3144                                break;
3145                            }
3146
3147                            // Okay we found a previously set preferred or last chosen app.
3148                            // If the result set is different from when this
3149                            // was created, we need to clear it and re-ask the
3150                            // user their preference, if we're looking for an "always" type entry.
3151                            if (always && !pa.mPref.sameSet(query, priority)) {
3152                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3153                                        + intent + " type " + resolvedType);
3154                                if (DEBUG_PREFERRED) {
3155                                    Slog.v(TAG, "Removing preferred activity since set changed "
3156                                            + pa.mPref.mComponent);
3157                                }
3158                                pir.removeFilter(pa);
3159                                // Re-add the filter as a "last chosen" entry (!always)
3160                                PreferredActivity lastChosen = new PreferredActivity(
3161                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3162                                pir.addFilter(lastChosen);
3163                                changed = true;
3164                                return null;
3165                            }
3166
3167                            // Yay! Either the set matched or we're looking for the last chosen
3168                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3169                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3170                            return ri;
3171                        }
3172                    }
3173                } finally {
3174                    if (changed) {
3175                        if (DEBUG_PREFERRED) {
3176                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3177                        }
3178                        mSettings.writePackageRestrictionsLPr(userId);
3179                    }
3180                }
3181            }
3182        }
3183        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3184        return null;
3185    }
3186
3187    /*
3188     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3189     */
3190    @Override
3191    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3192            int targetUserId) {
3193        mContext.enforceCallingOrSelfPermission(
3194                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3195        List<CrossProfileIntentFilter> matches =
3196                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3197        if (matches != null) {
3198            int size = matches.size();
3199            for (int i = 0; i < size; i++) {
3200                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3201            }
3202        }
3203        return false;
3204    }
3205
3206    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3207            String resolvedType, int userId) {
3208        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3209        if (resolver != null) {
3210            return resolver.queryIntent(intent, resolvedType, false, userId);
3211        }
3212        return null;
3213    }
3214
3215    @Override
3216    public List<ResolveInfo> queryIntentActivities(Intent intent,
3217            String resolvedType, int flags, int userId) {
3218        if (!sUserManager.exists(userId)) return Collections.emptyList();
3219        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3220        ComponentName comp = intent.getComponent();
3221        if (comp == null) {
3222            if (intent.getSelector() != null) {
3223                intent = intent.getSelector();
3224                comp = intent.getComponent();
3225            }
3226        }
3227
3228        if (comp != null) {
3229            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3230            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3231            if (ai != null) {
3232                final ResolveInfo ri = new ResolveInfo();
3233                ri.activityInfo = ai;
3234                list.add(ri);
3235            }
3236            return list;
3237        }
3238
3239        // reader
3240        synchronized (mPackages) {
3241            final String pkgName = intent.getPackage();
3242            if (pkgName == null) {
3243                List<CrossProfileIntentFilter> matchingFilters =
3244                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3245                // Check for results that need to skip the current profile.
3246                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3247                        resolvedType, flags, userId);
3248                if (resolveInfo != null) {
3249                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3250                    result.add(resolveInfo);
3251                    return result;
3252                }
3253                // Check for cross profile results.
3254                resolveInfo = queryCrossProfileIntents(
3255                        matchingFilters, intent, resolvedType, flags, userId);
3256
3257                // Check for results in the current profile.
3258                List<ResolveInfo> result = mActivities.queryIntent(
3259                        intent, resolvedType, flags, userId);
3260                if (resolveInfo != null) {
3261                    result.add(resolveInfo);
3262                    Collections.sort(result, mResolvePrioritySorter);
3263                }
3264                return result;
3265            }
3266            final PackageParser.Package pkg = mPackages.get(pkgName);
3267            if (pkg != null) {
3268                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3269                        pkg.activities, userId);
3270            }
3271            return new ArrayList<ResolveInfo>();
3272        }
3273    }
3274
3275    private ResolveInfo querySkipCurrentProfileIntents(
3276            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3277            int flags, int sourceUserId) {
3278        if (matchingFilters != null) {
3279            int size = matchingFilters.size();
3280            for (int i = 0; i < size; i ++) {
3281                CrossProfileIntentFilter filter = matchingFilters.get(i);
3282                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3283                    // Checking if there are activities in the target user that can handle the
3284                    // intent.
3285                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3286                            flags, sourceUserId);
3287                    if (resolveInfo != null) {
3288                        return resolveInfo;
3289                    }
3290                }
3291            }
3292        }
3293        return null;
3294    }
3295
3296    // Return matching ResolveInfo if any for skip current profile intent filters.
3297    private ResolveInfo queryCrossProfileIntents(
3298            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3299            int flags, int sourceUserId) {
3300        if (matchingFilters != null) {
3301            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3302            // match the same intent. For performance reasons, it is better not to
3303            // run queryIntent twice for the same userId
3304            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3305            int size = matchingFilters.size();
3306            for (int i = 0; i < size; i++) {
3307                CrossProfileIntentFilter filter = matchingFilters.get(i);
3308                int targetUserId = filter.getTargetUserId();
3309                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3310                        && !alreadyTriedUserIds.get(targetUserId)) {
3311                    // Checking if there are activities in the target user that can handle the
3312                    // intent.
3313                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3314                            flags, sourceUserId);
3315                    if (resolveInfo != null) return resolveInfo;
3316                    alreadyTriedUserIds.put(targetUserId, true);
3317                }
3318            }
3319        }
3320        return null;
3321    }
3322
3323    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3324            String resolvedType, int flags, int sourceUserId) {
3325        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3326                resolvedType, flags, filter.getTargetUserId());
3327        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3328            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3329        }
3330        return null;
3331    }
3332
3333    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3334            int sourceUserId, int targetUserId) {
3335        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3336        String className;
3337        if (targetUserId == UserHandle.USER_OWNER) {
3338            className = FORWARD_INTENT_TO_USER_OWNER;
3339        } else {
3340            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3341        }
3342        ComponentName forwardingActivityComponentName = new ComponentName(
3343                mAndroidApplication.packageName, className);
3344        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3345                sourceUserId);
3346        if (targetUserId == UserHandle.USER_OWNER) {
3347            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3348            forwardingResolveInfo.noResourceId = true;
3349        }
3350        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3351        forwardingResolveInfo.priority = 0;
3352        forwardingResolveInfo.preferredOrder = 0;
3353        forwardingResolveInfo.match = 0;
3354        forwardingResolveInfo.isDefault = true;
3355        forwardingResolveInfo.filter = filter;
3356        forwardingResolveInfo.targetUserId = targetUserId;
3357        return forwardingResolveInfo;
3358    }
3359
3360    @Override
3361    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3362            Intent[] specifics, String[] specificTypes, Intent intent,
3363            String resolvedType, int flags, int userId) {
3364        if (!sUserManager.exists(userId)) return Collections.emptyList();
3365        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3366                false, "query intent activity options");
3367        final String resultsAction = intent.getAction();
3368
3369        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3370                | PackageManager.GET_RESOLVED_FILTER, userId);
3371
3372        if (DEBUG_INTENT_MATCHING) {
3373            Log.v(TAG, "Query " + intent + ": " + results);
3374        }
3375
3376        int specificsPos = 0;
3377        int N;
3378
3379        // todo: note that the algorithm used here is O(N^2).  This
3380        // isn't a problem in our current environment, but if we start running
3381        // into situations where we have more than 5 or 10 matches then this
3382        // should probably be changed to something smarter...
3383
3384        // First we go through and resolve each of the specific items
3385        // that were supplied, taking care of removing any corresponding
3386        // duplicate items in the generic resolve list.
3387        if (specifics != null) {
3388            for (int i=0; i<specifics.length; i++) {
3389                final Intent sintent = specifics[i];
3390                if (sintent == null) {
3391                    continue;
3392                }
3393
3394                if (DEBUG_INTENT_MATCHING) {
3395                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3396                }
3397
3398                String action = sintent.getAction();
3399                if (resultsAction != null && resultsAction.equals(action)) {
3400                    // If this action was explicitly requested, then don't
3401                    // remove things that have it.
3402                    action = null;
3403                }
3404
3405                ResolveInfo ri = null;
3406                ActivityInfo ai = null;
3407
3408                ComponentName comp = sintent.getComponent();
3409                if (comp == null) {
3410                    ri = resolveIntent(
3411                        sintent,
3412                        specificTypes != null ? specificTypes[i] : null,
3413                            flags, userId);
3414                    if (ri == null) {
3415                        continue;
3416                    }
3417                    if (ri == mResolveInfo) {
3418                        // ACK!  Must do something better with this.
3419                    }
3420                    ai = ri.activityInfo;
3421                    comp = new ComponentName(ai.applicationInfo.packageName,
3422                            ai.name);
3423                } else {
3424                    ai = getActivityInfo(comp, flags, userId);
3425                    if (ai == null) {
3426                        continue;
3427                    }
3428                }
3429
3430                // Look for any generic query activities that are duplicates
3431                // of this specific one, and remove them from the results.
3432                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3433                N = results.size();
3434                int j;
3435                for (j=specificsPos; j<N; j++) {
3436                    ResolveInfo sri = results.get(j);
3437                    if ((sri.activityInfo.name.equals(comp.getClassName())
3438                            && sri.activityInfo.applicationInfo.packageName.equals(
3439                                    comp.getPackageName()))
3440                        || (action != null && sri.filter.matchAction(action))) {
3441                        results.remove(j);
3442                        if (DEBUG_INTENT_MATCHING) Log.v(
3443                            TAG, "Removing duplicate item from " + j
3444                            + " due to specific " + specificsPos);
3445                        if (ri == null) {
3446                            ri = sri;
3447                        }
3448                        j--;
3449                        N--;
3450                    }
3451                }
3452
3453                // Add this specific item to its proper place.
3454                if (ri == null) {
3455                    ri = new ResolveInfo();
3456                    ri.activityInfo = ai;
3457                }
3458                results.add(specificsPos, ri);
3459                ri.specificIndex = i;
3460                specificsPos++;
3461            }
3462        }
3463
3464        // Now we go through the remaining generic results and remove any
3465        // duplicate actions that are found here.
3466        N = results.size();
3467        for (int i=specificsPos; i<N-1; i++) {
3468            final ResolveInfo rii = results.get(i);
3469            if (rii.filter == null) {
3470                continue;
3471            }
3472
3473            // Iterate over all of the actions of this result's intent
3474            // filter...  typically this should be just one.
3475            final Iterator<String> it = rii.filter.actionsIterator();
3476            if (it == null) {
3477                continue;
3478            }
3479            while (it.hasNext()) {
3480                final String action = it.next();
3481                if (resultsAction != null && resultsAction.equals(action)) {
3482                    // If this action was explicitly requested, then don't
3483                    // remove things that have it.
3484                    continue;
3485                }
3486                for (int j=i+1; j<N; j++) {
3487                    final ResolveInfo rij = results.get(j);
3488                    if (rij.filter != null && rij.filter.hasAction(action)) {
3489                        results.remove(j);
3490                        if (DEBUG_INTENT_MATCHING) Log.v(
3491                            TAG, "Removing duplicate item from " + j
3492                            + " due to action " + action + " at " + i);
3493                        j--;
3494                        N--;
3495                    }
3496                }
3497            }
3498
3499            // If the caller didn't request filter information, drop it now
3500            // so we don't have to marshall/unmarshall it.
3501            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3502                rii.filter = null;
3503            }
3504        }
3505
3506        // Filter out the caller activity if so requested.
3507        if (caller != null) {
3508            N = results.size();
3509            for (int i=0; i<N; i++) {
3510                ActivityInfo ainfo = results.get(i).activityInfo;
3511                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3512                        && caller.getClassName().equals(ainfo.name)) {
3513                    results.remove(i);
3514                    break;
3515                }
3516            }
3517        }
3518
3519        // If the caller didn't request filter information,
3520        // drop them now so we don't have to
3521        // marshall/unmarshall it.
3522        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3523            N = results.size();
3524            for (int i=0; i<N; i++) {
3525                results.get(i).filter = null;
3526            }
3527        }
3528
3529        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3530        return results;
3531    }
3532
3533    @Override
3534    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3535            int userId) {
3536        if (!sUserManager.exists(userId)) return Collections.emptyList();
3537        ComponentName comp = intent.getComponent();
3538        if (comp == null) {
3539            if (intent.getSelector() != null) {
3540                intent = intent.getSelector();
3541                comp = intent.getComponent();
3542            }
3543        }
3544        if (comp != null) {
3545            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3546            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3547            if (ai != null) {
3548                ResolveInfo ri = new ResolveInfo();
3549                ri.activityInfo = ai;
3550                list.add(ri);
3551            }
3552            return list;
3553        }
3554
3555        // reader
3556        synchronized (mPackages) {
3557            String pkgName = intent.getPackage();
3558            if (pkgName == null) {
3559                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3560            }
3561            final PackageParser.Package pkg = mPackages.get(pkgName);
3562            if (pkg != null) {
3563                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3564                        userId);
3565            }
3566            return null;
3567        }
3568    }
3569
3570    @Override
3571    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3572        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3573        if (!sUserManager.exists(userId)) return null;
3574        if (query != null) {
3575            if (query.size() >= 1) {
3576                // If there is more than one service with the same priority,
3577                // just arbitrarily pick the first one.
3578                return query.get(0);
3579            }
3580        }
3581        return null;
3582    }
3583
3584    @Override
3585    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3586            int userId) {
3587        if (!sUserManager.exists(userId)) return Collections.emptyList();
3588        ComponentName comp = intent.getComponent();
3589        if (comp == null) {
3590            if (intent.getSelector() != null) {
3591                intent = intent.getSelector();
3592                comp = intent.getComponent();
3593            }
3594        }
3595        if (comp != null) {
3596            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3597            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3598            if (si != null) {
3599                final ResolveInfo ri = new ResolveInfo();
3600                ri.serviceInfo = si;
3601                list.add(ri);
3602            }
3603            return list;
3604        }
3605
3606        // reader
3607        synchronized (mPackages) {
3608            String pkgName = intent.getPackage();
3609            if (pkgName == null) {
3610                return mServices.queryIntent(intent, resolvedType, flags, userId);
3611            }
3612            final PackageParser.Package pkg = mPackages.get(pkgName);
3613            if (pkg != null) {
3614                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3615                        userId);
3616            }
3617            return null;
3618        }
3619    }
3620
3621    @Override
3622    public List<ResolveInfo> queryIntentContentProviders(
3623            Intent intent, String resolvedType, int flags, int userId) {
3624        if (!sUserManager.exists(userId)) return Collections.emptyList();
3625        ComponentName comp = intent.getComponent();
3626        if (comp == null) {
3627            if (intent.getSelector() != null) {
3628                intent = intent.getSelector();
3629                comp = intent.getComponent();
3630            }
3631        }
3632        if (comp != null) {
3633            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3634            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3635            if (pi != null) {
3636                final ResolveInfo ri = new ResolveInfo();
3637                ri.providerInfo = pi;
3638                list.add(ri);
3639            }
3640            return list;
3641        }
3642
3643        // reader
3644        synchronized (mPackages) {
3645            String pkgName = intent.getPackage();
3646            if (pkgName == null) {
3647                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3648            }
3649            final PackageParser.Package pkg = mPackages.get(pkgName);
3650            if (pkg != null) {
3651                return mProviders.queryIntentForPackage(
3652                        intent, resolvedType, flags, pkg.providers, userId);
3653            }
3654            return null;
3655        }
3656    }
3657
3658    @Override
3659    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3660        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3661
3662        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3663
3664        // writer
3665        synchronized (mPackages) {
3666            ArrayList<PackageInfo> list;
3667            if (listUninstalled) {
3668                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3669                for (PackageSetting ps : mSettings.mPackages.values()) {
3670                    PackageInfo pi;
3671                    if (ps.pkg != null) {
3672                        pi = generatePackageInfo(ps.pkg, flags, userId);
3673                    } else {
3674                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3675                    }
3676                    if (pi != null) {
3677                        list.add(pi);
3678                    }
3679                }
3680            } else {
3681                list = new ArrayList<PackageInfo>(mPackages.size());
3682                for (PackageParser.Package p : mPackages.values()) {
3683                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3684                    if (pi != null) {
3685                        list.add(pi);
3686                    }
3687                }
3688            }
3689
3690            return new ParceledListSlice<PackageInfo>(list);
3691        }
3692    }
3693
3694    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3695            String[] permissions, boolean[] tmp, int flags, int userId) {
3696        int numMatch = 0;
3697        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3698        for (int i=0; i<permissions.length; i++) {
3699            if (gp.grantedPermissions.contains(permissions[i])) {
3700                tmp[i] = true;
3701                numMatch++;
3702            } else {
3703                tmp[i] = false;
3704            }
3705        }
3706        if (numMatch == 0) {
3707            return;
3708        }
3709        PackageInfo pi;
3710        if (ps.pkg != null) {
3711            pi = generatePackageInfo(ps.pkg, flags, userId);
3712        } else {
3713            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3714        }
3715        // The above might return null in cases of uninstalled apps or install-state
3716        // skew across users/profiles.
3717        if (pi != null) {
3718            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3719                if (numMatch == permissions.length) {
3720                    pi.requestedPermissions = permissions;
3721                } else {
3722                    pi.requestedPermissions = new String[numMatch];
3723                    numMatch = 0;
3724                    for (int i=0; i<permissions.length; i++) {
3725                        if (tmp[i]) {
3726                            pi.requestedPermissions[numMatch] = permissions[i];
3727                            numMatch++;
3728                        }
3729                    }
3730                }
3731            }
3732            list.add(pi);
3733        }
3734    }
3735
3736    @Override
3737    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3738            String[] permissions, int flags, int userId) {
3739        if (!sUserManager.exists(userId)) return null;
3740        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3741
3742        // writer
3743        synchronized (mPackages) {
3744            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3745            boolean[] tmpBools = new boolean[permissions.length];
3746            if (listUninstalled) {
3747                for (PackageSetting ps : mSettings.mPackages.values()) {
3748                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3749                }
3750            } else {
3751                for (PackageParser.Package pkg : mPackages.values()) {
3752                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3753                    if (ps != null) {
3754                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3755                                userId);
3756                    }
3757                }
3758            }
3759
3760            return new ParceledListSlice<PackageInfo>(list);
3761        }
3762    }
3763
3764    @Override
3765    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3766        if (!sUserManager.exists(userId)) return null;
3767        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3768
3769        // writer
3770        synchronized (mPackages) {
3771            ArrayList<ApplicationInfo> list;
3772            if (listUninstalled) {
3773                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3774                for (PackageSetting ps : mSettings.mPackages.values()) {
3775                    ApplicationInfo ai;
3776                    if (ps.pkg != null) {
3777                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3778                                ps.readUserState(userId), userId);
3779                    } else {
3780                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3781                    }
3782                    if (ai != null) {
3783                        list.add(ai);
3784                    }
3785                }
3786            } else {
3787                list = new ArrayList<ApplicationInfo>(mPackages.size());
3788                for (PackageParser.Package p : mPackages.values()) {
3789                    if (p.mExtras != null) {
3790                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3791                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3792                        if (ai != null) {
3793                            list.add(ai);
3794                        }
3795                    }
3796                }
3797            }
3798
3799            return new ParceledListSlice<ApplicationInfo>(list);
3800        }
3801    }
3802
3803    public List<ApplicationInfo> getPersistentApplications(int flags) {
3804        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3805
3806        // reader
3807        synchronized (mPackages) {
3808            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3809            final int userId = UserHandle.getCallingUserId();
3810            while (i.hasNext()) {
3811                final PackageParser.Package p = i.next();
3812                if (p.applicationInfo != null
3813                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3814                        && (!mSafeMode || isSystemApp(p))) {
3815                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3816                    if (ps != null) {
3817                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3818                                ps.readUserState(userId), userId);
3819                        if (ai != null) {
3820                            finalList.add(ai);
3821                        }
3822                    }
3823                }
3824            }
3825        }
3826
3827        return finalList;
3828    }
3829
3830    @Override
3831    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3832        if (!sUserManager.exists(userId)) return null;
3833        // reader
3834        synchronized (mPackages) {
3835            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3836            PackageSetting ps = provider != null
3837                    ? mSettings.mPackages.get(provider.owner.packageName)
3838                    : null;
3839            return ps != null
3840                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3841                    && (!mSafeMode || (provider.info.applicationInfo.flags
3842                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3843                    ? PackageParser.generateProviderInfo(provider, flags,
3844                            ps.readUserState(userId), userId)
3845                    : null;
3846        }
3847    }
3848
3849    /**
3850     * @deprecated
3851     */
3852    @Deprecated
3853    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3854        // reader
3855        synchronized (mPackages) {
3856            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3857                    .entrySet().iterator();
3858            final int userId = UserHandle.getCallingUserId();
3859            while (i.hasNext()) {
3860                Map.Entry<String, PackageParser.Provider> entry = i.next();
3861                PackageParser.Provider p = entry.getValue();
3862                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3863
3864                if (ps != null && p.syncable
3865                        && (!mSafeMode || (p.info.applicationInfo.flags
3866                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3867                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3868                            ps.readUserState(userId), userId);
3869                    if (info != null) {
3870                        outNames.add(entry.getKey());
3871                        outInfo.add(info);
3872                    }
3873                }
3874            }
3875        }
3876    }
3877
3878    @Override
3879    public List<ProviderInfo> queryContentProviders(String processName,
3880            int uid, int flags) {
3881        ArrayList<ProviderInfo> finalList = null;
3882        // reader
3883        synchronized (mPackages) {
3884            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3885            final int userId = processName != null ?
3886                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3887            while (i.hasNext()) {
3888                final PackageParser.Provider p = i.next();
3889                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3890                if (ps != null && p.info.authority != null
3891                        && (processName == null
3892                                || (p.info.processName.equals(processName)
3893                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3894                        && mSettings.isEnabledLPr(p.info, flags, userId)
3895                        && (!mSafeMode
3896                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3897                    if (finalList == null) {
3898                        finalList = new ArrayList<ProviderInfo>(3);
3899                    }
3900                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3901                            ps.readUserState(userId), userId);
3902                    if (info != null) {
3903                        finalList.add(info);
3904                    }
3905                }
3906            }
3907        }
3908
3909        if (finalList != null) {
3910            Collections.sort(finalList, mProviderInitOrderSorter);
3911        }
3912
3913        return finalList;
3914    }
3915
3916    @Override
3917    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3918            int flags) {
3919        // reader
3920        synchronized (mPackages) {
3921            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3922            return PackageParser.generateInstrumentationInfo(i, flags);
3923        }
3924    }
3925
3926    @Override
3927    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3928            int flags) {
3929        ArrayList<InstrumentationInfo> finalList =
3930            new ArrayList<InstrumentationInfo>();
3931
3932        // reader
3933        synchronized (mPackages) {
3934            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3935            while (i.hasNext()) {
3936                final PackageParser.Instrumentation p = i.next();
3937                if (targetPackage == null
3938                        || targetPackage.equals(p.info.targetPackage)) {
3939                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3940                            flags);
3941                    if (ii != null) {
3942                        finalList.add(ii);
3943                    }
3944                }
3945            }
3946        }
3947
3948        return finalList;
3949    }
3950
3951    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3952        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3953        if (overlays == null) {
3954            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3955            return;
3956        }
3957        for (PackageParser.Package opkg : overlays.values()) {
3958            // Not much to do if idmap fails: we already logged the error
3959            // and we certainly don't want to abort installation of pkg simply
3960            // because an overlay didn't fit properly. For these reasons,
3961            // ignore the return value of createIdmapForPackagePairLI.
3962            createIdmapForPackagePairLI(pkg, opkg);
3963        }
3964    }
3965
3966    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3967            PackageParser.Package opkg) {
3968        if (!opkg.mTrustedOverlay) {
3969            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
3970                    opkg.baseCodePath + ": overlay not trusted");
3971            return false;
3972        }
3973        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3974        if (overlaySet == null) {
3975            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
3976                    opkg.baseCodePath + " but target package has no known overlays");
3977            return false;
3978        }
3979        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3980        // TODO: generate idmap for split APKs
3981        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
3982            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
3983                    + opkg.baseCodePath);
3984            return false;
3985        }
3986        PackageParser.Package[] overlayArray =
3987            overlaySet.values().toArray(new PackageParser.Package[0]);
3988        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3989            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3990                return p1.mOverlayPriority - p2.mOverlayPriority;
3991            }
3992        };
3993        Arrays.sort(overlayArray, cmp);
3994
3995        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3996        int i = 0;
3997        for (PackageParser.Package p : overlayArray) {
3998            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
3999        }
4000        return true;
4001    }
4002
4003    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4004        final File[] files = dir.listFiles();
4005        if (ArrayUtils.isEmpty(files)) {
4006            Log.d(TAG, "No files in app dir " + dir);
4007            return;
4008        }
4009
4010        if (DEBUG_PACKAGE_SCANNING) {
4011            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4012                    + " flags=0x" + Integer.toHexString(parseFlags));
4013        }
4014
4015        for (File file : files) {
4016            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4017                    && !PackageInstallerService.isStageName(file.getName());
4018            if (!isPackage) {
4019                // Ignore entries which are not packages
4020                continue;
4021            }
4022            try {
4023                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4024                        scanFlags, currentTime, null);
4025            } catch (PackageManagerException e) {
4026                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4027
4028                // Delete invalid userdata apps
4029                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4030                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4031                    Slog.w(TAG, "Deleting invalid package at " + file);
4032                    if (file.isDirectory()) {
4033                        FileUtils.deleteContents(file);
4034                    }
4035                    file.delete();
4036                }
4037            }
4038        }
4039    }
4040
4041    private static File getSettingsProblemFile() {
4042        File dataDir = Environment.getDataDirectory();
4043        File systemDir = new File(dataDir, "system");
4044        File fname = new File(systemDir, "uiderrors.txt");
4045        return fname;
4046    }
4047
4048    static void reportSettingsProblem(int priority, String msg) {
4049        try {
4050            File fname = getSettingsProblemFile();
4051            FileOutputStream out = new FileOutputStream(fname, true);
4052            PrintWriter pw = new FastPrintWriter(out);
4053            SimpleDateFormat formatter = new SimpleDateFormat();
4054            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4055            pw.println(dateString + ": " + msg);
4056            pw.close();
4057            FileUtils.setPermissions(
4058                    fname.toString(),
4059                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4060                    -1, -1);
4061        } catch (java.io.IOException e) {
4062        }
4063        Slog.println(priority, TAG, msg);
4064    }
4065
4066    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4067            PackageParser.Package pkg, File srcFile, int parseFlags)
4068            throws PackageManagerException {
4069        if (ps != null
4070                && ps.codePath.equals(srcFile)
4071                && ps.timeStamp == srcFile.lastModified()
4072                && !isCompatSignatureUpdateNeeded(pkg)) {
4073            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4074            if (ps.signatures.mSignatures != null
4075                    && ps.signatures.mSignatures.length != 0
4076                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4077                // Optimization: reuse the existing cached certificates
4078                // if the package appears to be unchanged.
4079                pkg.mSignatures = ps.signatures.mSignatures;
4080                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4081                synchronized (mPackages) {
4082                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4083                }
4084                return;
4085            }
4086
4087            Slog.w(TAG, "PackageSetting for " + ps.name
4088                    + " is missing signatures.  Collecting certs again to recover them.");
4089        } else {
4090            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4091        }
4092
4093        try {
4094            pp.collectCertificates(pkg, parseFlags);
4095            pp.collectManifestDigest(pkg);
4096        } catch (PackageParserException e) {
4097            throw PackageManagerException.from(e);
4098        }
4099    }
4100
4101    /*
4102     *  Scan a package and return the newly parsed package.
4103     *  Returns null in case of errors and the error code is stored in mLastScanError
4104     */
4105    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4106            long currentTime, UserHandle user) throws PackageManagerException {
4107        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4108        parseFlags |= mDefParseFlags;
4109        PackageParser pp = new PackageParser();
4110        pp.setSeparateProcesses(mSeparateProcesses);
4111        pp.setOnlyCoreApps(mOnlyCore);
4112        pp.setDisplayMetrics(mMetrics);
4113
4114        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4115            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4116        }
4117
4118        final PackageParser.Package pkg;
4119        try {
4120            pkg = pp.parsePackage(scanFile, parseFlags);
4121        } catch (PackageParserException e) {
4122            throw PackageManagerException.from(e);
4123        }
4124
4125        PackageSetting ps = null;
4126        PackageSetting updatedPkg;
4127        // reader
4128        synchronized (mPackages) {
4129            // Look to see if we already know about this package.
4130            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4131            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4132                // This package has been renamed to its original name.  Let's
4133                // use that.
4134                ps = mSettings.peekPackageLPr(oldName);
4135            }
4136            // If there was no original package, see one for the real package name.
4137            if (ps == null) {
4138                ps = mSettings.peekPackageLPr(pkg.packageName);
4139            }
4140            // Check to see if this package could be hiding/updating a system
4141            // package.  Must look for it either under the original or real
4142            // package name depending on our state.
4143            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4144            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4145        }
4146        boolean updatedPkgBetter = false;
4147        // First check if this is a system package that may involve an update
4148        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4149            if (ps != null && !ps.codePath.equals(scanFile)) {
4150                // The path has changed from what was last scanned...  check the
4151                // version of the new path against what we have stored to determine
4152                // what to do.
4153                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4154                if (pkg.mVersionCode < ps.versionCode) {
4155                    // The system package has been updated and the code path does not match
4156                    // Ignore entry. Skip it.
4157                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4158                            + " ignored: updated version " + ps.versionCode
4159                            + " better than this " + pkg.mVersionCode);
4160                    if (!updatedPkg.codePath.equals(scanFile)) {
4161                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4162                                + ps.name + " changing from " + updatedPkg.codePathString
4163                                + " to " + scanFile);
4164                        updatedPkg.codePath = scanFile;
4165                        updatedPkg.codePathString = scanFile.toString();
4166                        // This is the point at which we know that the system-disk APK
4167                        // for this package has moved during a reboot (e.g. due to an OTA),
4168                        // so we need to reevaluate it for privilege policy.
4169                        if (locationIsPrivileged(scanFile)) {
4170                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4171                        }
4172                    }
4173                    updatedPkg.pkg = pkg;
4174                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4175                } else {
4176                    // The current app on the system partition is better than
4177                    // what we have updated to on the data partition; switch
4178                    // back to the system partition version.
4179                    // At this point, its safely assumed that package installation for
4180                    // apps in system partition will go through. If not there won't be a working
4181                    // version of the app
4182                    // writer
4183                    synchronized (mPackages) {
4184                        // Just remove the loaded entries from package lists.
4185                        mPackages.remove(ps.name);
4186                    }
4187                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4188                            + "reverting from " + ps.codePathString
4189                            + ": new version " + pkg.mVersionCode
4190                            + " better than installed " + ps.versionCode);
4191
4192                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4193                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4194                            getAppDexInstructionSets(ps));
4195                    synchronized (mInstallLock) {
4196                        args.cleanUpResourcesLI();
4197                    }
4198                    synchronized (mPackages) {
4199                        mSettings.enableSystemPackageLPw(ps.name);
4200                    }
4201                    updatedPkgBetter = true;
4202                }
4203            }
4204        }
4205
4206        if (updatedPkg != null) {
4207            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4208            // initially
4209            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4210
4211            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4212            // flag set initially
4213            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4214                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4215            }
4216        }
4217
4218        // Verify certificates against what was last scanned
4219        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4220
4221        /*
4222         * A new system app appeared, but we already had a non-system one of the
4223         * same name installed earlier.
4224         */
4225        boolean shouldHideSystemApp = false;
4226        if (updatedPkg == null && ps != null
4227                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4228            /*
4229             * Check to make sure the signatures match first. If they don't,
4230             * wipe the installed application and its data.
4231             */
4232            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4233                    != PackageManager.SIGNATURE_MATCH) {
4234                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4235                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4236                ps = null;
4237            } else {
4238                /*
4239                 * If the newly-added system app is an older version than the
4240                 * already installed version, hide it. It will be scanned later
4241                 * and re-added like an update.
4242                 */
4243                if (pkg.mVersionCode < ps.versionCode) {
4244                    shouldHideSystemApp = true;
4245                } else {
4246                    /*
4247                     * The newly found system app is a newer version that the
4248                     * one previously installed. Simply remove the
4249                     * already-installed application and replace it with our own
4250                     * while keeping the application data.
4251                     */
4252                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4253                            + ps.codePathString + ": new version " + pkg.mVersionCode
4254                            + " better than installed " + ps.versionCode);
4255                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4256                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4257                            getAppDexInstructionSets(ps));
4258                    synchronized (mInstallLock) {
4259                        args.cleanUpResourcesLI();
4260                    }
4261                }
4262            }
4263        }
4264
4265        // The apk is forward locked (not public) if its code and resources
4266        // are kept in different files. (except for app in either system or
4267        // vendor path).
4268        // TODO grab this value from PackageSettings
4269        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4270            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4271                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4272            }
4273        }
4274
4275        // TODO: extend to support forward-locked splits
4276        String resourcePath = null;
4277        String baseResourcePath = null;
4278        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4279            if (ps != null && ps.resourcePathString != null) {
4280                resourcePath = ps.resourcePathString;
4281                baseResourcePath = ps.resourcePathString;
4282            } else {
4283                // Should not happen at all. Just log an error.
4284                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4285            }
4286        } else {
4287            resourcePath = pkg.codePath;
4288            baseResourcePath = pkg.baseCodePath;
4289        }
4290
4291        // Set application objects path explicitly.
4292        pkg.applicationInfo.setCodePath(pkg.codePath);
4293        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4294        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4295        pkg.applicationInfo.setResourcePath(resourcePath);
4296        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4297        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4298
4299        // Note that we invoke the following method only if we are about to unpack an application
4300        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4301                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4302
4303        /*
4304         * If the system app should be overridden by a previously installed
4305         * data, hide the system app now and let the /data/app scan pick it up
4306         * again.
4307         */
4308        if (shouldHideSystemApp) {
4309            synchronized (mPackages) {
4310                /*
4311                 * We have to grant systems permissions before we hide, because
4312                 * grantPermissions will assume the package update is trying to
4313                 * expand its permissions.
4314                 */
4315                grantPermissionsLPw(pkg, true, pkg.packageName);
4316                mSettings.disableSystemPackageLPw(pkg.packageName);
4317            }
4318        }
4319
4320        return scannedPkg;
4321    }
4322
4323    private static String fixProcessName(String defProcessName,
4324            String processName, int uid) {
4325        if (processName == null) {
4326            return defProcessName;
4327        }
4328        return processName;
4329    }
4330
4331    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4332            throws PackageManagerException {
4333        if (pkgSetting.signatures.mSignatures != null) {
4334            // Already existing package. Make sure signatures match
4335            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4336                    == PackageManager.SIGNATURE_MATCH;
4337            if (!match) {
4338                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4339                        == PackageManager.SIGNATURE_MATCH;
4340            }
4341            if (!match) {
4342                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4343                        + pkg.packageName + " signatures do not match the "
4344                        + "previously installed version; ignoring!");
4345            }
4346        }
4347
4348        // Check for shared user signatures
4349        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4350            // Already existing package. Make sure signatures match
4351            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4352                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4353            if (!match) {
4354                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4355                        == PackageManager.SIGNATURE_MATCH;
4356            }
4357            if (!match) {
4358                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4359                        "Package " + pkg.packageName
4360                        + " has no signatures that match those in shared user "
4361                        + pkgSetting.sharedUser.name + "; ignoring!");
4362            }
4363        }
4364    }
4365
4366    /**
4367     * Enforces that only the system UID or root's UID can call a method exposed
4368     * via Binder.
4369     *
4370     * @param message used as message if SecurityException is thrown
4371     * @throws SecurityException if the caller is not system or root
4372     */
4373    private static final void enforceSystemOrRoot(String message) {
4374        final int uid = Binder.getCallingUid();
4375        if (uid != Process.SYSTEM_UID && uid != 0) {
4376            throw new SecurityException(message);
4377        }
4378    }
4379
4380    @Override
4381    public void performBootDexOpt() {
4382        enforceSystemOrRoot("Only the system can request dexopt be performed");
4383
4384        final HashSet<PackageParser.Package> pkgs;
4385        synchronized (mPackages) {
4386            pkgs = mDeferredDexOpt;
4387            mDeferredDexOpt = null;
4388        }
4389
4390        if (pkgs != null) {
4391            // Filter out packages that aren't recently used.
4392            //
4393            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4394            // should do a full dexopt.
4395            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4396                // TODO: add a property to control this?
4397                long dexOptLRUThresholdInMinutes;
4398                if (mLazyDexOpt) {
4399                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4400                } else {
4401                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4402                }
4403                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4404
4405                int total = pkgs.size();
4406                int skipped = 0;
4407                long now = System.currentTimeMillis();
4408                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4409                    PackageParser.Package pkg = i.next();
4410                    long then = pkg.mLastPackageUsageTimeInMills;
4411                    if (then + dexOptLRUThresholdInMills < now) {
4412                        if (DEBUG_DEXOPT) {
4413                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4414                                  ((then == 0) ? "never" : new Date(then)));
4415                        }
4416                        i.remove();
4417                        skipped++;
4418                    }
4419                }
4420                if (DEBUG_DEXOPT) {
4421                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4422                }
4423            }
4424
4425            int i = 0;
4426            for (PackageParser.Package pkg : pkgs) {
4427                i++;
4428                if (DEBUG_DEXOPT) {
4429                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4430                          + ": " + pkg.packageName);
4431                }
4432                if (!isFirstBoot()) {
4433                    try {
4434                        ActivityManagerNative.getDefault().showBootMessage(
4435                                mContext.getResources().getString(
4436                                        R.string.android_upgrading_apk,
4437                                        i, pkgs.size()), true);
4438                    } catch (RemoteException e) {
4439                    }
4440                }
4441                PackageParser.Package p = pkg;
4442                synchronized (mInstallLock) {
4443                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4444                            true /* include dependencies */);
4445                }
4446            }
4447        }
4448    }
4449
4450    @Override
4451    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4452        return performDexOpt(packageName, instructionSet, false);
4453    }
4454
4455    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4456        if (info.primaryCpuAbi == null) {
4457            return getPreferredInstructionSet();
4458        }
4459
4460        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4461    }
4462
4463    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4464        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4465        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4466        if (!dexopt && !updateUsage) {
4467            // We aren't going to dexopt or update usage, so bail early.
4468            return false;
4469        }
4470        PackageParser.Package p;
4471        final String targetInstructionSet;
4472        synchronized (mPackages) {
4473            p = mPackages.get(packageName);
4474            if (p == null) {
4475                return false;
4476            }
4477            if (updateUsage) {
4478                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4479            }
4480            mPackageUsage.write(false);
4481            if (!dexopt) {
4482                // We aren't going to dexopt, so bail early.
4483                return false;
4484            }
4485
4486            targetInstructionSet = instructionSet != null ? instructionSet :
4487                    getPrimaryInstructionSet(p.applicationInfo);
4488            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4489                return false;
4490            }
4491        }
4492
4493        synchronized (mInstallLock) {
4494            final String[] instructionSets = new String[] { targetInstructionSet };
4495            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4496                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4497        }
4498    }
4499
4500    public HashSet<String> getPackagesThatNeedDexOpt() {
4501        HashSet<String> pkgs = null;
4502        synchronized (mPackages) {
4503            for (PackageParser.Package p : mPackages.values()) {
4504                if (DEBUG_DEXOPT) {
4505                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4506                }
4507                if (!p.mDexOptPerformed.isEmpty()) {
4508                    continue;
4509                }
4510                if (pkgs == null) {
4511                    pkgs = new HashSet<String>();
4512                }
4513                pkgs.add(p.packageName);
4514            }
4515        }
4516        return pkgs;
4517    }
4518
4519    public void shutdown() {
4520        mPackageUsage.write(true);
4521    }
4522
4523    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4524             boolean forceDex, boolean defer, HashSet<String> done) {
4525        for (int i=0; i<libs.size(); i++) {
4526            PackageParser.Package libPkg;
4527            String libName;
4528            synchronized (mPackages) {
4529                libName = libs.get(i);
4530                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4531                if (lib != null && lib.apk != null) {
4532                    libPkg = mPackages.get(lib.apk);
4533                } else {
4534                    libPkg = null;
4535                }
4536            }
4537            if (libPkg != null && !done.contains(libName)) {
4538                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4539            }
4540        }
4541    }
4542
4543    static final int DEX_OPT_SKIPPED = 0;
4544    static final int DEX_OPT_PERFORMED = 1;
4545    static final int DEX_OPT_DEFERRED = 2;
4546    static final int DEX_OPT_FAILED = -1;
4547
4548    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4549            boolean forceDex, boolean defer, HashSet<String> done) {
4550        final String[] instructionSets = targetInstructionSets != null ?
4551                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4552
4553        if (done != null) {
4554            done.add(pkg.packageName);
4555            if (pkg.usesLibraries != null) {
4556                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4557            }
4558            if (pkg.usesOptionalLibraries != null) {
4559                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4560            }
4561        }
4562
4563        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4564            return DEX_OPT_SKIPPED;
4565        }
4566
4567        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4568
4569        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4570        boolean performedDexOpt = false;
4571        // There are three basic cases here:
4572        // 1.) we need to dexopt, either because we are forced or it is needed
4573        // 2.) we are defering a needed dexopt
4574        // 3.) we are skipping an unneeded dexopt
4575        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4576        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4577            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4578                continue;
4579            }
4580
4581            for (String path : paths) {
4582                try {
4583                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4584                    // patckage or the one we find does not match the image checksum (i.e. it was
4585                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4586                    // odex file and it matches the checksum of the image but not its base address,
4587                    // meaning we need to move it.
4588                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4589                            pkg.packageName, dexCodeInstructionSet, defer);
4590                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4591                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4592                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4593                                + " vmSafeMode=" + vmSafeMode);
4594                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4595                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4596                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4597
4598                        if (ret < 0) {
4599                            // Don't bother running dexopt again if we failed, it will probably
4600                            // just result in an error again. Also, don't bother dexopting for other
4601                            // paths & ISAs.
4602                            return DEX_OPT_FAILED;
4603                        }
4604
4605                        performedDexOpt = true;
4606                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4607                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4608                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4609                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4610                                pkg.packageName, dexCodeInstructionSet);
4611
4612                        if (ret < 0) {
4613                            // Don't bother running patchoat again if we failed, it will probably
4614                            // just result in an error again. Also, don't bother dexopting for other
4615                            // paths & ISAs.
4616                            return DEX_OPT_FAILED;
4617                        }
4618
4619                        performedDexOpt = true;
4620                    }
4621
4622                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4623                    // paths and instruction sets. We'll deal with them all together when we process
4624                    // our list of deferred dexopts.
4625                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4626                        if (mDeferredDexOpt == null) {
4627                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4628                        }
4629                        mDeferredDexOpt.add(pkg);
4630                        return DEX_OPT_DEFERRED;
4631                    }
4632                } catch (FileNotFoundException e) {
4633                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4634                    return DEX_OPT_FAILED;
4635                } catch (IOException e) {
4636                    Slog.w(TAG, "IOException reading apk: " + path, e);
4637                    return DEX_OPT_FAILED;
4638                } catch (StaleDexCacheError e) {
4639                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4640                    return DEX_OPT_FAILED;
4641                } catch (Exception e) {
4642                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4643                    return DEX_OPT_FAILED;
4644                }
4645            }
4646
4647            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4648            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4649            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4650            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4651            // it.
4652            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4653        }
4654
4655        // If we've gotten here, we're sure that no error occurred and that we haven't
4656        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4657        // we've skipped all of them because they are up to date. In both cases this
4658        // package doesn't need dexopt any longer.
4659        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4660    }
4661
4662    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4663        if (info.primaryCpuAbi != null) {
4664            if (info.secondaryCpuAbi != null) {
4665                return new String[] {
4666                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4667                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4668            } else {
4669                return new String[] {
4670                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4671            }
4672        }
4673
4674        return new String[] { getPreferredInstructionSet() };
4675    }
4676
4677    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4678        if (ps.primaryCpuAbiString != null) {
4679            if (ps.secondaryCpuAbiString != null) {
4680                return new String[] {
4681                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4682                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4683            } else {
4684                return new String[] {
4685                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4686            }
4687        }
4688
4689        return new String[] { getPreferredInstructionSet() };
4690    }
4691
4692    private static String getPreferredInstructionSet() {
4693        if (sPreferredInstructionSet == null) {
4694            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4695        }
4696
4697        return sPreferredInstructionSet;
4698    }
4699
4700    private static List<String> getAllInstructionSets() {
4701        final String[] allAbis = Build.SUPPORTED_ABIS;
4702        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4703
4704        for (String abi : allAbis) {
4705            final String instructionSet = VMRuntime.getInstructionSet(abi);
4706            if (!allInstructionSets.contains(instructionSet)) {
4707                allInstructionSets.add(instructionSet);
4708            }
4709        }
4710
4711        return allInstructionSets;
4712    }
4713
4714    /**
4715     * Returns the instruction set that should be used to compile dex code. In the presence of
4716     * a native bridge this might be different than the one shared libraries use.
4717     */
4718    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4719        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4720        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4721    }
4722
4723    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4724        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4725        for (String instructionSet : instructionSets) {
4726            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4727        }
4728        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4729    }
4730
4731    @Override
4732    public void forceDexOpt(String packageName) {
4733        enforceSystemOrRoot("forceDexOpt");
4734
4735        PackageParser.Package pkg;
4736        synchronized (mPackages) {
4737            pkg = mPackages.get(packageName);
4738            if (pkg == null) {
4739                throw new IllegalArgumentException("Missing package: " + packageName);
4740            }
4741        }
4742
4743        synchronized (mInstallLock) {
4744            final String[] instructionSets = new String[] {
4745                    getPrimaryInstructionSet(pkg.applicationInfo) };
4746            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4747            if (res != DEX_OPT_PERFORMED) {
4748                throw new IllegalStateException("Failed to dexopt: " + res);
4749            }
4750        }
4751    }
4752
4753    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4754                                boolean forceDex, boolean defer, boolean inclDependencies) {
4755        HashSet<String> done;
4756        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4757            done = new HashSet<String>();
4758            done.add(pkg.packageName);
4759        } else {
4760            done = null;
4761        }
4762        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4763    }
4764
4765    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4766        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4767            Slog.w(TAG, "Unable to update from " + oldPkg.name
4768                    + " to " + newPkg.packageName
4769                    + ": old package not in system partition");
4770            return false;
4771        } else if (mPackages.get(oldPkg.name) != null) {
4772            Slog.w(TAG, "Unable to update from " + oldPkg.name
4773                    + " to " + newPkg.packageName
4774                    + ": old package still exists");
4775            return false;
4776        }
4777        return true;
4778    }
4779
4780    File getDataPathForUser(int userId) {
4781        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4782    }
4783
4784    private File getDataPathForPackage(String packageName, int userId) {
4785        /*
4786         * Until we fully support multiple users, return the directory we
4787         * previously would have. The PackageManagerTests will need to be
4788         * revised when this is changed back..
4789         */
4790        if (userId == 0) {
4791            return new File(mAppDataDir, packageName);
4792        } else {
4793            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4794                + File.separator + packageName);
4795        }
4796    }
4797
4798    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4799        int[] users = sUserManager.getUserIds();
4800        int res = mInstaller.install(packageName, uid, uid, seinfo);
4801        if (res < 0) {
4802            return res;
4803        }
4804        for (int user : users) {
4805            if (user != 0) {
4806                res = mInstaller.createUserData(packageName,
4807                        UserHandle.getUid(user, uid), user, seinfo);
4808                if (res < 0) {
4809                    return res;
4810                }
4811            }
4812        }
4813        return res;
4814    }
4815
4816    private int removeDataDirsLI(String packageName) {
4817        int[] users = sUserManager.getUserIds();
4818        int res = 0;
4819        for (int user : users) {
4820            int resInner = mInstaller.remove(packageName, user);
4821            if (resInner < 0) {
4822                res = resInner;
4823            }
4824        }
4825
4826        return res;
4827    }
4828
4829    private int deleteCodeCacheDirsLI(String packageName) {
4830        int[] users = sUserManager.getUserIds();
4831        int res = 0;
4832        for (int user : users) {
4833            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4834            if (resInner < 0) {
4835                res = resInner;
4836            }
4837        }
4838        return res;
4839    }
4840
4841    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4842            PackageParser.Package changingLib) {
4843        if (file.path != null) {
4844            usesLibraryFiles.add(file.path);
4845            return;
4846        }
4847        PackageParser.Package p = mPackages.get(file.apk);
4848        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4849            // If we are doing this while in the middle of updating a library apk,
4850            // then we need to make sure to use that new apk for determining the
4851            // dependencies here.  (We haven't yet finished committing the new apk
4852            // to the package manager state.)
4853            if (p == null || p.packageName.equals(changingLib.packageName)) {
4854                p = changingLib;
4855            }
4856        }
4857        if (p != null) {
4858            usesLibraryFiles.addAll(p.getAllCodePaths());
4859        }
4860    }
4861
4862    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4863            PackageParser.Package changingLib) throws PackageManagerException {
4864        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4865            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4866            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4867            for (int i=0; i<N; i++) {
4868                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4869                if (file == null) {
4870                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4871                            "Package " + pkg.packageName + " requires unavailable shared library "
4872                            + pkg.usesLibraries.get(i) + "; failing!");
4873                }
4874                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4875            }
4876            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4877            for (int i=0; i<N; i++) {
4878                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4879                if (file == null) {
4880                    Slog.w(TAG, "Package " + pkg.packageName
4881                            + " desires unavailable shared library "
4882                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4883                } else {
4884                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4885                }
4886            }
4887            N = usesLibraryFiles.size();
4888            if (N > 0) {
4889                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4890            } else {
4891                pkg.usesLibraryFiles = null;
4892            }
4893        }
4894    }
4895
4896    private static boolean hasString(List<String> list, List<String> which) {
4897        if (list == null) {
4898            return false;
4899        }
4900        for (int i=list.size()-1; i>=0; i--) {
4901            for (int j=which.size()-1; j>=0; j--) {
4902                if (which.get(j).equals(list.get(i))) {
4903                    return true;
4904                }
4905            }
4906        }
4907        return false;
4908    }
4909
4910    private void updateAllSharedLibrariesLPw() {
4911        for (PackageParser.Package pkg : mPackages.values()) {
4912            try {
4913                updateSharedLibrariesLPw(pkg, null);
4914            } catch (PackageManagerException e) {
4915                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4916            }
4917        }
4918    }
4919
4920    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4921            PackageParser.Package changingPkg) {
4922        ArrayList<PackageParser.Package> res = null;
4923        for (PackageParser.Package pkg : mPackages.values()) {
4924            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4925                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4926                if (res == null) {
4927                    res = new ArrayList<PackageParser.Package>();
4928                }
4929                res.add(pkg);
4930                try {
4931                    updateSharedLibrariesLPw(pkg, changingPkg);
4932                } catch (PackageManagerException e) {
4933                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4934                }
4935            }
4936        }
4937        return res;
4938    }
4939
4940    /**
4941     * Derive the value of the {@code cpuAbiOverride} based on the provided
4942     * value and an optional stored value from the package settings.
4943     */
4944    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4945        String cpuAbiOverride = null;
4946
4947        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4948            cpuAbiOverride = null;
4949        } else if (abiOverride != null) {
4950            cpuAbiOverride = abiOverride;
4951        } else if (settings != null) {
4952            cpuAbiOverride = settings.cpuAbiOverrideString;
4953        }
4954
4955        return cpuAbiOverride;
4956    }
4957
4958    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4959            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4960        boolean success = false;
4961        try {
4962            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
4963                    currentTime, user);
4964            success = true;
4965            return res;
4966        } finally {
4967            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4968                removeDataDirsLI(pkg.packageName);
4969            }
4970        }
4971    }
4972
4973    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
4974            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4975        final File scanFile = new File(pkg.codePath);
4976        if (pkg.applicationInfo.getCodePath() == null ||
4977                pkg.applicationInfo.getResourcePath() == null) {
4978            // Bail out. The resource and code paths haven't been set.
4979            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4980                    "Code and resource paths haven't been set correctly");
4981        }
4982
4983        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4984            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4985        }
4986
4987        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4988            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4989        }
4990
4991        if (mCustomResolverComponentName != null &&
4992                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4993            setUpCustomResolverActivity(pkg);
4994        }
4995
4996        if (pkg.packageName.equals("android")) {
4997            synchronized (mPackages) {
4998                if (mAndroidApplication != null) {
4999                    Slog.w(TAG, "*************************************************");
5000                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5001                    Slog.w(TAG, " file=" + scanFile);
5002                    Slog.w(TAG, "*************************************************");
5003                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5004                            "Core android package being redefined.  Skipping.");
5005                }
5006
5007                // Set up information for our fall-back user intent resolution activity.
5008                mPlatformPackage = pkg;
5009                pkg.mVersionCode = mSdkVersion;
5010                mAndroidApplication = pkg.applicationInfo;
5011
5012                if (!mResolverReplaced) {
5013                    mResolveActivity.applicationInfo = mAndroidApplication;
5014                    mResolveActivity.name = ResolverActivity.class.getName();
5015                    mResolveActivity.packageName = mAndroidApplication.packageName;
5016                    mResolveActivity.processName = "system:ui";
5017                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5018                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5019                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5020                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5021                    mResolveActivity.exported = true;
5022                    mResolveActivity.enabled = true;
5023                    mResolveInfo.activityInfo = mResolveActivity;
5024                    mResolveInfo.priority = 0;
5025                    mResolveInfo.preferredOrder = 0;
5026                    mResolveInfo.match = 0;
5027                    mResolveComponentName = new ComponentName(
5028                            mAndroidApplication.packageName, mResolveActivity.name);
5029                }
5030            }
5031        }
5032
5033        if (DEBUG_PACKAGE_SCANNING) {
5034            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5035                Log.d(TAG, "Scanning package " + pkg.packageName);
5036        }
5037
5038        if (mPackages.containsKey(pkg.packageName)
5039                || mSharedLibraries.containsKey(pkg.packageName)) {
5040            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5041                    "Application package " + pkg.packageName
5042                    + " already installed.  Skipping duplicate.");
5043        }
5044
5045        // Initialize package source and resource directories
5046        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5047        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5048
5049        SharedUserSetting suid = null;
5050        PackageSetting pkgSetting = null;
5051
5052        if (!isSystemApp(pkg)) {
5053            // Only system apps can use these features.
5054            pkg.mOriginalPackages = null;
5055            pkg.mRealPackage = null;
5056            pkg.mAdoptPermissions = null;
5057        }
5058
5059        // writer
5060        synchronized (mPackages) {
5061            if (pkg.mSharedUserId != null) {
5062                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5063                if (suid == null) {
5064                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5065                            "Creating application package " + pkg.packageName
5066                            + " for shared user failed");
5067                }
5068                if (DEBUG_PACKAGE_SCANNING) {
5069                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5070                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5071                                + "): packages=" + suid.packages);
5072                }
5073            }
5074
5075            // Check if we are renaming from an original package name.
5076            PackageSetting origPackage = null;
5077            String realName = null;
5078            if (pkg.mOriginalPackages != null) {
5079                // This package may need to be renamed to a previously
5080                // installed name.  Let's check on that...
5081                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5082                if (pkg.mOriginalPackages.contains(renamed)) {
5083                    // This package had originally been installed as the
5084                    // original name, and we have already taken care of
5085                    // transitioning to the new one.  Just update the new
5086                    // one to continue using the old name.
5087                    realName = pkg.mRealPackage;
5088                    if (!pkg.packageName.equals(renamed)) {
5089                        // Callers into this function may have already taken
5090                        // care of renaming the package; only do it here if
5091                        // it is not already done.
5092                        pkg.setPackageName(renamed);
5093                    }
5094
5095                } else {
5096                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5097                        if ((origPackage = mSettings.peekPackageLPr(
5098                                pkg.mOriginalPackages.get(i))) != null) {
5099                            // We do have the package already installed under its
5100                            // original name...  should we use it?
5101                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5102                                // New package is not compatible with original.
5103                                origPackage = null;
5104                                continue;
5105                            } else if (origPackage.sharedUser != null) {
5106                                // Make sure uid is compatible between packages.
5107                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5108                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5109                                            + " to " + pkg.packageName + ": old uid "
5110                                            + origPackage.sharedUser.name
5111                                            + " differs from " + pkg.mSharedUserId);
5112                                    origPackage = null;
5113                                    continue;
5114                                }
5115                            } else {
5116                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5117                                        + pkg.packageName + " to old name " + origPackage.name);
5118                            }
5119                            break;
5120                        }
5121                    }
5122                }
5123            }
5124
5125            if (mTransferedPackages.contains(pkg.packageName)) {
5126                Slog.w(TAG, "Package " + pkg.packageName
5127                        + " was transferred to another, but its .apk remains");
5128            }
5129
5130            // Just create the setting, don't add it yet. For already existing packages
5131            // the PkgSetting exists already and doesn't have to be created.
5132            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5133                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5134                    pkg.applicationInfo.primaryCpuAbi,
5135                    pkg.applicationInfo.secondaryCpuAbi,
5136                    pkg.applicationInfo.flags, user, false);
5137            if (pkgSetting == null) {
5138                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5139                        "Creating application package " + pkg.packageName + " failed");
5140            }
5141
5142            if (pkgSetting.origPackage != null) {
5143                // If we are first transitioning from an original package,
5144                // fix up the new package's name now.  We need to do this after
5145                // looking up the package under its new name, so getPackageLP
5146                // can take care of fiddling things correctly.
5147                pkg.setPackageName(origPackage.name);
5148
5149                // File a report about this.
5150                String msg = "New package " + pkgSetting.realName
5151                        + " renamed to replace old package " + pkgSetting.name;
5152                reportSettingsProblem(Log.WARN, msg);
5153
5154                // Make a note of it.
5155                mTransferedPackages.add(origPackage.name);
5156
5157                // No longer need to retain this.
5158                pkgSetting.origPackage = null;
5159            }
5160
5161            if (realName != null) {
5162                // Make a note of it.
5163                mTransferedPackages.add(pkg.packageName);
5164            }
5165
5166            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5167                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5168            }
5169
5170            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5171                // Check all shared libraries and map to their actual file path.
5172                // We only do this here for apps not on a system dir, because those
5173                // are the only ones that can fail an install due to this.  We
5174                // will take care of the system apps by updating all of their
5175                // library paths after the scan is done.
5176                updateSharedLibrariesLPw(pkg, null);
5177            }
5178
5179            if (mFoundPolicyFile) {
5180                SELinuxMMAC.assignSeinfoValue(pkg);
5181            }
5182
5183            pkg.applicationInfo.uid = pkgSetting.appId;
5184            pkg.mExtras = pkgSetting;
5185            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5186                try {
5187                    verifySignaturesLP(pkgSetting, pkg);
5188                } catch (PackageManagerException e) {
5189                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5190                        throw e;
5191                    }
5192                    // The signature has changed, but this package is in the system
5193                    // image...  let's recover!
5194                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5195                    // However...  if this package is part of a shared user, but it
5196                    // doesn't match the signature of the shared user, let's fail.
5197                    // What this means is that you can't change the signatures
5198                    // associated with an overall shared user, which doesn't seem all
5199                    // that unreasonable.
5200                    if (pkgSetting.sharedUser != null) {
5201                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5202                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5203                            throw new PackageManagerException(
5204                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5205                                            "Signature mismatch for shared user : "
5206                                            + pkgSetting.sharedUser);
5207                        }
5208                    }
5209                    // File a report about this.
5210                    String msg = "System package " + pkg.packageName
5211                        + " signature changed; retaining data.";
5212                    reportSettingsProblem(Log.WARN, msg);
5213                }
5214            } else {
5215                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5216                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5217                            + pkg.packageName + " upgrade keys do not match the "
5218                            + "previously installed version");
5219                } else {
5220                    // signatures may have changed as result of upgrade
5221                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5222                }
5223            }
5224            // Verify that this new package doesn't have any content providers
5225            // that conflict with existing packages.  Only do this if the
5226            // package isn't already installed, since we don't want to break
5227            // things that are installed.
5228            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5229                final int N = pkg.providers.size();
5230                int i;
5231                for (i=0; i<N; i++) {
5232                    PackageParser.Provider p = pkg.providers.get(i);
5233                    if (p.info.authority != null) {
5234                        String names[] = p.info.authority.split(";");
5235                        for (int j = 0; j < names.length; j++) {
5236                            if (mProvidersByAuthority.containsKey(names[j])) {
5237                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5238                                final String otherPackageName =
5239                                        ((other != null && other.getComponentName() != null) ?
5240                                                other.getComponentName().getPackageName() : "?");
5241                                throw new PackageManagerException(
5242                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5243                                                "Can't install because provider name " + names[j]
5244                                                + " (in package " + pkg.applicationInfo.packageName
5245                                                + ") is already used by " + otherPackageName);
5246                            }
5247                        }
5248                    }
5249                }
5250            }
5251
5252            if (pkg.mAdoptPermissions != null) {
5253                // This package wants to adopt ownership of permissions from
5254                // another package.
5255                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5256                    final String origName = pkg.mAdoptPermissions.get(i);
5257                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5258                    if (orig != null) {
5259                        if (verifyPackageUpdateLPr(orig, pkg)) {
5260                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5261                                    + pkg.packageName);
5262                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5263                        }
5264                    }
5265                }
5266            }
5267        }
5268
5269        final String pkgName = pkg.packageName;
5270
5271        final long scanFileTime = scanFile.lastModified();
5272        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5273        pkg.applicationInfo.processName = fixProcessName(
5274                pkg.applicationInfo.packageName,
5275                pkg.applicationInfo.processName,
5276                pkg.applicationInfo.uid);
5277
5278        File dataPath;
5279        if (mPlatformPackage == pkg) {
5280            // The system package is special.
5281            dataPath = new File(Environment.getDataDirectory(), "system");
5282
5283            pkg.applicationInfo.dataDir = dataPath.getPath();
5284
5285        } else {
5286            // This is a normal package, need to make its data directory.
5287            dataPath = getDataPathForPackage(pkg.packageName, 0);
5288
5289            boolean uidError = false;
5290            if (dataPath.exists()) {
5291                int currentUid = 0;
5292                try {
5293                    StructStat stat = Os.stat(dataPath.getPath());
5294                    currentUid = stat.st_uid;
5295                } catch (ErrnoException e) {
5296                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5297                }
5298
5299                // If we have mismatched owners for the data path, we have a problem.
5300                if (currentUid != pkg.applicationInfo.uid) {
5301                    boolean recovered = false;
5302                    if (currentUid == 0) {
5303                        // The directory somehow became owned by root.  Wow.
5304                        // This is probably because the system was stopped while
5305                        // installd was in the middle of messing with its libs
5306                        // directory.  Ask installd to fix that.
5307                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5308                                pkg.applicationInfo.uid);
5309                        if (ret >= 0) {
5310                            recovered = true;
5311                            String msg = "Package " + pkg.packageName
5312                                    + " unexpectedly changed to uid 0; recovered to " +
5313                                    + pkg.applicationInfo.uid;
5314                            reportSettingsProblem(Log.WARN, msg);
5315                        }
5316                    }
5317                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5318                            || (scanFlags&SCAN_BOOTING) != 0)) {
5319                        // If this is a system app, we can at least delete its
5320                        // current data so the application will still work.
5321                        int ret = removeDataDirsLI(pkgName);
5322                        if (ret >= 0) {
5323                            // TODO: Kill the processes first
5324                            // Old data gone!
5325                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5326                                    ? "System package " : "Third party package ";
5327                            String msg = prefix + pkg.packageName
5328                                    + " has changed from uid: "
5329                                    + currentUid + " to "
5330                                    + pkg.applicationInfo.uid + "; old data erased";
5331                            reportSettingsProblem(Log.WARN, msg);
5332                            recovered = true;
5333
5334                            // And now re-install the app.
5335                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5336                                                   pkg.applicationInfo.seinfo);
5337                            if (ret == -1) {
5338                                // Ack should not happen!
5339                                msg = prefix + pkg.packageName
5340                                        + " could not have data directory re-created after delete.";
5341                                reportSettingsProblem(Log.WARN, msg);
5342                                throw new PackageManagerException(
5343                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5344                            }
5345                        }
5346                        if (!recovered) {
5347                            mHasSystemUidErrors = true;
5348                        }
5349                    } else if (!recovered) {
5350                        // If we allow this install to proceed, we will be broken.
5351                        // Abort, abort!
5352                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5353                                "scanPackageLI");
5354                    }
5355                    if (!recovered) {
5356                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5357                            + pkg.applicationInfo.uid + "/fs_"
5358                            + currentUid;
5359                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5360                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5361                        String msg = "Package " + pkg.packageName
5362                                + " has mismatched uid: "
5363                                + currentUid + " on disk, "
5364                                + pkg.applicationInfo.uid + " in settings";
5365                        // writer
5366                        synchronized (mPackages) {
5367                            mSettings.mReadMessages.append(msg);
5368                            mSettings.mReadMessages.append('\n');
5369                            uidError = true;
5370                            if (!pkgSetting.uidError) {
5371                                reportSettingsProblem(Log.ERROR, msg);
5372                            }
5373                        }
5374                    }
5375                }
5376                pkg.applicationInfo.dataDir = dataPath.getPath();
5377                if (mShouldRestoreconData) {
5378                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5379                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5380                                pkg.applicationInfo.uid);
5381                }
5382            } else {
5383                if (DEBUG_PACKAGE_SCANNING) {
5384                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5385                        Log.v(TAG, "Want this data dir: " + dataPath);
5386                }
5387                //invoke installer to do the actual installation
5388                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5389                                           pkg.applicationInfo.seinfo);
5390                if (ret < 0) {
5391                    // Error from installer
5392                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5393                            "Unable to create data dirs [errorCode=" + ret + "]");
5394                }
5395
5396                if (dataPath.exists()) {
5397                    pkg.applicationInfo.dataDir = dataPath.getPath();
5398                } else {
5399                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5400                    pkg.applicationInfo.dataDir = null;
5401                }
5402            }
5403
5404            pkgSetting.uidError = uidError;
5405        }
5406
5407        final String path = scanFile.getPath();
5408        final String codePath = pkg.applicationInfo.getCodePath();
5409        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5410        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5411            setBundledAppAbisAndRoots(pkg, pkgSetting);
5412
5413            // If we haven't found any native libraries for the app, check if it has
5414            // renderscript code. We'll need to force the app to 32 bit if it has
5415            // renderscript bitcode.
5416            if (pkg.applicationInfo.primaryCpuAbi == null
5417                    && pkg.applicationInfo.secondaryCpuAbi == null
5418                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5419                NativeLibraryHelper.Handle handle = null;
5420                try {
5421                    handle = NativeLibraryHelper.Handle.create(scanFile);
5422                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5423                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5424                    }
5425                } catch (IOException ioe) {
5426                    Slog.w(TAG, "Error scanning system app : " + ioe);
5427                } finally {
5428                    IoUtils.closeQuietly(handle);
5429                }
5430            }
5431
5432            setNativeLibraryPaths(pkg);
5433        } else {
5434            // TODO: We can probably be smarter about this stuff. For installed apps,
5435            // we can calculate this information at install time once and for all. For
5436            // system apps, we can probably assume that this information doesn't change
5437            // after the first boot scan. As things stand, we do lots of unnecessary work.
5438
5439            // Give ourselves some initial paths; we'll come back for another
5440            // pass once we've determined ABI below.
5441            setNativeLibraryPaths(pkg);
5442
5443            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5444            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5445            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5446
5447            NativeLibraryHelper.Handle handle = null;
5448            try {
5449                handle = NativeLibraryHelper.Handle.create(scanFile);
5450                // TODO(multiArch): This can be null for apps that didn't go through the
5451                // usual installation process. We can calculate it again, like we
5452                // do during install time.
5453                //
5454                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5455                // unnecessary.
5456                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5457
5458                // Null out the abis so that they can be recalculated.
5459                pkg.applicationInfo.primaryCpuAbi = null;
5460                pkg.applicationInfo.secondaryCpuAbi = null;
5461                if (isMultiArch(pkg.applicationInfo)) {
5462                    // Warn if we've set an abiOverride for multi-lib packages..
5463                    // By definition, we need to copy both 32 and 64 bit libraries for
5464                    // such packages.
5465                    if (pkg.cpuAbiOverride != null
5466                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5467                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5468                    }
5469
5470                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5471                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5472                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5473                        if (isAsec) {
5474                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5475                        } else {
5476                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5477                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5478                                    useIsaSpecificSubdirs);
5479                        }
5480                    }
5481
5482                    maybeThrowExceptionForMultiArchCopy(
5483                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5484
5485                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5486                        if (isAsec) {
5487                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5488                        } else {
5489                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5490                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5491                                    useIsaSpecificSubdirs);
5492                        }
5493                    }
5494
5495                    maybeThrowExceptionForMultiArchCopy(
5496                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5497
5498                    if (abi64 >= 0) {
5499                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5500                    }
5501
5502                    if (abi32 >= 0) {
5503                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5504                        if (abi64 >= 0) {
5505                            pkg.applicationInfo.secondaryCpuAbi = abi;
5506                        } else {
5507                            pkg.applicationInfo.primaryCpuAbi = abi;
5508                        }
5509                    }
5510                } else {
5511                    String[] abiList = (cpuAbiOverride != null) ?
5512                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5513
5514                    // Enable gross and lame hacks for apps that are built with old
5515                    // SDK tools. We must scan their APKs for renderscript bitcode and
5516                    // not launch them if it's present. Don't bother checking on devices
5517                    // that don't have 64 bit support.
5518                    boolean needsRenderScriptOverride = false;
5519                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5520                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5521                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5522                        needsRenderScriptOverride = true;
5523                    }
5524
5525                    final int copyRet;
5526                    if (isAsec) {
5527                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5528                    } else {
5529                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5530                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5531                    }
5532
5533                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5534                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5535                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5536                    }
5537
5538                    if (copyRet >= 0) {
5539                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5540                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5541                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5542                    } else if (needsRenderScriptOverride) {
5543                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5544                    }
5545                }
5546            } catch (IOException ioe) {
5547                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5548            } finally {
5549                IoUtils.closeQuietly(handle);
5550            }
5551
5552            // Now that we've calculated the ABIs and determined if it's an internal app,
5553            // we will go ahead and populate the nativeLibraryPath.
5554            setNativeLibraryPaths(pkg);
5555
5556            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5557            final int[] userIds = sUserManager.getUserIds();
5558            synchronized (mInstallLock) {
5559                // Create a native library symlink only if we have native libraries
5560                // and if the native libraries are 32 bit libraries. We do not provide
5561                // this symlink for 64 bit libraries.
5562                if (pkg.applicationInfo.primaryCpuAbi != null &&
5563                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5564                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5565                    for (int userId : userIds) {
5566                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5567                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5568                                    "Failed linking native library dir (user=" + userId + ")");
5569                        }
5570                    }
5571                }
5572            }
5573        }
5574
5575        // This is a special case for the "system" package, where the ABI is
5576        // dictated by the zygote configuration (and init.rc). We should keep track
5577        // of this ABI so that we can deal with "normal" applications that run under
5578        // the same UID correctly.
5579        if (mPlatformPackage == pkg) {
5580            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5581                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5582        }
5583
5584        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5585        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5586        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5587        // Copy the derived override back to the parsed package, so that we can
5588        // update the package settings accordingly.
5589        pkg.cpuAbiOverride = cpuAbiOverride;
5590
5591        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5592                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5593                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5594
5595        // Push the derived path down into PackageSettings so we know what to
5596        // clean up at uninstall time.
5597        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5598
5599        if (DEBUG_ABI_SELECTION) {
5600            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5601                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5602                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5603        }
5604
5605        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5606            // We don't do this here during boot because we can do it all
5607            // at once after scanning all existing packages.
5608            //
5609            // We also do this *before* we perform dexopt on this package, so that
5610            // we can avoid redundant dexopts, and also to make sure we've got the
5611            // code and package path correct.
5612            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5613                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5614        }
5615
5616        if ((scanFlags & SCAN_NO_DEX) == 0) {
5617            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5618                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5619                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5620            }
5621        }
5622
5623        if (mFactoryTest && pkg.requestedPermissions.contains(
5624                android.Manifest.permission.FACTORY_TEST)) {
5625            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5626        }
5627
5628        ArrayList<PackageParser.Package> clientLibPkgs = null;
5629
5630        // writer
5631        synchronized (mPackages) {
5632            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5633                // Only system apps can add new shared libraries.
5634                if (pkg.libraryNames != null) {
5635                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5636                        String name = pkg.libraryNames.get(i);
5637                        boolean allowed = false;
5638                        if (isUpdatedSystemApp(pkg)) {
5639                            // New library entries can only be added through the
5640                            // system image.  This is important to get rid of a lot
5641                            // of nasty edge cases: for example if we allowed a non-
5642                            // system update of the app to add a library, then uninstalling
5643                            // the update would make the library go away, and assumptions
5644                            // we made such as through app install filtering would now
5645                            // have allowed apps on the device which aren't compatible
5646                            // with it.  Better to just have the restriction here, be
5647                            // conservative, and create many fewer cases that can negatively
5648                            // impact the user experience.
5649                            final PackageSetting sysPs = mSettings
5650                                    .getDisabledSystemPkgLPr(pkg.packageName);
5651                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5652                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5653                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5654                                        allowed = true;
5655                                        allowed = true;
5656                                        break;
5657                                    }
5658                                }
5659                            }
5660                        } else {
5661                            allowed = true;
5662                        }
5663                        if (allowed) {
5664                            if (!mSharedLibraries.containsKey(name)) {
5665                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5666                            } else if (!name.equals(pkg.packageName)) {
5667                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5668                                        + name + " already exists; skipping");
5669                            }
5670                        } else {
5671                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5672                                    + name + " that is not declared on system image; skipping");
5673                        }
5674                    }
5675                    if ((scanFlags&SCAN_BOOTING) == 0) {
5676                        // If we are not booting, we need to update any applications
5677                        // that are clients of our shared library.  If we are booting,
5678                        // this will all be done once the scan is complete.
5679                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5680                    }
5681                }
5682            }
5683        }
5684
5685        // We also need to dexopt any apps that are dependent on this library.  Note that
5686        // if these fail, we should abort the install since installing the library will
5687        // result in some apps being broken.
5688        if (clientLibPkgs != null) {
5689            if ((scanFlags & SCAN_NO_DEX) == 0) {
5690                for (int i = 0; i < clientLibPkgs.size(); i++) {
5691                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5692                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5693                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5694                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5695                                "scanPackageLI failed to dexopt clientLibPkgs");
5696                    }
5697                }
5698            }
5699        }
5700
5701        // Request the ActivityManager to kill the process(only for existing packages)
5702        // so that we do not end up in a confused state while the user is still using the older
5703        // version of the application while the new one gets installed.
5704        if ((scanFlags & SCAN_REPLACING) != 0) {
5705            killApplication(pkg.applicationInfo.packageName,
5706                        pkg.applicationInfo.uid, "update pkg");
5707        }
5708
5709        // Also need to kill any apps that are dependent on the library.
5710        if (clientLibPkgs != null) {
5711            for (int i=0; i<clientLibPkgs.size(); i++) {
5712                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5713                killApplication(clientPkg.applicationInfo.packageName,
5714                        clientPkg.applicationInfo.uid, "update lib");
5715            }
5716        }
5717
5718        // writer
5719        synchronized (mPackages) {
5720            // We don't expect installation to fail beyond this point
5721
5722            // Add the new setting to mSettings
5723            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5724            // Add the new setting to mPackages
5725            mPackages.put(pkg.applicationInfo.packageName, pkg);
5726            // Make sure we don't accidentally delete its data.
5727            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5728            while (iter.hasNext()) {
5729                PackageCleanItem item = iter.next();
5730                if (pkgName.equals(item.packageName)) {
5731                    iter.remove();
5732                }
5733            }
5734
5735            // Take care of first install / last update times.
5736            if (currentTime != 0) {
5737                if (pkgSetting.firstInstallTime == 0) {
5738                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5739                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5740                    pkgSetting.lastUpdateTime = currentTime;
5741                }
5742            } else if (pkgSetting.firstInstallTime == 0) {
5743                // We need *something*.  Take time time stamp of the file.
5744                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5745            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5746                if (scanFileTime != pkgSetting.timeStamp) {
5747                    // A package on the system image has changed; consider this
5748                    // to be an update.
5749                    pkgSetting.lastUpdateTime = scanFileTime;
5750                }
5751            }
5752
5753            // Add the package's KeySets to the global KeySetManagerService
5754            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5755            try {
5756                // Old KeySetData no longer valid.
5757                ksms.removeAppKeySetDataLPw(pkg.packageName);
5758                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5759                if (pkg.mKeySetMapping != null) {
5760                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5761                            pkg.mKeySetMapping.entrySet()) {
5762                        if (entry.getValue() != null) {
5763                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5764                                                          entry.getValue(), entry.getKey());
5765                        }
5766                    }
5767                    if (pkg.mUpgradeKeySets != null) {
5768                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5769                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5770                        }
5771                    }
5772                }
5773            } catch (NullPointerException e) {
5774                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5775            } catch (IllegalArgumentException e) {
5776                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5777            }
5778
5779            int N = pkg.providers.size();
5780            StringBuilder r = null;
5781            int i;
5782            for (i=0; i<N; i++) {
5783                PackageParser.Provider p = pkg.providers.get(i);
5784                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5785                        p.info.processName, pkg.applicationInfo.uid);
5786                mProviders.addProvider(p);
5787                p.syncable = p.info.isSyncable;
5788                if (p.info.authority != null) {
5789                    String names[] = p.info.authority.split(";");
5790                    p.info.authority = null;
5791                    for (int j = 0; j < names.length; j++) {
5792                        if (j == 1 && p.syncable) {
5793                            // We only want the first authority for a provider to possibly be
5794                            // syncable, so if we already added this provider using a different
5795                            // authority clear the syncable flag. We copy the provider before
5796                            // changing it because the mProviders object contains a reference
5797                            // to a provider that we don't want to change.
5798                            // Only do this for the second authority since the resulting provider
5799                            // object can be the same for all future authorities for this provider.
5800                            p = new PackageParser.Provider(p);
5801                            p.syncable = false;
5802                        }
5803                        if (!mProvidersByAuthority.containsKey(names[j])) {
5804                            mProvidersByAuthority.put(names[j], p);
5805                            if (p.info.authority == null) {
5806                                p.info.authority = names[j];
5807                            } else {
5808                                p.info.authority = p.info.authority + ";" + names[j];
5809                            }
5810                            if (DEBUG_PACKAGE_SCANNING) {
5811                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5812                                    Log.d(TAG, "Registered content provider: " + names[j]
5813                                            + ", className = " + p.info.name + ", isSyncable = "
5814                                            + p.info.isSyncable);
5815                            }
5816                        } else {
5817                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5818                            Slog.w(TAG, "Skipping provider name " + names[j] +
5819                                    " (in package " + pkg.applicationInfo.packageName +
5820                                    "): name already used by "
5821                                    + ((other != null && other.getComponentName() != null)
5822                                            ? other.getComponentName().getPackageName() : "?"));
5823                        }
5824                    }
5825                }
5826                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5827                    if (r == null) {
5828                        r = new StringBuilder(256);
5829                    } else {
5830                        r.append(' ');
5831                    }
5832                    r.append(p.info.name);
5833                }
5834            }
5835            if (r != null) {
5836                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5837            }
5838
5839            N = pkg.services.size();
5840            r = null;
5841            for (i=0; i<N; i++) {
5842                PackageParser.Service s = pkg.services.get(i);
5843                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5844                        s.info.processName, pkg.applicationInfo.uid);
5845                mServices.addService(s);
5846                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5847                    if (r == null) {
5848                        r = new StringBuilder(256);
5849                    } else {
5850                        r.append(' ');
5851                    }
5852                    r.append(s.info.name);
5853                }
5854            }
5855            if (r != null) {
5856                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5857            }
5858
5859            N = pkg.receivers.size();
5860            r = null;
5861            for (i=0; i<N; i++) {
5862                PackageParser.Activity a = pkg.receivers.get(i);
5863                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5864                        a.info.processName, pkg.applicationInfo.uid);
5865                mReceivers.addActivity(a, "receiver");
5866                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5867                    if (r == null) {
5868                        r = new StringBuilder(256);
5869                    } else {
5870                        r.append(' ');
5871                    }
5872                    r.append(a.info.name);
5873                }
5874            }
5875            if (r != null) {
5876                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5877            }
5878
5879            N = pkg.activities.size();
5880            r = null;
5881            for (i=0; i<N; i++) {
5882                PackageParser.Activity a = pkg.activities.get(i);
5883                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5884                        a.info.processName, pkg.applicationInfo.uid);
5885                mActivities.addActivity(a, "activity");
5886                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5887                    if (r == null) {
5888                        r = new StringBuilder(256);
5889                    } else {
5890                        r.append(' ');
5891                    }
5892                    r.append(a.info.name);
5893                }
5894            }
5895            if (r != null) {
5896                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5897            }
5898
5899            N = pkg.permissionGroups.size();
5900            r = null;
5901            for (i=0; i<N; i++) {
5902                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5903                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5904                if (cur == null) {
5905                    mPermissionGroups.put(pg.info.name, pg);
5906                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5907                        if (r == null) {
5908                            r = new StringBuilder(256);
5909                        } else {
5910                            r.append(' ');
5911                        }
5912                        r.append(pg.info.name);
5913                    }
5914                } else {
5915                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5916                            + pg.info.packageName + " ignored: original from "
5917                            + cur.info.packageName);
5918                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5919                        if (r == null) {
5920                            r = new StringBuilder(256);
5921                        } else {
5922                            r.append(' ');
5923                        }
5924                        r.append("DUP:");
5925                        r.append(pg.info.name);
5926                    }
5927                }
5928            }
5929            if (r != null) {
5930                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5931            }
5932
5933            N = pkg.permissions.size();
5934            r = null;
5935            for (i=0; i<N; i++) {
5936                PackageParser.Permission p = pkg.permissions.get(i);
5937                HashMap<String, BasePermission> permissionMap =
5938                        p.tree ? mSettings.mPermissionTrees
5939                        : mSettings.mPermissions;
5940                p.group = mPermissionGroups.get(p.info.group);
5941                if (p.info.group == null || p.group != null) {
5942                    BasePermission bp = permissionMap.get(p.info.name);
5943                    if (bp == null) {
5944                        bp = new BasePermission(p.info.name, p.info.packageName,
5945                                BasePermission.TYPE_NORMAL);
5946                        permissionMap.put(p.info.name, bp);
5947                    }
5948                    if (bp.perm == null) {
5949                        if (bp.sourcePackage != null
5950                                && !bp.sourcePackage.equals(p.info.packageName)) {
5951                            // If this is a permission that was formerly defined by a non-system
5952                            // app, but is now defined by a system app (following an upgrade),
5953                            // discard the previous declaration and consider the system's to be
5954                            // canonical.
5955                            if (isSystemApp(p.owner)) {
5956                                String msg = "New decl " + p.owner + " of permission  "
5957                                        + p.info.name + " is system";
5958                                reportSettingsProblem(Log.WARN, msg);
5959                                bp.sourcePackage = null;
5960                            }
5961                        }
5962                        if (bp.sourcePackage == null
5963                                || bp.sourcePackage.equals(p.info.packageName)) {
5964                            BasePermission tree = findPermissionTreeLP(p.info.name);
5965                            if (tree == null
5966                                    || tree.sourcePackage.equals(p.info.packageName)) {
5967                                bp.packageSetting = pkgSetting;
5968                                bp.perm = p;
5969                                bp.uid = pkg.applicationInfo.uid;
5970                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5971                                    if (r == null) {
5972                                        r = new StringBuilder(256);
5973                                    } else {
5974                                        r.append(' ');
5975                                    }
5976                                    r.append(p.info.name);
5977                                }
5978                            } else {
5979                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5980                                        + p.info.packageName + " ignored: base tree "
5981                                        + tree.name + " is from package "
5982                                        + tree.sourcePackage);
5983                            }
5984                        } else {
5985                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5986                                    + p.info.packageName + " ignored: original from "
5987                                    + bp.sourcePackage);
5988                        }
5989                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5990                        if (r == null) {
5991                            r = new StringBuilder(256);
5992                        } else {
5993                            r.append(' ');
5994                        }
5995                        r.append("DUP:");
5996                        r.append(p.info.name);
5997                    }
5998                    if (bp.perm == p) {
5999                        bp.protectionLevel = p.info.protectionLevel;
6000                    }
6001                } else {
6002                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6003                            + p.info.packageName + " ignored: no group "
6004                            + p.group);
6005                }
6006            }
6007            if (r != null) {
6008                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6009            }
6010
6011            N = pkg.instrumentation.size();
6012            r = null;
6013            for (i=0; i<N; i++) {
6014                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6015                a.info.packageName = pkg.applicationInfo.packageName;
6016                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6017                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6018                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6019                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6020                a.info.dataDir = pkg.applicationInfo.dataDir;
6021
6022                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6023                // need other information about the application, like the ABI and what not ?
6024                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6025                mInstrumentation.put(a.getComponentName(), a);
6026                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6027                    if (r == null) {
6028                        r = new StringBuilder(256);
6029                    } else {
6030                        r.append(' ');
6031                    }
6032                    r.append(a.info.name);
6033                }
6034            }
6035            if (r != null) {
6036                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6037            }
6038
6039            if (pkg.protectedBroadcasts != null) {
6040                N = pkg.protectedBroadcasts.size();
6041                for (i=0; i<N; i++) {
6042                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6043                }
6044            }
6045
6046            pkgSetting.setTimeStamp(scanFileTime);
6047
6048            // Create idmap files for pairs of (packages, overlay packages).
6049            // Note: "android", ie framework-res.apk, is handled by native layers.
6050            if (pkg.mOverlayTarget != null) {
6051                // This is an overlay package.
6052                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6053                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6054                        mOverlays.put(pkg.mOverlayTarget,
6055                                new HashMap<String, PackageParser.Package>());
6056                    }
6057                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6058                    map.put(pkg.packageName, pkg);
6059                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6060                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6061                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6062                                "scanPackageLI failed to createIdmap");
6063                    }
6064                }
6065            } else if (mOverlays.containsKey(pkg.packageName) &&
6066                    !pkg.packageName.equals("android")) {
6067                // This is a regular package, with one or more known overlay packages.
6068                createIdmapsForPackageLI(pkg);
6069            }
6070        }
6071
6072        return pkg;
6073    }
6074
6075    /**
6076     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6077     * i.e, so that all packages can be run inside a single process if required.
6078     *
6079     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6080     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6081     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6082     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6083     * updating a package that belongs to a shared user.
6084     *
6085     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6086     * adds unnecessary complexity.
6087     */
6088    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6089            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6090        String requiredInstructionSet = null;
6091        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6092            requiredInstructionSet = VMRuntime.getInstructionSet(
6093                     scannedPackage.applicationInfo.primaryCpuAbi);
6094        }
6095
6096        PackageSetting requirer = null;
6097        for (PackageSetting ps : packagesForUser) {
6098            // If packagesForUser contains scannedPackage, we skip it. This will happen
6099            // when scannedPackage is an update of an existing package. Without this check,
6100            // we will never be able to change the ABI of any package belonging to a shared
6101            // user, even if it's compatible with other packages.
6102            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6103                if (ps.primaryCpuAbiString == null) {
6104                    continue;
6105                }
6106
6107                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6108                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6109                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6110                    // this but there's not much we can do.
6111                    String errorMessage = "Instruction set mismatch, "
6112                            + ((requirer == null) ? "[caller]" : requirer)
6113                            + " requires " + requiredInstructionSet + " whereas " + ps
6114                            + " requires " + instructionSet;
6115                    Slog.w(TAG, errorMessage);
6116                }
6117
6118                if (requiredInstructionSet == null) {
6119                    requiredInstructionSet = instructionSet;
6120                    requirer = ps;
6121                }
6122            }
6123        }
6124
6125        if (requiredInstructionSet != null) {
6126            String adjustedAbi;
6127            if (requirer != null) {
6128                // requirer != null implies that either scannedPackage was null or that scannedPackage
6129                // did not require an ABI, in which case we have to adjust scannedPackage to match
6130                // the ABI of the set (which is the same as requirer's ABI)
6131                adjustedAbi = requirer.primaryCpuAbiString;
6132                if (scannedPackage != null) {
6133                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6134                }
6135            } else {
6136                // requirer == null implies that we're updating all ABIs in the set to
6137                // match scannedPackage.
6138                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6139            }
6140
6141            for (PackageSetting ps : packagesForUser) {
6142                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6143                    if (ps.primaryCpuAbiString != null) {
6144                        continue;
6145                    }
6146
6147                    ps.primaryCpuAbiString = adjustedAbi;
6148                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6149                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6150                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6151
6152                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6153                                deferDexOpt, true) == DEX_OPT_FAILED) {
6154                            ps.primaryCpuAbiString = null;
6155                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6156                            return;
6157                        } else {
6158                            mInstaller.rmdex(ps.codePathString,
6159                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6160                        }
6161                    }
6162                }
6163            }
6164        }
6165    }
6166
6167    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6168        synchronized (mPackages) {
6169            mResolverReplaced = true;
6170            // Set up information for custom user intent resolution activity.
6171            mResolveActivity.applicationInfo = pkg.applicationInfo;
6172            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6173            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6174            mResolveActivity.processName = null;
6175            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6176            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6177                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6178            mResolveActivity.theme = 0;
6179            mResolveActivity.exported = true;
6180            mResolveActivity.enabled = true;
6181            mResolveInfo.activityInfo = mResolveActivity;
6182            mResolveInfo.priority = 0;
6183            mResolveInfo.preferredOrder = 0;
6184            mResolveInfo.match = 0;
6185            mResolveComponentName = mCustomResolverComponentName;
6186            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6187                    mResolveComponentName);
6188        }
6189    }
6190
6191    private static String calculateBundledApkRoot(final String codePathString) {
6192        final File codePath = new File(codePathString);
6193        final File codeRoot;
6194        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6195            codeRoot = Environment.getRootDirectory();
6196        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6197            codeRoot = Environment.getOemDirectory();
6198        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6199            codeRoot = Environment.getVendorDirectory();
6200        } else {
6201            // Unrecognized code path; take its top real segment as the apk root:
6202            // e.g. /something/app/blah.apk => /something
6203            try {
6204                File f = codePath.getCanonicalFile();
6205                File parent = f.getParentFile();    // non-null because codePath is a file
6206                File tmp;
6207                while ((tmp = parent.getParentFile()) != null) {
6208                    f = parent;
6209                    parent = tmp;
6210                }
6211                codeRoot = f;
6212                Slog.w(TAG, "Unrecognized code path "
6213                        + codePath + " - using " + codeRoot);
6214            } catch (IOException e) {
6215                // Can't canonicalize the code path -- shenanigans?
6216                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6217                return Environment.getRootDirectory().getPath();
6218            }
6219        }
6220        return codeRoot.getPath();
6221    }
6222
6223    /**
6224     * Derive and set the location of native libraries for the given package,
6225     * which varies depending on where and how the package was installed.
6226     */
6227    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6228        final ApplicationInfo info = pkg.applicationInfo;
6229        final String codePath = pkg.codePath;
6230        final File codeFile = new File(codePath);
6231        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6232        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6233
6234        info.nativeLibraryRootDir = null;
6235        info.nativeLibraryRootRequiresIsa = false;
6236        info.nativeLibraryDir = null;
6237        info.secondaryNativeLibraryDir = null;
6238
6239        if (isApkFile(codeFile)) {
6240            // Monolithic install
6241            if (bundledApp) {
6242                // If "/system/lib64/apkname" exists, assume that is the per-package
6243                // native library directory to use; otherwise use "/system/lib/apkname".
6244                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6245                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6246                        getPrimaryInstructionSet(info));
6247
6248                // This is a bundled system app so choose the path based on the ABI.
6249                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6250                // is just the default path.
6251                final String apkName = deriveCodePathName(codePath);
6252                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6253                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6254                        apkName).getAbsolutePath();
6255
6256                if (info.secondaryCpuAbi != null) {
6257                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6258                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6259                            secondaryLibDir, apkName).getAbsolutePath();
6260                }
6261            } else if (asecApp) {
6262                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6263                        .getAbsolutePath();
6264            } else {
6265                final String apkName = deriveCodePathName(codePath);
6266                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6267                        .getAbsolutePath();
6268            }
6269
6270            info.nativeLibraryRootRequiresIsa = false;
6271            info.nativeLibraryDir = info.nativeLibraryRootDir;
6272        } else {
6273            // Cluster install
6274            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6275            info.nativeLibraryRootRequiresIsa = true;
6276
6277            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6278                    getPrimaryInstructionSet(info)).getAbsolutePath();
6279
6280            if (info.secondaryCpuAbi != null) {
6281                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6282                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6283            }
6284        }
6285    }
6286
6287    /**
6288     * Calculate the abis and roots for a bundled app. These can uniquely
6289     * be determined from the contents of the system partition, i.e whether
6290     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6291     * of this information, and instead assume that the system was built
6292     * sensibly.
6293     */
6294    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6295                                           PackageSetting pkgSetting) {
6296        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6297
6298        // If "/system/lib64/apkname" exists, assume that is the per-package
6299        // native library directory to use; otherwise use "/system/lib/apkname".
6300        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6301        setBundledAppAbi(pkg, apkRoot, apkName);
6302        // pkgSetting might be null during rescan following uninstall of updates
6303        // to a bundled app, so accommodate that possibility.  The settings in
6304        // that case will be established later from the parsed package.
6305        //
6306        // If the settings aren't null, sync them up with what we've just derived.
6307        // note that apkRoot isn't stored in the package settings.
6308        if (pkgSetting != null) {
6309            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6310            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6311        }
6312    }
6313
6314    /**
6315     * Deduces the ABI of a bundled app and sets the relevant fields on the
6316     * parsed pkg object.
6317     *
6318     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6319     *        under which system libraries are installed.
6320     * @param apkName the name of the installed package.
6321     */
6322    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6323        final File codeFile = new File(pkg.codePath);
6324
6325        final boolean has64BitLibs;
6326        final boolean has32BitLibs;
6327        if (isApkFile(codeFile)) {
6328            // Monolithic install
6329            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6330            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6331        } else {
6332            // Cluster install
6333            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6334            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6335                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6336                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6337                has64BitLibs = (new File(rootDir, isa)).exists();
6338            } else {
6339                has64BitLibs = false;
6340            }
6341            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6342                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6343                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6344                has32BitLibs = (new File(rootDir, isa)).exists();
6345            } else {
6346                has32BitLibs = false;
6347            }
6348        }
6349
6350        if (has64BitLibs && !has32BitLibs) {
6351            // The package has 64 bit libs, but not 32 bit libs. Its primary
6352            // ABI should be 64 bit. We can safely assume here that the bundled
6353            // native libraries correspond to the most preferred ABI in the list.
6354
6355            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6356            pkg.applicationInfo.secondaryCpuAbi = null;
6357        } else if (has32BitLibs && !has64BitLibs) {
6358            // The package has 32 bit libs but not 64 bit libs. Its primary
6359            // ABI should be 32 bit.
6360
6361            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6362            pkg.applicationInfo.secondaryCpuAbi = null;
6363        } else if (has32BitLibs && has64BitLibs) {
6364            // The application has both 64 and 32 bit bundled libraries. We check
6365            // here that the app declares multiArch support, and warn if it doesn't.
6366            //
6367            // We will be lenient here and record both ABIs. The primary will be the
6368            // ABI that's higher on the list, i.e, a device that's configured to prefer
6369            // 64 bit apps will see a 64 bit primary ABI,
6370
6371            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6372                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6373            }
6374
6375            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6376                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6377                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6378            } else {
6379                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6380                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6381            }
6382        } else {
6383            pkg.applicationInfo.primaryCpuAbi = null;
6384            pkg.applicationInfo.secondaryCpuAbi = null;
6385        }
6386    }
6387
6388    private void killApplication(String pkgName, int appId, String reason) {
6389        // Request the ActivityManager to kill the process(only for existing packages)
6390        // so that we do not end up in a confused state while the user is still using the older
6391        // version of the application while the new one gets installed.
6392        IActivityManager am = ActivityManagerNative.getDefault();
6393        if (am != null) {
6394            try {
6395                am.killApplicationWithAppId(pkgName, appId, reason);
6396            } catch (RemoteException e) {
6397            }
6398        }
6399    }
6400
6401    void removePackageLI(PackageSetting ps, boolean chatty) {
6402        if (DEBUG_INSTALL) {
6403            if (chatty)
6404                Log.d(TAG, "Removing package " + ps.name);
6405        }
6406
6407        // writer
6408        synchronized (mPackages) {
6409            mPackages.remove(ps.name);
6410            final PackageParser.Package pkg = ps.pkg;
6411            if (pkg != null) {
6412                cleanPackageDataStructuresLILPw(pkg, chatty);
6413            }
6414        }
6415    }
6416
6417    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6418        if (DEBUG_INSTALL) {
6419            if (chatty)
6420                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6421        }
6422
6423        // writer
6424        synchronized (mPackages) {
6425            mPackages.remove(pkg.applicationInfo.packageName);
6426            cleanPackageDataStructuresLILPw(pkg, chatty);
6427        }
6428    }
6429
6430    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6431        int N = pkg.providers.size();
6432        StringBuilder r = null;
6433        int i;
6434        for (i=0; i<N; i++) {
6435            PackageParser.Provider p = pkg.providers.get(i);
6436            mProviders.removeProvider(p);
6437            if (p.info.authority == null) {
6438
6439                /* There was another ContentProvider with this authority when
6440                 * this app was installed so this authority is null,
6441                 * Ignore it as we don't have to unregister the provider.
6442                 */
6443                continue;
6444            }
6445            String names[] = p.info.authority.split(";");
6446            for (int j = 0; j < names.length; j++) {
6447                if (mProvidersByAuthority.get(names[j]) == p) {
6448                    mProvidersByAuthority.remove(names[j]);
6449                    if (DEBUG_REMOVE) {
6450                        if (chatty)
6451                            Log.d(TAG, "Unregistered content provider: " + names[j]
6452                                    + ", className = " + p.info.name + ", isSyncable = "
6453                                    + p.info.isSyncable);
6454                    }
6455                }
6456            }
6457            if (DEBUG_REMOVE && chatty) {
6458                if (r == null) {
6459                    r = new StringBuilder(256);
6460                } else {
6461                    r.append(' ');
6462                }
6463                r.append(p.info.name);
6464            }
6465        }
6466        if (r != null) {
6467            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6468        }
6469
6470        N = pkg.services.size();
6471        r = null;
6472        for (i=0; i<N; i++) {
6473            PackageParser.Service s = pkg.services.get(i);
6474            mServices.removeService(s);
6475            if (chatty) {
6476                if (r == null) {
6477                    r = new StringBuilder(256);
6478                } else {
6479                    r.append(' ');
6480                }
6481                r.append(s.info.name);
6482            }
6483        }
6484        if (r != null) {
6485            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6486        }
6487
6488        N = pkg.receivers.size();
6489        r = null;
6490        for (i=0; i<N; i++) {
6491            PackageParser.Activity a = pkg.receivers.get(i);
6492            mReceivers.removeActivity(a, "receiver");
6493            if (DEBUG_REMOVE && chatty) {
6494                if (r == null) {
6495                    r = new StringBuilder(256);
6496                } else {
6497                    r.append(' ');
6498                }
6499                r.append(a.info.name);
6500            }
6501        }
6502        if (r != null) {
6503            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6504        }
6505
6506        N = pkg.activities.size();
6507        r = null;
6508        for (i=0; i<N; i++) {
6509            PackageParser.Activity a = pkg.activities.get(i);
6510            mActivities.removeActivity(a, "activity");
6511            if (DEBUG_REMOVE && chatty) {
6512                if (r == null) {
6513                    r = new StringBuilder(256);
6514                } else {
6515                    r.append(' ');
6516                }
6517                r.append(a.info.name);
6518            }
6519        }
6520        if (r != null) {
6521            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6522        }
6523
6524        N = pkg.permissions.size();
6525        r = null;
6526        for (i=0; i<N; i++) {
6527            PackageParser.Permission p = pkg.permissions.get(i);
6528            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6529            if (bp == null) {
6530                bp = mSettings.mPermissionTrees.get(p.info.name);
6531            }
6532            if (bp != null && bp.perm == p) {
6533                bp.perm = null;
6534                if (DEBUG_REMOVE && chatty) {
6535                    if (r == null) {
6536                        r = new StringBuilder(256);
6537                    } else {
6538                        r.append(' ');
6539                    }
6540                    r.append(p.info.name);
6541                }
6542            }
6543            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6544                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6545                if (appOpPerms != null) {
6546                    appOpPerms.remove(pkg.packageName);
6547                }
6548            }
6549        }
6550        if (r != null) {
6551            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6552        }
6553
6554        N = pkg.requestedPermissions.size();
6555        r = null;
6556        for (i=0; i<N; i++) {
6557            String perm = pkg.requestedPermissions.get(i);
6558            BasePermission bp = mSettings.mPermissions.get(perm);
6559            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6560                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6561                if (appOpPerms != null) {
6562                    appOpPerms.remove(pkg.packageName);
6563                    if (appOpPerms.isEmpty()) {
6564                        mAppOpPermissionPackages.remove(perm);
6565                    }
6566                }
6567            }
6568        }
6569        if (r != null) {
6570            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6571        }
6572
6573        N = pkg.instrumentation.size();
6574        r = null;
6575        for (i=0; i<N; i++) {
6576            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6577            mInstrumentation.remove(a.getComponentName());
6578            if (DEBUG_REMOVE && chatty) {
6579                if (r == null) {
6580                    r = new StringBuilder(256);
6581                } else {
6582                    r.append(' ');
6583                }
6584                r.append(a.info.name);
6585            }
6586        }
6587        if (r != null) {
6588            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6589        }
6590
6591        r = null;
6592        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6593            // Only system apps can hold shared libraries.
6594            if (pkg.libraryNames != null) {
6595                for (i=0; i<pkg.libraryNames.size(); i++) {
6596                    String name = pkg.libraryNames.get(i);
6597                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6598                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6599                        mSharedLibraries.remove(name);
6600                        if (DEBUG_REMOVE && chatty) {
6601                            if (r == null) {
6602                                r = new StringBuilder(256);
6603                            } else {
6604                                r.append(' ');
6605                            }
6606                            r.append(name);
6607                        }
6608                    }
6609                }
6610            }
6611        }
6612        if (r != null) {
6613            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6614        }
6615    }
6616
6617    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6618        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6619            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6620                return true;
6621            }
6622        }
6623        return false;
6624    }
6625
6626    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6627    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6628    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6629
6630    private void updatePermissionsLPw(String changingPkg,
6631            PackageParser.Package pkgInfo, int flags) {
6632        // Make sure there are no dangling permission trees.
6633        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6634        while (it.hasNext()) {
6635            final BasePermission bp = it.next();
6636            if (bp.packageSetting == null) {
6637                // We may not yet have parsed the package, so just see if
6638                // we still know about its settings.
6639                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6640            }
6641            if (bp.packageSetting == null) {
6642                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6643                        + " from package " + bp.sourcePackage);
6644                it.remove();
6645            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6646                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6647                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6648                            + " from package " + bp.sourcePackage);
6649                    flags |= UPDATE_PERMISSIONS_ALL;
6650                    it.remove();
6651                }
6652            }
6653        }
6654
6655        // Make sure all dynamic permissions have been assigned to a package,
6656        // and make sure there are no dangling permissions.
6657        it = mSettings.mPermissions.values().iterator();
6658        while (it.hasNext()) {
6659            final BasePermission bp = it.next();
6660            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6661                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6662                        + bp.name + " pkg=" + bp.sourcePackage
6663                        + " info=" + bp.pendingInfo);
6664                if (bp.packageSetting == null && bp.pendingInfo != null) {
6665                    final BasePermission tree = findPermissionTreeLP(bp.name);
6666                    if (tree != null && tree.perm != null) {
6667                        bp.packageSetting = tree.packageSetting;
6668                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6669                                new PermissionInfo(bp.pendingInfo));
6670                        bp.perm.info.packageName = tree.perm.info.packageName;
6671                        bp.perm.info.name = bp.name;
6672                        bp.uid = tree.uid;
6673                    }
6674                }
6675            }
6676            if (bp.packageSetting == null) {
6677                // We may not yet have parsed the package, so just see if
6678                // we still know about its settings.
6679                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6680            }
6681            if (bp.packageSetting == null) {
6682                Slog.w(TAG, "Removing dangling permission: " + bp.name
6683                        + " from package " + bp.sourcePackage);
6684                it.remove();
6685            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6686                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6687                    Slog.i(TAG, "Removing old permission: " + bp.name
6688                            + " from package " + bp.sourcePackage);
6689                    flags |= UPDATE_PERMISSIONS_ALL;
6690                    it.remove();
6691                }
6692            }
6693        }
6694
6695        // Now update the permissions for all packages, in particular
6696        // replace the granted permissions of the system packages.
6697        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6698            for (PackageParser.Package pkg : mPackages.values()) {
6699                if (pkg != pkgInfo) {
6700                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6701                            changingPkg);
6702                }
6703            }
6704        }
6705
6706        if (pkgInfo != null) {
6707            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6708        }
6709    }
6710
6711    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6712            String packageOfInterest) {
6713        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6714        if (ps == null) {
6715            return;
6716        }
6717        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6718        HashSet<String> origPermissions = gp.grantedPermissions;
6719        boolean changedPermission = false;
6720
6721        if (replace) {
6722            ps.permissionsFixed = false;
6723            if (gp == ps) {
6724                origPermissions = new HashSet<String>(gp.grantedPermissions);
6725                gp.grantedPermissions.clear();
6726                gp.gids = mGlobalGids;
6727            }
6728        }
6729
6730        if (gp.gids == null) {
6731            gp.gids = mGlobalGids;
6732        }
6733
6734        final int N = pkg.requestedPermissions.size();
6735        for (int i=0; i<N; i++) {
6736            final String name = pkg.requestedPermissions.get(i);
6737            final boolean required = pkg.requestedPermissionsRequired.get(i);
6738            final BasePermission bp = mSettings.mPermissions.get(name);
6739            if (DEBUG_INSTALL) {
6740                if (gp != ps) {
6741                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6742                }
6743            }
6744
6745            if (bp == null || bp.packageSetting == null) {
6746                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6747                    Slog.w(TAG, "Unknown permission " + name
6748                            + " in package " + pkg.packageName);
6749                }
6750                continue;
6751            }
6752
6753            final String perm = bp.name;
6754            boolean allowed;
6755            boolean allowedSig = false;
6756            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6757                // Keep track of app op permissions.
6758                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6759                if (pkgs == null) {
6760                    pkgs = new ArraySet<>();
6761                    mAppOpPermissionPackages.put(bp.name, pkgs);
6762                }
6763                pkgs.add(pkg.packageName);
6764            }
6765            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6766            if (level == PermissionInfo.PROTECTION_NORMAL
6767                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6768                // We grant a normal or dangerous permission if any of the following
6769                // are true:
6770                // 1) The permission is required
6771                // 2) The permission is optional, but was granted in the past
6772                // 3) The permission is optional, but was requested by an
6773                //    app in /system (not /data)
6774                //
6775                // Otherwise, reject the permission.
6776                allowed = (required || origPermissions.contains(perm)
6777                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6778            } else if (bp.packageSetting == null) {
6779                // This permission is invalid; skip it.
6780                allowed = false;
6781            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6782                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6783                if (allowed) {
6784                    allowedSig = true;
6785                }
6786            } else {
6787                allowed = false;
6788            }
6789            if (DEBUG_INSTALL) {
6790                if (gp != ps) {
6791                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6792                }
6793            }
6794            if (allowed) {
6795                if (!isSystemApp(ps) && ps.permissionsFixed) {
6796                    // If this is an existing, non-system package, then
6797                    // we can't add any new permissions to it.
6798                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6799                        // Except...  if this is a permission that was added
6800                        // to the platform (note: need to only do this when
6801                        // updating the platform).
6802                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6803                    }
6804                }
6805                if (allowed) {
6806                    if (!gp.grantedPermissions.contains(perm)) {
6807                        changedPermission = true;
6808                        gp.grantedPermissions.add(perm);
6809                        gp.gids = appendInts(gp.gids, bp.gids);
6810                    } else if (!ps.haveGids) {
6811                        gp.gids = appendInts(gp.gids, bp.gids);
6812                    }
6813                } else {
6814                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6815                        Slog.w(TAG, "Not granting permission " + perm
6816                                + " to package " + pkg.packageName
6817                                + " because it was previously installed without");
6818                    }
6819                }
6820            } else {
6821                if (gp.grantedPermissions.remove(perm)) {
6822                    changedPermission = true;
6823                    gp.gids = removeInts(gp.gids, bp.gids);
6824                    Slog.i(TAG, "Un-granting permission " + perm
6825                            + " from package " + pkg.packageName
6826                            + " (protectionLevel=" + bp.protectionLevel
6827                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6828                            + ")");
6829                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6830                    // Don't print warning for app op permissions, since it is fine for them
6831                    // not to be granted, there is a UI for the user to decide.
6832                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6833                        Slog.w(TAG, "Not granting permission " + perm
6834                                + " to package " + pkg.packageName
6835                                + " (protectionLevel=" + bp.protectionLevel
6836                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6837                                + ")");
6838                    }
6839                }
6840            }
6841        }
6842
6843        if ((changedPermission || replace) && !ps.permissionsFixed &&
6844                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6845            // This is the first that we have heard about this package, so the
6846            // permissions we have now selected are fixed until explicitly
6847            // changed.
6848            ps.permissionsFixed = true;
6849        }
6850        ps.haveGids = true;
6851    }
6852
6853    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6854        boolean allowed = false;
6855        final int NP = PackageParser.NEW_PERMISSIONS.length;
6856        for (int ip=0; ip<NP; ip++) {
6857            final PackageParser.NewPermissionInfo npi
6858                    = PackageParser.NEW_PERMISSIONS[ip];
6859            if (npi.name.equals(perm)
6860                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6861                allowed = true;
6862                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6863                        + pkg.packageName);
6864                break;
6865            }
6866        }
6867        return allowed;
6868    }
6869
6870    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6871                                          BasePermission bp, HashSet<String> origPermissions) {
6872        boolean allowed;
6873        allowed = (compareSignatures(
6874                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6875                        == PackageManager.SIGNATURE_MATCH)
6876                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6877                        == PackageManager.SIGNATURE_MATCH);
6878        if (!allowed && (bp.protectionLevel
6879                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6880            if (isSystemApp(pkg)) {
6881                // For updated system applications, a system permission
6882                // is granted only if it had been defined by the original application.
6883                if (isUpdatedSystemApp(pkg)) {
6884                    final PackageSetting sysPs = mSettings
6885                            .getDisabledSystemPkgLPr(pkg.packageName);
6886                    final GrantedPermissions origGp = sysPs.sharedUser != null
6887                            ? sysPs.sharedUser : sysPs;
6888
6889                    if (origGp.grantedPermissions.contains(perm)) {
6890                        // If the original was granted this permission, we take
6891                        // that grant decision as read and propagate it to the
6892                        // update.
6893                        allowed = true;
6894                    } else {
6895                        // The system apk may have been updated with an older
6896                        // version of the one on the data partition, but which
6897                        // granted a new system permission that it didn't have
6898                        // before.  In this case we do want to allow the app to
6899                        // now get the new permission if the ancestral apk is
6900                        // privileged to get it.
6901                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6902                            for (int j=0;
6903                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6904                                if (perm.equals(
6905                                        sysPs.pkg.requestedPermissions.get(j))) {
6906                                    allowed = true;
6907                                    break;
6908                                }
6909                            }
6910                        }
6911                    }
6912                } else {
6913                    allowed = isPrivilegedApp(pkg);
6914                }
6915            }
6916        }
6917        if (!allowed && (bp.protectionLevel
6918                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6919            // For development permissions, a development permission
6920            // is granted only if it was already granted.
6921            allowed = origPermissions.contains(perm);
6922        }
6923        return allowed;
6924    }
6925
6926    final class ActivityIntentResolver
6927            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6928        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6929                boolean defaultOnly, int userId) {
6930            if (!sUserManager.exists(userId)) return null;
6931            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6932            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6933        }
6934
6935        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6936                int userId) {
6937            if (!sUserManager.exists(userId)) return null;
6938            mFlags = flags;
6939            return super.queryIntent(intent, resolvedType,
6940                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6941        }
6942
6943        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6944                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6945            if (!sUserManager.exists(userId)) return null;
6946            if (packageActivities == null) {
6947                return null;
6948            }
6949            mFlags = flags;
6950            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6951            final int N = packageActivities.size();
6952            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6953                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6954
6955            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6956            for (int i = 0; i < N; ++i) {
6957                intentFilters = packageActivities.get(i).intents;
6958                if (intentFilters != null && intentFilters.size() > 0) {
6959                    PackageParser.ActivityIntentInfo[] array =
6960                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6961                    intentFilters.toArray(array);
6962                    listCut.add(array);
6963                }
6964            }
6965            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6966        }
6967
6968        public final void addActivity(PackageParser.Activity a, String type) {
6969            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6970            mActivities.put(a.getComponentName(), a);
6971            if (DEBUG_SHOW_INFO)
6972                Log.v(
6973                TAG, "  " + type + " " +
6974                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6975            if (DEBUG_SHOW_INFO)
6976                Log.v(TAG, "    Class=" + a.info.name);
6977            final int NI = a.intents.size();
6978            for (int j=0; j<NI; j++) {
6979                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6980                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6981                    intent.setPriority(0);
6982                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6983                            + a.className + " with priority > 0, forcing to 0");
6984                }
6985                if (DEBUG_SHOW_INFO) {
6986                    Log.v(TAG, "    IntentFilter:");
6987                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6988                }
6989                if (!intent.debugCheck()) {
6990                    Log.w(TAG, "==> For Activity " + a.info.name);
6991                }
6992                addFilter(intent);
6993            }
6994        }
6995
6996        public final void removeActivity(PackageParser.Activity a, String type) {
6997            mActivities.remove(a.getComponentName());
6998            if (DEBUG_SHOW_INFO) {
6999                Log.v(TAG, "  " + type + " "
7000                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7001                                : a.info.name) + ":");
7002                Log.v(TAG, "    Class=" + a.info.name);
7003            }
7004            final int NI = a.intents.size();
7005            for (int j=0; j<NI; j++) {
7006                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7007                if (DEBUG_SHOW_INFO) {
7008                    Log.v(TAG, "    IntentFilter:");
7009                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7010                }
7011                removeFilter(intent);
7012            }
7013        }
7014
7015        @Override
7016        protected boolean allowFilterResult(
7017                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7018            ActivityInfo filterAi = filter.activity.info;
7019            for (int i=dest.size()-1; i>=0; i--) {
7020                ActivityInfo destAi = dest.get(i).activityInfo;
7021                if (destAi.name == filterAi.name
7022                        && destAi.packageName == filterAi.packageName) {
7023                    return false;
7024                }
7025            }
7026            return true;
7027        }
7028
7029        @Override
7030        protected ActivityIntentInfo[] newArray(int size) {
7031            return new ActivityIntentInfo[size];
7032        }
7033
7034        @Override
7035        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7036            if (!sUserManager.exists(userId)) return true;
7037            PackageParser.Package p = filter.activity.owner;
7038            if (p != null) {
7039                PackageSetting ps = (PackageSetting)p.mExtras;
7040                if (ps != null) {
7041                    // System apps are never considered stopped for purposes of
7042                    // filtering, because there may be no way for the user to
7043                    // actually re-launch them.
7044                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7045                            && ps.getStopped(userId);
7046                }
7047            }
7048            return false;
7049        }
7050
7051        @Override
7052        protected boolean isPackageForFilter(String packageName,
7053                PackageParser.ActivityIntentInfo info) {
7054            return packageName.equals(info.activity.owner.packageName);
7055        }
7056
7057        @Override
7058        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7059                int match, int userId) {
7060            if (!sUserManager.exists(userId)) return null;
7061            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7062                return null;
7063            }
7064            final PackageParser.Activity activity = info.activity;
7065            if (mSafeMode && (activity.info.applicationInfo.flags
7066                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7067                return null;
7068            }
7069            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7070            if (ps == null) {
7071                return null;
7072            }
7073            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7074                    ps.readUserState(userId), userId);
7075            if (ai == null) {
7076                return null;
7077            }
7078            final ResolveInfo res = new ResolveInfo();
7079            res.activityInfo = ai;
7080            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7081                res.filter = info;
7082            }
7083            res.priority = info.getPriority();
7084            res.preferredOrder = activity.owner.mPreferredOrder;
7085            //System.out.println("Result: " + res.activityInfo.className +
7086            //                   " = " + res.priority);
7087            res.match = match;
7088            res.isDefault = info.hasDefault;
7089            res.labelRes = info.labelRes;
7090            res.nonLocalizedLabel = info.nonLocalizedLabel;
7091            if (userNeedsBadging(userId)) {
7092                res.noResourceId = true;
7093            } else {
7094                res.icon = info.icon;
7095            }
7096            res.system = isSystemApp(res.activityInfo.applicationInfo);
7097            return res;
7098        }
7099
7100        @Override
7101        protected void sortResults(List<ResolveInfo> results) {
7102            Collections.sort(results, mResolvePrioritySorter);
7103        }
7104
7105        @Override
7106        protected void dumpFilter(PrintWriter out, String prefix,
7107                PackageParser.ActivityIntentInfo filter) {
7108            out.print(prefix); out.print(
7109                    Integer.toHexString(System.identityHashCode(filter.activity)));
7110                    out.print(' ');
7111                    filter.activity.printComponentShortName(out);
7112                    out.print(" filter ");
7113                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7114        }
7115
7116//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7117//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7118//            final List<ResolveInfo> retList = Lists.newArrayList();
7119//            while (i.hasNext()) {
7120//                final ResolveInfo resolveInfo = i.next();
7121//                if (isEnabledLP(resolveInfo.activityInfo)) {
7122//                    retList.add(resolveInfo);
7123//                }
7124//            }
7125//            return retList;
7126//        }
7127
7128        // Keys are String (activity class name), values are Activity.
7129        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7130                = new HashMap<ComponentName, PackageParser.Activity>();
7131        private int mFlags;
7132    }
7133
7134    private final class ServiceIntentResolver
7135            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7136        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7137                boolean defaultOnly, int userId) {
7138            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7139            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7140        }
7141
7142        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7143                int userId) {
7144            if (!sUserManager.exists(userId)) return null;
7145            mFlags = flags;
7146            return super.queryIntent(intent, resolvedType,
7147                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7148        }
7149
7150        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7151                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7152            if (!sUserManager.exists(userId)) return null;
7153            if (packageServices == null) {
7154                return null;
7155            }
7156            mFlags = flags;
7157            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7158            final int N = packageServices.size();
7159            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7160                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7161
7162            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7163            for (int i = 0; i < N; ++i) {
7164                intentFilters = packageServices.get(i).intents;
7165                if (intentFilters != null && intentFilters.size() > 0) {
7166                    PackageParser.ServiceIntentInfo[] array =
7167                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7168                    intentFilters.toArray(array);
7169                    listCut.add(array);
7170                }
7171            }
7172            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7173        }
7174
7175        public final void addService(PackageParser.Service s) {
7176            mServices.put(s.getComponentName(), s);
7177            if (DEBUG_SHOW_INFO) {
7178                Log.v(TAG, "  "
7179                        + (s.info.nonLocalizedLabel != null
7180                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7181                Log.v(TAG, "    Class=" + s.info.name);
7182            }
7183            final int NI = s.intents.size();
7184            int j;
7185            for (j=0; j<NI; j++) {
7186                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7187                if (DEBUG_SHOW_INFO) {
7188                    Log.v(TAG, "    IntentFilter:");
7189                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7190                }
7191                if (!intent.debugCheck()) {
7192                    Log.w(TAG, "==> For Service " + s.info.name);
7193                }
7194                addFilter(intent);
7195            }
7196        }
7197
7198        public final void removeService(PackageParser.Service s) {
7199            mServices.remove(s.getComponentName());
7200            if (DEBUG_SHOW_INFO) {
7201                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7202                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7203                Log.v(TAG, "    Class=" + s.info.name);
7204            }
7205            final int NI = s.intents.size();
7206            int j;
7207            for (j=0; j<NI; j++) {
7208                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7209                if (DEBUG_SHOW_INFO) {
7210                    Log.v(TAG, "    IntentFilter:");
7211                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7212                }
7213                removeFilter(intent);
7214            }
7215        }
7216
7217        @Override
7218        protected boolean allowFilterResult(
7219                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7220            ServiceInfo filterSi = filter.service.info;
7221            for (int i=dest.size()-1; i>=0; i--) {
7222                ServiceInfo destAi = dest.get(i).serviceInfo;
7223                if (destAi.name == filterSi.name
7224                        && destAi.packageName == filterSi.packageName) {
7225                    return false;
7226                }
7227            }
7228            return true;
7229        }
7230
7231        @Override
7232        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7233            return new PackageParser.ServiceIntentInfo[size];
7234        }
7235
7236        @Override
7237        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7238            if (!sUserManager.exists(userId)) return true;
7239            PackageParser.Package p = filter.service.owner;
7240            if (p != null) {
7241                PackageSetting ps = (PackageSetting)p.mExtras;
7242                if (ps != null) {
7243                    // System apps are never considered stopped for purposes of
7244                    // filtering, because there may be no way for the user to
7245                    // actually re-launch them.
7246                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7247                            && ps.getStopped(userId);
7248                }
7249            }
7250            return false;
7251        }
7252
7253        @Override
7254        protected boolean isPackageForFilter(String packageName,
7255                PackageParser.ServiceIntentInfo info) {
7256            return packageName.equals(info.service.owner.packageName);
7257        }
7258
7259        @Override
7260        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7261                int match, int userId) {
7262            if (!sUserManager.exists(userId)) return null;
7263            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7264            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7265                return null;
7266            }
7267            final PackageParser.Service service = info.service;
7268            if (mSafeMode && (service.info.applicationInfo.flags
7269                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7270                return null;
7271            }
7272            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7273            if (ps == null) {
7274                return null;
7275            }
7276            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7277                    ps.readUserState(userId), userId);
7278            if (si == null) {
7279                return null;
7280            }
7281            final ResolveInfo res = new ResolveInfo();
7282            res.serviceInfo = si;
7283            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7284                res.filter = filter;
7285            }
7286            res.priority = info.getPriority();
7287            res.preferredOrder = service.owner.mPreferredOrder;
7288            //System.out.println("Result: " + res.activityInfo.className +
7289            //                   " = " + res.priority);
7290            res.match = match;
7291            res.isDefault = info.hasDefault;
7292            res.labelRes = info.labelRes;
7293            res.nonLocalizedLabel = info.nonLocalizedLabel;
7294            res.icon = info.icon;
7295            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7296            return res;
7297        }
7298
7299        @Override
7300        protected void sortResults(List<ResolveInfo> results) {
7301            Collections.sort(results, mResolvePrioritySorter);
7302        }
7303
7304        @Override
7305        protected void dumpFilter(PrintWriter out, String prefix,
7306                PackageParser.ServiceIntentInfo filter) {
7307            out.print(prefix); out.print(
7308                    Integer.toHexString(System.identityHashCode(filter.service)));
7309                    out.print(' ');
7310                    filter.service.printComponentShortName(out);
7311                    out.print(" filter ");
7312                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7313        }
7314
7315//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7316//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7317//            final List<ResolveInfo> retList = Lists.newArrayList();
7318//            while (i.hasNext()) {
7319//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7320//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7321//                    retList.add(resolveInfo);
7322//                }
7323//            }
7324//            return retList;
7325//        }
7326
7327        // Keys are String (activity class name), values are Activity.
7328        private final HashMap<ComponentName, PackageParser.Service> mServices
7329                = new HashMap<ComponentName, PackageParser.Service>();
7330        private int mFlags;
7331    };
7332
7333    private final class ProviderIntentResolver
7334            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7335        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7336                boolean defaultOnly, int userId) {
7337            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7338            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7339        }
7340
7341        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7342                int userId) {
7343            if (!sUserManager.exists(userId))
7344                return null;
7345            mFlags = flags;
7346            return super.queryIntent(intent, resolvedType,
7347                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7348        }
7349
7350        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7351                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7352            if (!sUserManager.exists(userId))
7353                return null;
7354            if (packageProviders == null) {
7355                return null;
7356            }
7357            mFlags = flags;
7358            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7359            final int N = packageProviders.size();
7360            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7361                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7362
7363            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7364            for (int i = 0; i < N; ++i) {
7365                intentFilters = packageProviders.get(i).intents;
7366                if (intentFilters != null && intentFilters.size() > 0) {
7367                    PackageParser.ProviderIntentInfo[] array =
7368                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7369                    intentFilters.toArray(array);
7370                    listCut.add(array);
7371                }
7372            }
7373            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7374        }
7375
7376        public final void addProvider(PackageParser.Provider p) {
7377            if (mProviders.containsKey(p.getComponentName())) {
7378                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7379                return;
7380            }
7381
7382            mProviders.put(p.getComponentName(), p);
7383            if (DEBUG_SHOW_INFO) {
7384                Log.v(TAG, "  "
7385                        + (p.info.nonLocalizedLabel != null
7386                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7387                Log.v(TAG, "    Class=" + p.info.name);
7388            }
7389            final int NI = p.intents.size();
7390            int j;
7391            for (j = 0; j < NI; j++) {
7392                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7393                if (DEBUG_SHOW_INFO) {
7394                    Log.v(TAG, "    IntentFilter:");
7395                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7396                }
7397                if (!intent.debugCheck()) {
7398                    Log.w(TAG, "==> For Provider " + p.info.name);
7399                }
7400                addFilter(intent);
7401            }
7402        }
7403
7404        public final void removeProvider(PackageParser.Provider p) {
7405            mProviders.remove(p.getComponentName());
7406            if (DEBUG_SHOW_INFO) {
7407                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7408                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7409                Log.v(TAG, "    Class=" + p.info.name);
7410            }
7411            final int NI = p.intents.size();
7412            int j;
7413            for (j = 0; j < NI; j++) {
7414                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7415                if (DEBUG_SHOW_INFO) {
7416                    Log.v(TAG, "    IntentFilter:");
7417                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7418                }
7419                removeFilter(intent);
7420            }
7421        }
7422
7423        @Override
7424        protected boolean allowFilterResult(
7425                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7426            ProviderInfo filterPi = filter.provider.info;
7427            for (int i = dest.size() - 1; i >= 0; i--) {
7428                ProviderInfo destPi = dest.get(i).providerInfo;
7429                if (destPi.name == filterPi.name
7430                        && destPi.packageName == filterPi.packageName) {
7431                    return false;
7432                }
7433            }
7434            return true;
7435        }
7436
7437        @Override
7438        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7439            return new PackageParser.ProviderIntentInfo[size];
7440        }
7441
7442        @Override
7443        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7444            if (!sUserManager.exists(userId))
7445                return true;
7446            PackageParser.Package p = filter.provider.owner;
7447            if (p != null) {
7448                PackageSetting ps = (PackageSetting) p.mExtras;
7449                if (ps != null) {
7450                    // System apps are never considered stopped for purposes of
7451                    // filtering, because there may be no way for the user to
7452                    // actually re-launch them.
7453                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7454                            && ps.getStopped(userId);
7455                }
7456            }
7457            return false;
7458        }
7459
7460        @Override
7461        protected boolean isPackageForFilter(String packageName,
7462                PackageParser.ProviderIntentInfo info) {
7463            return packageName.equals(info.provider.owner.packageName);
7464        }
7465
7466        @Override
7467        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7468                int match, int userId) {
7469            if (!sUserManager.exists(userId))
7470                return null;
7471            final PackageParser.ProviderIntentInfo info = filter;
7472            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7473                return null;
7474            }
7475            final PackageParser.Provider provider = info.provider;
7476            if (mSafeMode && (provider.info.applicationInfo.flags
7477                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7478                return null;
7479            }
7480            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7481            if (ps == null) {
7482                return null;
7483            }
7484            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7485                    ps.readUserState(userId), userId);
7486            if (pi == null) {
7487                return null;
7488            }
7489            final ResolveInfo res = new ResolveInfo();
7490            res.providerInfo = pi;
7491            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7492                res.filter = filter;
7493            }
7494            res.priority = info.getPriority();
7495            res.preferredOrder = provider.owner.mPreferredOrder;
7496            res.match = match;
7497            res.isDefault = info.hasDefault;
7498            res.labelRes = info.labelRes;
7499            res.nonLocalizedLabel = info.nonLocalizedLabel;
7500            res.icon = info.icon;
7501            res.system = isSystemApp(res.providerInfo.applicationInfo);
7502            return res;
7503        }
7504
7505        @Override
7506        protected void sortResults(List<ResolveInfo> results) {
7507            Collections.sort(results, mResolvePrioritySorter);
7508        }
7509
7510        @Override
7511        protected void dumpFilter(PrintWriter out, String prefix,
7512                PackageParser.ProviderIntentInfo filter) {
7513            out.print(prefix);
7514            out.print(
7515                    Integer.toHexString(System.identityHashCode(filter.provider)));
7516            out.print(' ');
7517            filter.provider.printComponentShortName(out);
7518            out.print(" filter ");
7519            out.println(Integer.toHexString(System.identityHashCode(filter)));
7520        }
7521
7522        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7523                = new HashMap<ComponentName, PackageParser.Provider>();
7524        private int mFlags;
7525    };
7526
7527    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7528            new Comparator<ResolveInfo>() {
7529        public int compare(ResolveInfo r1, ResolveInfo r2) {
7530            int v1 = r1.priority;
7531            int v2 = r2.priority;
7532            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7533            if (v1 != v2) {
7534                return (v1 > v2) ? -1 : 1;
7535            }
7536            v1 = r1.preferredOrder;
7537            v2 = r2.preferredOrder;
7538            if (v1 != v2) {
7539                return (v1 > v2) ? -1 : 1;
7540            }
7541            if (r1.isDefault != r2.isDefault) {
7542                return r1.isDefault ? -1 : 1;
7543            }
7544            v1 = r1.match;
7545            v2 = r2.match;
7546            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7547            if (v1 != v2) {
7548                return (v1 > v2) ? -1 : 1;
7549            }
7550            if (r1.system != r2.system) {
7551                return r1.system ? -1 : 1;
7552            }
7553            return 0;
7554        }
7555    };
7556
7557    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7558            new Comparator<ProviderInfo>() {
7559        public int compare(ProviderInfo p1, ProviderInfo p2) {
7560            final int v1 = p1.initOrder;
7561            final int v2 = p2.initOrder;
7562            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7563        }
7564    };
7565
7566    static final void sendPackageBroadcast(String action, String pkg,
7567            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7568            int[] userIds) {
7569        IActivityManager am = ActivityManagerNative.getDefault();
7570        if (am != null) {
7571            try {
7572                if (userIds == null) {
7573                    userIds = am.getRunningUserIds();
7574                }
7575                for (int id : userIds) {
7576                    final Intent intent = new Intent(action,
7577                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7578                    if (extras != null) {
7579                        intent.putExtras(extras);
7580                    }
7581                    if (targetPkg != null) {
7582                        intent.setPackage(targetPkg);
7583                    }
7584                    // Modify the UID when posting to other users
7585                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7586                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7587                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7588                        intent.putExtra(Intent.EXTRA_UID, uid);
7589                    }
7590                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7591                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7592                    if (DEBUG_BROADCASTS) {
7593                        RuntimeException here = new RuntimeException("here");
7594                        here.fillInStackTrace();
7595                        Slog.d(TAG, "Sending to user " + id + ": "
7596                                + intent.toShortString(false, true, false, false)
7597                                + " " + intent.getExtras(), here);
7598                    }
7599                    am.broadcastIntent(null, intent, null, finishedReceiver,
7600                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7601                            finishedReceiver != null, false, id);
7602                }
7603            } catch (RemoteException ex) {
7604            }
7605        }
7606    }
7607
7608    /**
7609     * Check if the external storage media is available. This is true if there
7610     * is a mounted external storage medium or if the external storage is
7611     * emulated.
7612     */
7613    private boolean isExternalMediaAvailable() {
7614        return mMediaMounted || Environment.isExternalStorageEmulated();
7615    }
7616
7617    @Override
7618    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7619        // writer
7620        synchronized (mPackages) {
7621            if (!isExternalMediaAvailable()) {
7622                // If the external storage is no longer mounted at this point,
7623                // the caller may not have been able to delete all of this
7624                // packages files and can not delete any more.  Bail.
7625                return null;
7626            }
7627            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7628            if (lastPackage != null) {
7629                pkgs.remove(lastPackage);
7630            }
7631            if (pkgs.size() > 0) {
7632                return pkgs.get(0);
7633            }
7634        }
7635        return null;
7636    }
7637
7638    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7639        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7640                userId, andCode ? 1 : 0, packageName);
7641        if (mSystemReady) {
7642            msg.sendToTarget();
7643        } else {
7644            if (mPostSystemReadyMessages == null) {
7645                mPostSystemReadyMessages = new ArrayList<>();
7646            }
7647            mPostSystemReadyMessages.add(msg);
7648        }
7649    }
7650
7651    void startCleaningPackages() {
7652        // reader
7653        synchronized (mPackages) {
7654            if (!isExternalMediaAvailable()) {
7655                return;
7656            }
7657            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7658                return;
7659            }
7660        }
7661        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7662        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7663        IActivityManager am = ActivityManagerNative.getDefault();
7664        if (am != null) {
7665            try {
7666                am.startService(null, intent, null, UserHandle.USER_OWNER);
7667            } catch (RemoteException e) {
7668            }
7669        }
7670    }
7671
7672    @Override
7673    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7674            int installFlags, String installerPackageName, VerificationParams verificationParams,
7675            String packageAbiOverride) {
7676        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7677                packageAbiOverride, UserHandle.getCallingUserId());
7678    }
7679
7680    @Override
7681    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7682            int installFlags, String installerPackageName, VerificationParams verificationParams,
7683            String packageAbiOverride, int userId) {
7684        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7685
7686        final int callingUid = Binder.getCallingUid();
7687        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7688
7689        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7690            try {
7691                if (observer != null) {
7692                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7693                }
7694            } catch (RemoteException re) {
7695            }
7696            return;
7697        }
7698
7699        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7700            installFlags |= PackageManager.INSTALL_FROM_ADB;
7701
7702        } else {
7703            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7704            // about installerPackageName.
7705
7706            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7707            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7708        }
7709
7710        UserHandle user;
7711        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7712            user = UserHandle.ALL;
7713        } else {
7714            user = new UserHandle(userId);
7715        }
7716
7717        verificationParams.setInstallerUid(callingUid);
7718
7719        final File originFile = new File(originPath);
7720        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7721
7722        final Message msg = mHandler.obtainMessage(INIT_COPY);
7723        msg.obj = new InstallParams(origin, observer, installFlags,
7724                installerPackageName, verificationParams, user, packageAbiOverride);
7725        mHandler.sendMessage(msg);
7726    }
7727
7728    void installStage(String packageName, File stagedDir, String stagedCid,
7729            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7730            String installerPackageName, int installerUid, UserHandle user) {
7731        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7732                params.referrerUri, installerUid, null);
7733
7734        final OriginInfo origin;
7735        if (stagedDir != null) {
7736            origin = OriginInfo.fromStagedFile(stagedDir);
7737        } else {
7738            origin = OriginInfo.fromStagedContainer(stagedCid);
7739        }
7740
7741        final Message msg = mHandler.obtainMessage(INIT_COPY);
7742        msg.obj = new InstallParams(origin, observer, params.installFlags,
7743                installerPackageName, verifParams, user, params.abiOverride);
7744        mHandler.sendMessage(msg);
7745    }
7746
7747    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7748        Bundle extras = new Bundle(1);
7749        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7750
7751        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7752                packageName, extras, null, null, new int[] {userId});
7753        try {
7754            IActivityManager am = ActivityManagerNative.getDefault();
7755            final boolean isSystem =
7756                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7757            if (isSystem && am.isUserRunning(userId, false)) {
7758                // The just-installed/enabled app is bundled on the system, so presumed
7759                // to be able to run automatically without needing an explicit launch.
7760                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7761                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7762                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7763                        .setPackage(packageName);
7764                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7765                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7766            }
7767        } catch (RemoteException e) {
7768            // shouldn't happen
7769            Slog.w(TAG, "Unable to bootstrap installed package", e);
7770        }
7771    }
7772
7773    @Override
7774    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7775            int userId) {
7776        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7777        PackageSetting pkgSetting;
7778        final int uid = Binder.getCallingUid();
7779        enforceCrossUserPermission(uid, userId, true, true,
7780                "setApplicationHiddenSetting for user " + userId);
7781
7782        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7783            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7784            return false;
7785        }
7786
7787        long callingId = Binder.clearCallingIdentity();
7788        try {
7789            boolean sendAdded = false;
7790            boolean sendRemoved = false;
7791            // writer
7792            synchronized (mPackages) {
7793                pkgSetting = mSettings.mPackages.get(packageName);
7794                if (pkgSetting == null) {
7795                    return false;
7796                }
7797                if (pkgSetting.getHidden(userId) != hidden) {
7798                    pkgSetting.setHidden(hidden, userId);
7799                    mSettings.writePackageRestrictionsLPr(userId);
7800                    if (hidden) {
7801                        sendRemoved = true;
7802                    } else {
7803                        sendAdded = true;
7804                    }
7805                }
7806            }
7807            if (sendAdded) {
7808                sendPackageAddedForUser(packageName, pkgSetting, userId);
7809                return true;
7810            }
7811            if (sendRemoved) {
7812                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7813                        "hiding pkg");
7814                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7815            }
7816        } finally {
7817            Binder.restoreCallingIdentity(callingId);
7818        }
7819        return false;
7820    }
7821
7822    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7823            int userId) {
7824        final PackageRemovedInfo info = new PackageRemovedInfo();
7825        info.removedPackage = packageName;
7826        info.removedUsers = new int[] {userId};
7827        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7828        info.sendBroadcast(false, false, false);
7829    }
7830
7831    /**
7832     * Returns true if application is not found or there was an error. Otherwise it returns
7833     * the hidden state of the package for the given user.
7834     */
7835    @Override
7836    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7837        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7838        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7839                false, "getApplicationHidden for user " + userId);
7840        PackageSetting pkgSetting;
7841        long callingId = Binder.clearCallingIdentity();
7842        try {
7843            // writer
7844            synchronized (mPackages) {
7845                pkgSetting = mSettings.mPackages.get(packageName);
7846                if (pkgSetting == null) {
7847                    return true;
7848                }
7849                return pkgSetting.getHidden(userId);
7850            }
7851        } finally {
7852            Binder.restoreCallingIdentity(callingId);
7853        }
7854    }
7855
7856    /**
7857     * @hide
7858     */
7859    @Override
7860    public int installExistingPackageAsUser(String packageName, int userId) {
7861        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7862                null);
7863        PackageSetting pkgSetting;
7864        final int uid = Binder.getCallingUid();
7865        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7866                + userId);
7867        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7868            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7869        }
7870
7871        long callingId = Binder.clearCallingIdentity();
7872        try {
7873            boolean sendAdded = false;
7874            Bundle extras = new Bundle(1);
7875
7876            // writer
7877            synchronized (mPackages) {
7878                pkgSetting = mSettings.mPackages.get(packageName);
7879                if (pkgSetting == null) {
7880                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7881                }
7882                if (!pkgSetting.getInstalled(userId)) {
7883                    pkgSetting.setInstalled(true, userId);
7884                    pkgSetting.setHidden(false, userId);
7885                    mSettings.writePackageRestrictionsLPr(userId);
7886                    sendAdded = true;
7887                }
7888            }
7889
7890            if (sendAdded) {
7891                sendPackageAddedForUser(packageName, pkgSetting, userId);
7892            }
7893        } finally {
7894            Binder.restoreCallingIdentity(callingId);
7895        }
7896
7897        return PackageManager.INSTALL_SUCCEEDED;
7898    }
7899
7900    boolean isUserRestricted(int userId, String restrictionKey) {
7901        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7902        if (restrictions.getBoolean(restrictionKey, false)) {
7903            Log.w(TAG, "User is restricted: " + restrictionKey);
7904            return true;
7905        }
7906        return false;
7907    }
7908
7909    @Override
7910    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7911        mContext.enforceCallingOrSelfPermission(
7912                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7913                "Only package verification agents can verify applications");
7914
7915        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7916        final PackageVerificationResponse response = new PackageVerificationResponse(
7917                verificationCode, Binder.getCallingUid());
7918        msg.arg1 = id;
7919        msg.obj = response;
7920        mHandler.sendMessage(msg);
7921    }
7922
7923    @Override
7924    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7925            long millisecondsToDelay) {
7926        mContext.enforceCallingOrSelfPermission(
7927                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7928                "Only package verification agents can extend verification timeouts");
7929
7930        final PackageVerificationState state = mPendingVerification.get(id);
7931        final PackageVerificationResponse response = new PackageVerificationResponse(
7932                verificationCodeAtTimeout, Binder.getCallingUid());
7933
7934        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7935            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7936        }
7937        if (millisecondsToDelay < 0) {
7938            millisecondsToDelay = 0;
7939        }
7940        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7941                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7942            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7943        }
7944
7945        if ((state != null) && !state.timeoutExtended()) {
7946            state.extendTimeout();
7947
7948            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7949            msg.arg1 = id;
7950            msg.obj = response;
7951            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7952        }
7953    }
7954
7955    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7956            int verificationCode, UserHandle user) {
7957        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7958        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7959        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7960        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7961        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7962
7963        mContext.sendBroadcastAsUser(intent, user,
7964                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7965    }
7966
7967    private ComponentName matchComponentForVerifier(String packageName,
7968            List<ResolveInfo> receivers) {
7969        ActivityInfo targetReceiver = null;
7970
7971        final int NR = receivers.size();
7972        for (int i = 0; i < NR; i++) {
7973            final ResolveInfo info = receivers.get(i);
7974            if (info.activityInfo == null) {
7975                continue;
7976            }
7977
7978            if (packageName.equals(info.activityInfo.packageName)) {
7979                targetReceiver = info.activityInfo;
7980                break;
7981            }
7982        }
7983
7984        if (targetReceiver == null) {
7985            return null;
7986        }
7987
7988        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7989    }
7990
7991    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7992            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7993        if (pkgInfo.verifiers.length == 0) {
7994            return null;
7995        }
7996
7997        final int N = pkgInfo.verifiers.length;
7998        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7999        for (int i = 0; i < N; i++) {
8000            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8001
8002            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8003                    receivers);
8004            if (comp == null) {
8005                continue;
8006            }
8007
8008            final int verifierUid = getUidForVerifier(verifierInfo);
8009            if (verifierUid == -1) {
8010                continue;
8011            }
8012
8013            if (DEBUG_VERIFY) {
8014                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8015                        + " with the correct signature");
8016            }
8017            sufficientVerifiers.add(comp);
8018            verificationState.addSufficientVerifier(verifierUid);
8019        }
8020
8021        return sufficientVerifiers;
8022    }
8023
8024    private int getUidForVerifier(VerifierInfo verifierInfo) {
8025        synchronized (mPackages) {
8026            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8027            if (pkg == null) {
8028                return -1;
8029            } else if (pkg.mSignatures.length != 1) {
8030                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8031                        + " has more than one signature; ignoring");
8032                return -1;
8033            }
8034
8035            /*
8036             * If the public key of the package's signature does not match
8037             * our expected public key, then this is a different package and
8038             * we should skip.
8039             */
8040
8041            final byte[] expectedPublicKey;
8042            try {
8043                final Signature verifierSig = pkg.mSignatures[0];
8044                final PublicKey publicKey = verifierSig.getPublicKey();
8045                expectedPublicKey = publicKey.getEncoded();
8046            } catch (CertificateException e) {
8047                return -1;
8048            }
8049
8050            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8051
8052            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8053                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8054                        + " does not have the expected public key; ignoring");
8055                return -1;
8056            }
8057
8058            return pkg.applicationInfo.uid;
8059        }
8060    }
8061
8062    @Override
8063    public void finishPackageInstall(int token) {
8064        enforceSystemOrRoot("Only the system is allowed to finish installs");
8065
8066        if (DEBUG_INSTALL) {
8067            Slog.v(TAG, "BM finishing package install for " + token);
8068        }
8069
8070        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8071        mHandler.sendMessage(msg);
8072    }
8073
8074    /**
8075     * Get the verification agent timeout.
8076     *
8077     * @return verification timeout in milliseconds
8078     */
8079    private long getVerificationTimeout() {
8080        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8081                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8082                DEFAULT_VERIFICATION_TIMEOUT);
8083    }
8084
8085    /**
8086     * Get the default verification agent response code.
8087     *
8088     * @return default verification response code
8089     */
8090    private int getDefaultVerificationResponse() {
8091        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8092                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8093                DEFAULT_VERIFICATION_RESPONSE);
8094    }
8095
8096    /**
8097     * Check whether or not package verification has been enabled.
8098     *
8099     * @return true if verification should be performed
8100     */
8101    private boolean isVerificationEnabled(int userId, int installFlags) {
8102        if (!DEFAULT_VERIFY_ENABLE) {
8103            return false;
8104        }
8105
8106        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8107
8108        // Check if installing from ADB
8109        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8110            // Do not run verification in a test harness environment
8111            if (ActivityManager.isRunningInTestHarness()) {
8112                return false;
8113            }
8114            if (ensureVerifyAppsEnabled) {
8115                return true;
8116            }
8117            // Check if the developer does not want package verification for ADB installs
8118            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8119                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8120                return false;
8121            }
8122        }
8123
8124        if (ensureVerifyAppsEnabled) {
8125            return true;
8126        }
8127
8128        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8129                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8130    }
8131
8132    /**
8133     * Get the "allow unknown sources" setting.
8134     *
8135     * @return the current "allow unknown sources" setting
8136     */
8137    private int getUnknownSourcesSettings() {
8138        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8139                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8140                -1);
8141    }
8142
8143    @Override
8144    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8145        final int uid = Binder.getCallingUid();
8146        // writer
8147        synchronized (mPackages) {
8148            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8149            if (targetPackageSetting == null) {
8150                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8151            }
8152
8153            PackageSetting installerPackageSetting;
8154            if (installerPackageName != null) {
8155                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8156                if (installerPackageSetting == null) {
8157                    throw new IllegalArgumentException("Unknown installer package: "
8158                            + installerPackageName);
8159                }
8160            } else {
8161                installerPackageSetting = null;
8162            }
8163
8164            Signature[] callerSignature;
8165            Object obj = mSettings.getUserIdLPr(uid);
8166            if (obj != null) {
8167                if (obj instanceof SharedUserSetting) {
8168                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8169                } else if (obj instanceof PackageSetting) {
8170                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8171                } else {
8172                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8173                }
8174            } else {
8175                throw new SecurityException("Unknown calling uid " + uid);
8176            }
8177
8178            // Verify: can't set installerPackageName to a package that is
8179            // not signed with the same cert as the caller.
8180            if (installerPackageSetting != null) {
8181                if (compareSignatures(callerSignature,
8182                        installerPackageSetting.signatures.mSignatures)
8183                        != PackageManager.SIGNATURE_MATCH) {
8184                    throw new SecurityException(
8185                            "Caller does not have same cert as new installer package "
8186                            + installerPackageName);
8187                }
8188            }
8189
8190            // Verify: if target already has an installer package, it must
8191            // be signed with the same cert as the caller.
8192            if (targetPackageSetting.installerPackageName != null) {
8193                PackageSetting setting = mSettings.mPackages.get(
8194                        targetPackageSetting.installerPackageName);
8195                // If the currently set package isn't valid, then it's always
8196                // okay to change it.
8197                if (setting != null) {
8198                    if (compareSignatures(callerSignature,
8199                            setting.signatures.mSignatures)
8200                            != PackageManager.SIGNATURE_MATCH) {
8201                        throw new SecurityException(
8202                                "Caller does not have same cert as old installer package "
8203                                + targetPackageSetting.installerPackageName);
8204                    }
8205                }
8206            }
8207
8208            // Okay!
8209            targetPackageSetting.installerPackageName = installerPackageName;
8210            scheduleWriteSettingsLocked();
8211        }
8212    }
8213
8214    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8215        // Queue up an async operation since the package installation may take a little while.
8216        mHandler.post(new Runnable() {
8217            public void run() {
8218                mHandler.removeCallbacks(this);
8219                 // Result object to be returned
8220                PackageInstalledInfo res = new PackageInstalledInfo();
8221                res.returnCode = currentStatus;
8222                res.uid = -1;
8223                res.pkg = null;
8224                res.removedInfo = new PackageRemovedInfo();
8225                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8226                    args.doPreInstall(res.returnCode);
8227                    synchronized (mInstallLock) {
8228                        installPackageLI(args, res);
8229                    }
8230                    args.doPostInstall(res.returnCode, res.uid);
8231                }
8232
8233                // A restore should be performed at this point if (a) the install
8234                // succeeded, (b) the operation is not an update, and (c) the new
8235                // package has not opted out of backup participation.
8236                final boolean update = res.removedInfo.removedPackage != null;
8237                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8238                boolean doRestore = !update
8239                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8240
8241                // Set up the post-install work request bookkeeping.  This will be used
8242                // and cleaned up by the post-install event handling regardless of whether
8243                // there's a restore pass performed.  Token values are >= 1.
8244                int token;
8245                if (mNextInstallToken < 0) mNextInstallToken = 1;
8246                token = mNextInstallToken++;
8247
8248                PostInstallData data = new PostInstallData(args, res);
8249                mRunningInstalls.put(token, data);
8250                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8251
8252                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8253                    // Pass responsibility to the Backup Manager.  It will perform a
8254                    // restore if appropriate, then pass responsibility back to the
8255                    // Package Manager to run the post-install observer callbacks
8256                    // and broadcasts.
8257                    IBackupManager bm = IBackupManager.Stub.asInterface(
8258                            ServiceManager.getService(Context.BACKUP_SERVICE));
8259                    if (bm != null) {
8260                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8261                                + " to BM for possible restore");
8262                        try {
8263                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8264                        } catch (RemoteException e) {
8265                            // can't happen; the backup manager is local
8266                        } catch (Exception e) {
8267                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8268                            doRestore = false;
8269                        }
8270                    } else {
8271                        Slog.e(TAG, "Backup Manager not found!");
8272                        doRestore = false;
8273                    }
8274                }
8275
8276                if (!doRestore) {
8277                    // No restore possible, or the Backup Manager was mysteriously not
8278                    // available -- just fire the post-install work request directly.
8279                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8280                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8281                    mHandler.sendMessage(msg);
8282                }
8283            }
8284        });
8285    }
8286
8287    private abstract class HandlerParams {
8288        private static final int MAX_RETRIES = 4;
8289
8290        /**
8291         * Number of times startCopy() has been attempted and had a non-fatal
8292         * error.
8293         */
8294        private int mRetries = 0;
8295
8296        /** User handle for the user requesting the information or installation. */
8297        private final UserHandle mUser;
8298
8299        HandlerParams(UserHandle user) {
8300            mUser = user;
8301        }
8302
8303        UserHandle getUser() {
8304            return mUser;
8305        }
8306
8307        final boolean startCopy() {
8308            boolean res;
8309            try {
8310                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8311
8312                if (++mRetries > MAX_RETRIES) {
8313                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8314                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8315                    handleServiceError();
8316                    return false;
8317                } else {
8318                    handleStartCopy();
8319                    res = true;
8320                }
8321            } catch (RemoteException e) {
8322                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8323                mHandler.sendEmptyMessage(MCS_RECONNECT);
8324                res = false;
8325            }
8326            handleReturnCode();
8327            return res;
8328        }
8329
8330        final void serviceError() {
8331            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8332            handleServiceError();
8333            handleReturnCode();
8334        }
8335
8336        abstract void handleStartCopy() throws RemoteException;
8337        abstract void handleServiceError();
8338        abstract void handleReturnCode();
8339    }
8340
8341    class MeasureParams extends HandlerParams {
8342        private final PackageStats mStats;
8343        private boolean mSuccess;
8344
8345        private final IPackageStatsObserver mObserver;
8346
8347        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8348            super(new UserHandle(stats.userHandle));
8349            mObserver = observer;
8350            mStats = stats;
8351        }
8352
8353        @Override
8354        public String toString() {
8355            return "MeasureParams{"
8356                + Integer.toHexString(System.identityHashCode(this))
8357                + " " + mStats.packageName + "}";
8358        }
8359
8360        @Override
8361        void handleStartCopy() throws RemoteException {
8362            synchronized (mInstallLock) {
8363                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8364            }
8365
8366            if (mSuccess) {
8367                final boolean mounted;
8368                if (Environment.isExternalStorageEmulated()) {
8369                    mounted = true;
8370                } else {
8371                    final String status = Environment.getExternalStorageState();
8372                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8373                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8374                }
8375
8376                if (mounted) {
8377                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8378
8379                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8380                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8381
8382                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8383                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8384
8385                    // Always subtract cache size, since it's a subdirectory
8386                    mStats.externalDataSize -= mStats.externalCacheSize;
8387
8388                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8389                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8390
8391                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8392                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8393                }
8394            }
8395        }
8396
8397        @Override
8398        void handleReturnCode() {
8399            if (mObserver != null) {
8400                try {
8401                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8402                } catch (RemoteException e) {
8403                    Slog.i(TAG, "Observer no longer exists.");
8404                }
8405            }
8406        }
8407
8408        @Override
8409        void handleServiceError() {
8410            Slog.e(TAG, "Could not measure application " + mStats.packageName
8411                            + " external storage");
8412        }
8413    }
8414
8415    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8416            throws RemoteException {
8417        long result = 0;
8418        for (File path : paths) {
8419            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8420        }
8421        return result;
8422    }
8423
8424    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8425        for (File path : paths) {
8426            try {
8427                mcs.clearDirectory(path.getAbsolutePath());
8428            } catch (RemoteException e) {
8429            }
8430        }
8431    }
8432
8433    static class OriginInfo {
8434        /**
8435         * Location where install is coming from, before it has been
8436         * copied/renamed into place. This could be a single monolithic APK
8437         * file, or a cluster directory. This location may be untrusted.
8438         */
8439        final File file;
8440        final String cid;
8441
8442        /**
8443         * Flag indicating that {@link #file} or {@link #cid} has already been
8444         * staged, meaning downstream users don't need to defensively copy the
8445         * contents.
8446         */
8447        final boolean staged;
8448
8449        /**
8450         * Flag indicating that {@link #file} or {@link #cid} is an already
8451         * installed app that is being moved.
8452         */
8453        final boolean existing;
8454
8455        final String resolvedPath;
8456        final File resolvedFile;
8457
8458        static OriginInfo fromNothing() {
8459            return new OriginInfo(null, null, false, false);
8460        }
8461
8462        static OriginInfo fromUntrustedFile(File file) {
8463            return new OriginInfo(file, null, false, false);
8464        }
8465
8466        static OriginInfo fromExistingFile(File file) {
8467            return new OriginInfo(file, null, false, true);
8468        }
8469
8470        static OriginInfo fromStagedFile(File file) {
8471            return new OriginInfo(file, null, true, false);
8472        }
8473
8474        static OriginInfo fromStagedContainer(String cid) {
8475            return new OriginInfo(null, cid, true, false);
8476        }
8477
8478        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8479            this.file = file;
8480            this.cid = cid;
8481            this.staged = staged;
8482            this.existing = existing;
8483
8484            if (cid != null) {
8485                resolvedPath = PackageHelper.getSdDir(cid);
8486                resolvedFile = new File(resolvedPath);
8487            } else if (file != null) {
8488                resolvedPath = file.getAbsolutePath();
8489                resolvedFile = file;
8490            } else {
8491                resolvedPath = null;
8492                resolvedFile = null;
8493            }
8494        }
8495    }
8496
8497    class InstallParams extends HandlerParams {
8498        final OriginInfo origin;
8499        final IPackageInstallObserver2 observer;
8500        int installFlags;
8501        final String installerPackageName;
8502        final VerificationParams verificationParams;
8503        private InstallArgs mArgs;
8504        private int mRet;
8505        final String packageAbiOverride;
8506
8507        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8508                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8509                String packageAbiOverride) {
8510            super(user);
8511            this.origin = origin;
8512            this.observer = observer;
8513            this.installFlags = installFlags;
8514            this.installerPackageName = installerPackageName;
8515            this.verificationParams = verificationParams;
8516            this.packageAbiOverride = packageAbiOverride;
8517        }
8518
8519        @Override
8520        public String toString() {
8521            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8522                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8523        }
8524
8525        public ManifestDigest getManifestDigest() {
8526            if (verificationParams == null) {
8527                return null;
8528            }
8529            return verificationParams.getManifestDigest();
8530        }
8531
8532        private int installLocationPolicy(PackageInfoLite pkgLite) {
8533            String packageName = pkgLite.packageName;
8534            int installLocation = pkgLite.installLocation;
8535            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8536            // reader
8537            synchronized (mPackages) {
8538                PackageParser.Package pkg = mPackages.get(packageName);
8539                if (pkg != null) {
8540                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8541                        // Check for downgrading.
8542                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8543                            if (pkgLite.versionCode < pkg.mVersionCode) {
8544                                Slog.w(TAG, "Can't install update of " + packageName
8545                                        + " update version " + pkgLite.versionCode
8546                                        + " is older than installed version "
8547                                        + pkg.mVersionCode);
8548                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8549                            }
8550                        }
8551                        // Check for updated system application.
8552                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8553                            if (onSd) {
8554                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8555                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8556                            }
8557                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8558                        } else {
8559                            if (onSd) {
8560                                // Install flag overrides everything.
8561                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8562                            }
8563                            // If current upgrade specifies particular preference
8564                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8565                                // Application explicitly specified internal.
8566                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8567                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8568                                // App explictly prefers external. Let policy decide
8569                            } else {
8570                                // Prefer previous location
8571                                if (isExternal(pkg)) {
8572                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8573                                }
8574                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8575                            }
8576                        }
8577                    } else {
8578                        // Invalid install. Return error code
8579                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8580                    }
8581                }
8582            }
8583            // All the special cases have been taken care of.
8584            // Return result based on recommended install location.
8585            if (onSd) {
8586                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8587            }
8588            return pkgLite.recommendedInstallLocation;
8589        }
8590
8591        /*
8592         * Invoke remote method to get package information and install
8593         * location values. Override install location based on default
8594         * policy if needed and then create install arguments based
8595         * on the install location.
8596         */
8597        public void handleStartCopy() throws RemoteException {
8598            int ret = PackageManager.INSTALL_SUCCEEDED;
8599
8600            // If we're already staged, we've firmly committed to an install location
8601            if (origin.staged) {
8602                if (origin.file != null) {
8603                    installFlags |= PackageManager.INSTALL_INTERNAL;
8604                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8605                } else if (origin.cid != null) {
8606                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8607                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8608                } else {
8609                    throw new IllegalStateException("Invalid stage location");
8610                }
8611            }
8612
8613            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8614            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8615
8616            PackageInfoLite pkgLite = null;
8617
8618            if (onInt && onSd) {
8619                // Check if both bits are set.
8620                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8621                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8622            } else {
8623                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8624                        packageAbiOverride);
8625
8626                /*
8627                 * If we have too little free space, try to free cache
8628                 * before giving up.
8629                 */
8630                if (!origin.staged && pkgLite.recommendedInstallLocation
8631                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8632                    // TODO: focus freeing disk space on the target device
8633                    final StorageManager storage = StorageManager.from(mContext);
8634                    final long lowThreshold = storage.getStorageLowBytes(
8635                            Environment.getDataDirectory());
8636
8637                    final long sizeBytes = mContainerService.calculateInstalledSize(
8638                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8639
8640                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8641                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8642                                installFlags, packageAbiOverride);
8643                    }
8644
8645                    /*
8646                     * The cache free must have deleted the file we
8647                     * downloaded to install.
8648                     *
8649                     * TODO: fix the "freeCache" call to not delete
8650                     *       the file we care about.
8651                     */
8652                    if (pkgLite.recommendedInstallLocation
8653                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8654                        pkgLite.recommendedInstallLocation
8655                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8656                    }
8657                }
8658            }
8659
8660            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8661                int loc = pkgLite.recommendedInstallLocation;
8662                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8663                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8664                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8665                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8666                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8667                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8668                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8669                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8670                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8671                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8672                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8673                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8674                } else {
8675                    // Override with defaults if needed.
8676                    loc = installLocationPolicy(pkgLite);
8677                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8678                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8679                    } else if (!onSd && !onInt) {
8680                        // Override install location with flags
8681                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8682                            // Set the flag to install on external media.
8683                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8684                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8685                        } else {
8686                            // Make sure the flag for installing on external
8687                            // media is unset
8688                            installFlags |= PackageManager.INSTALL_INTERNAL;
8689                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8690                        }
8691                    }
8692                }
8693            }
8694
8695            final InstallArgs args = createInstallArgs(this);
8696            mArgs = args;
8697
8698            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8699                 /*
8700                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8701                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8702                 */
8703                int userIdentifier = getUser().getIdentifier();
8704                if (userIdentifier == UserHandle.USER_ALL
8705                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8706                    userIdentifier = UserHandle.USER_OWNER;
8707                }
8708
8709                /*
8710                 * Determine if we have any installed package verifiers. If we
8711                 * do, then we'll defer to them to verify the packages.
8712                 */
8713                final int requiredUid = mRequiredVerifierPackage == null ? -1
8714                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8715                if (!origin.existing && requiredUid != -1
8716                        && isVerificationEnabled(userIdentifier, installFlags)) {
8717                    final Intent verification = new Intent(
8718                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8719                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8720                            PACKAGE_MIME_TYPE);
8721                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8722
8723                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8724                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8725                            0 /* TODO: Which userId? */);
8726
8727                    if (DEBUG_VERIFY) {
8728                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8729                                + verification.toString() + " with " + pkgLite.verifiers.length
8730                                + " optional verifiers");
8731                    }
8732
8733                    final int verificationId = mPendingVerificationToken++;
8734
8735                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8736
8737                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8738                            installerPackageName);
8739
8740                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8741                            installFlags);
8742
8743                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8744                            pkgLite.packageName);
8745
8746                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8747                            pkgLite.versionCode);
8748
8749                    if (verificationParams != null) {
8750                        if (verificationParams.getVerificationURI() != null) {
8751                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8752                                 verificationParams.getVerificationURI());
8753                        }
8754                        if (verificationParams.getOriginatingURI() != null) {
8755                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8756                                  verificationParams.getOriginatingURI());
8757                        }
8758                        if (verificationParams.getReferrer() != null) {
8759                            verification.putExtra(Intent.EXTRA_REFERRER,
8760                                  verificationParams.getReferrer());
8761                        }
8762                        if (verificationParams.getOriginatingUid() >= 0) {
8763                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8764                                  verificationParams.getOriginatingUid());
8765                        }
8766                        if (verificationParams.getInstallerUid() >= 0) {
8767                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8768                                  verificationParams.getInstallerUid());
8769                        }
8770                    }
8771
8772                    final PackageVerificationState verificationState = new PackageVerificationState(
8773                            requiredUid, args);
8774
8775                    mPendingVerification.append(verificationId, verificationState);
8776
8777                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8778                            receivers, verificationState);
8779
8780                    /*
8781                     * If any sufficient verifiers were listed in the package
8782                     * manifest, attempt to ask them.
8783                     */
8784                    if (sufficientVerifiers != null) {
8785                        final int N = sufficientVerifiers.size();
8786                        if (N == 0) {
8787                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8788                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8789                        } else {
8790                            for (int i = 0; i < N; i++) {
8791                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8792
8793                                final Intent sufficientIntent = new Intent(verification);
8794                                sufficientIntent.setComponent(verifierComponent);
8795
8796                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8797                            }
8798                        }
8799                    }
8800
8801                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8802                            mRequiredVerifierPackage, receivers);
8803                    if (ret == PackageManager.INSTALL_SUCCEEDED
8804                            && mRequiredVerifierPackage != null) {
8805                        /*
8806                         * Send the intent to the required verification agent,
8807                         * but only start the verification timeout after the
8808                         * target BroadcastReceivers have run.
8809                         */
8810                        verification.setComponent(requiredVerifierComponent);
8811                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8812                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8813                                new BroadcastReceiver() {
8814                                    @Override
8815                                    public void onReceive(Context context, Intent intent) {
8816                                        final Message msg = mHandler
8817                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8818                                        msg.arg1 = verificationId;
8819                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8820                                    }
8821                                }, null, 0, null, null);
8822
8823                        /*
8824                         * We don't want the copy to proceed until verification
8825                         * succeeds, so null out this field.
8826                         */
8827                        mArgs = null;
8828                    }
8829                } else {
8830                    /*
8831                     * No package verification is enabled, so immediately start
8832                     * the remote call to initiate copy using temporary file.
8833                     */
8834                    ret = args.copyApk(mContainerService, true);
8835                }
8836            }
8837
8838            mRet = ret;
8839        }
8840
8841        @Override
8842        void handleReturnCode() {
8843            // If mArgs is null, then MCS couldn't be reached. When it
8844            // reconnects, it will try again to install. At that point, this
8845            // will succeed.
8846            if (mArgs != null) {
8847                processPendingInstall(mArgs, mRet);
8848            }
8849        }
8850
8851        @Override
8852        void handleServiceError() {
8853            mArgs = createInstallArgs(this);
8854            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8855        }
8856
8857        public boolean isForwardLocked() {
8858            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8859        }
8860    }
8861
8862    /**
8863     * Used during creation of InstallArgs
8864     *
8865     * @param installFlags package installation flags
8866     * @return true if should be installed on external storage
8867     */
8868    private static boolean installOnSd(int installFlags) {
8869        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8870            return false;
8871        }
8872        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8873            return true;
8874        }
8875        return false;
8876    }
8877
8878    /**
8879     * Used during creation of InstallArgs
8880     *
8881     * @param installFlags package installation flags
8882     * @return true if should be installed as forward locked
8883     */
8884    private static boolean installForwardLocked(int installFlags) {
8885        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8886    }
8887
8888    private InstallArgs createInstallArgs(InstallParams params) {
8889        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8890            return new AsecInstallArgs(params);
8891        } else {
8892            return new FileInstallArgs(params);
8893        }
8894    }
8895
8896    /**
8897     * Create args that describe an existing installed package. Typically used
8898     * when cleaning up old installs, or used as a move source.
8899     */
8900    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8901            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8902        final boolean isInAsec;
8903        if (installOnSd(installFlags)) {
8904            /* Apps on SD card are always in ASEC containers. */
8905            isInAsec = true;
8906        } else if (installForwardLocked(installFlags)
8907                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8908            /*
8909             * Forward-locked apps are only in ASEC containers if they're the
8910             * new style
8911             */
8912            isInAsec = true;
8913        } else {
8914            isInAsec = false;
8915        }
8916
8917        if (isInAsec) {
8918            return new AsecInstallArgs(codePath, instructionSets,
8919                    installOnSd(installFlags), installForwardLocked(installFlags));
8920        } else {
8921            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8922                    instructionSets);
8923        }
8924    }
8925
8926    static abstract class InstallArgs {
8927        /** @see InstallParams#origin */
8928        final OriginInfo origin;
8929
8930        final IPackageInstallObserver2 observer;
8931        // Always refers to PackageManager flags only
8932        final int installFlags;
8933        final String installerPackageName;
8934        final ManifestDigest manifestDigest;
8935        final UserHandle user;
8936        final String abiOverride;
8937
8938        // The list of instruction sets supported by this app. This is currently
8939        // only used during the rmdex() phase to clean up resources. We can get rid of this
8940        // if we move dex files under the common app path.
8941        /* nullable */ String[] instructionSets;
8942
8943        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8944                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8945                String[] instructionSets, String abiOverride) {
8946            this.origin = origin;
8947            this.installFlags = installFlags;
8948            this.observer = observer;
8949            this.installerPackageName = installerPackageName;
8950            this.manifestDigest = manifestDigest;
8951            this.user = user;
8952            this.instructionSets = instructionSets;
8953            this.abiOverride = abiOverride;
8954        }
8955
8956        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8957        abstract int doPreInstall(int status);
8958
8959        /**
8960         * Rename package into final resting place. All paths on the given
8961         * scanned package should be updated to reflect the rename.
8962         */
8963        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8964        abstract int doPostInstall(int status, int uid);
8965
8966        /** @see PackageSettingBase#codePathString */
8967        abstract String getCodePath();
8968        /** @see PackageSettingBase#resourcePathString */
8969        abstract String getResourcePath();
8970        abstract String getLegacyNativeLibraryPath();
8971
8972        // Need installer lock especially for dex file removal.
8973        abstract void cleanUpResourcesLI();
8974        abstract boolean doPostDeleteLI(boolean delete);
8975        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8976
8977        /**
8978         * Called before the source arguments are copied. This is used mostly
8979         * for MoveParams when it needs to read the source file to put it in the
8980         * destination.
8981         */
8982        int doPreCopy() {
8983            return PackageManager.INSTALL_SUCCEEDED;
8984        }
8985
8986        /**
8987         * Called after the source arguments are copied. This is used mostly for
8988         * MoveParams when it needs to read the source file to put it in the
8989         * destination.
8990         *
8991         * @return
8992         */
8993        int doPostCopy(int uid) {
8994            return PackageManager.INSTALL_SUCCEEDED;
8995        }
8996
8997        protected boolean isFwdLocked() {
8998            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8999        }
9000
9001        protected boolean isExternal() {
9002            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9003        }
9004
9005        UserHandle getUser() {
9006            return user;
9007        }
9008    }
9009
9010    /**
9011     * Logic to handle installation of non-ASEC applications, including copying
9012     * and renaming logic.
9013     */
9014    class FileInstallArgs extends InstallArgs {
9015        private File codeFile;
9016        private File resourceFile;
9017        private File legacyNativeLibraryPath;
9018
9019        // Example topology:
9020        // /data/app/com.example/base.apk
9021        // /data/app/com.example/split_foo.apk
9022        // /data/app/com.example/lib/arm/libfoo.so
9023        // /data/app/com.example/lib/arm64/libfoo.so
9024        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9025
9026        /** New install */
9027        FileInstallArgs(InstallParams params) {
9028            super(params.origin, params.observer, params.installFlags,
9029                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9030                    null /* instruction sets */, params.packageAbiOverride);
9031            if (isFwdLocked()) {
9032                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9033            }
9034        }
9035
9036        /** Existing install */
9037        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9038                String[] instructionSets) {
9039            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9040            this.codeFile = (codePath != null) ? new File(codePath) : null;
9041            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9042            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9043                    new File(legacyNativeLibraryPath) : null;
9044        }
9045
9046        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9047            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9048                    isFwdLocked(), abiOverride);
9049
9050            final StorageManager storage = StorageManager.from(mContext);
9051            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9052        }
9053
9054        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9055            if (origin.staged) {
9056                Slog.d(TAG, origin.file + " already staged; skipping copy");
9057                codeFile = origin.file;
9058                resourceFile = origin.file;
9059                return PackageManager.INSTALL_SUCCEEDED;
9060            }
9061
9062            try {
9063                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9064                codeFile = tempDir;
9065                resourceFile = tempDir;
9066            } catch (IOException e) {
9067                Slog.w(TAG, "Failed to create copy file: " + e);
9068                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9069            }
9070
9071            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9072                @Override
9073                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9074                    if (!FileUtils.isValidExtFilename(name)) {
9075                        throw new IllegalArgumentException("Invalid filename: " + name);
9076                    }
9077                    try {
9078                        final File file = new File(codeFile, name);
9079                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9080                                O_RDWR | O_CREAT, 0644);
9081                        Os.chmod(file.getAbsolutePath(), 0644);
9082                        return new ParcelFileDescriptor(fd);
9083                    } catch (ErrnoException e) {
9084                        throw new RemoteException("Failed to open: " + e.getMessage());
9085                    }
9086                }
9087            };
9088
9089            int ret = PackageManager.INSTALL_SUCCEEDED;
9090            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9091            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9092                Slog.e(TAG, "Failed to copy package");
9093                return ret;
9094            }
9095
9096            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9097            NativeLibraryHelper.Handle handle = null;
9098            try {
9099                handle = NativeLibraryHelper.Handle.create(codeFile);
9100                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9101                        abiOverride);
9102            } catch (IOException e) {
9103                Slog.e(TAG, "Copying native libraries failed", e);
9104                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9105            } finally {
9106                IoUtils.closeQuietly(handle);
9107            }
9108
9109            return ret;
9110        }
9111
9112        int doPreInstall(int status) {
9113            if (status != PackageManager.INSTALL_SUCCEEDED) {
9114                cleanUp();
9115            }
9116            return status;
9117        }
9118
9119        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9120            if (status != PackageManager.INSTALL_SUCCEEDED) {
9121                cleanUp();
9122                return false;
9123            } else {
9124                final File beforeCodeFile = codeFile;
9125                final File afterCodeFile = getNextCodePath(pkg.packageName);
9126
9127                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9128                try {
9129                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9130                } catch (ErrnoException e) {
9131                    Slog.d(TAG, "Failed to rename", e);
9132                    return false;
9133                }
9134
9135                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9136                    Slog.d(TAG, "Failed to restorecon");
9137                    return false;
9138                }
9139
9140                // Reflect the rename internally
9141                codeFile = afterCodeFile;
9142                resourceFile = afterCodeFile;
9143
9144                // Reflect the rename in scanned details
9145                pkg.codePath = afterCodeFile.getAbsolutePath();
9146                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9147                        pkg.baseCodePath);
9148                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9149                        pkg.splitCodePaths);
9150
9151                // Reflect the rename in app info
9152                pkg.applicationInfo.setCodePath(pkg.codePath);
9153                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9154                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9155                pkg.applicationInfo.setResourcePath(pkg.codePath);
9156                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9157                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9158
9159                return true;
9160            }
9161        }
9162
9163        int doPostInstall(int status, int uid) {
9164            if (status != PackageManager.INSTALL_SUCCEEDED) {
9165                cleanUp();
9166            }
9167            return status;
9168        }
9169
9170        @Override
9171        String getCodePath() {
9172            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9173        }
9174
9175        @Override
9176        String getResourcePath() {
9177            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9178        }
9179
9180        @Override
9181        String getLegacyNativeLibraryPath() {
9182            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9183        }
9184
9185        private boolean cleanUp() {
9186            if (codeFile == null || !codeFile.exists()) {
9187                return false;
9188            }
9189
9190            if (codeFile.isDirectory()) {
9191                FileUtils.deleteContents(codeFile);
9192            }
9193            codeFile.delete();
9194
9195            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9196                resourceFile.delete();
9197            }
9198
9199            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9200                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9201                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9202                }
9203                legacyNativeLibraryPath.delete();
9204            }
9205
9206            return true;
9207        }
9208
9209        void cleanUpResourcesLI() {
9210            // Try enumerating all code paths before deleting
9211            List<String> allCodePaths = Collections.EMPTY_LIST;
9212            if (codeFile != null && codeFile.exists()) {
9213                try {
9214                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9215                    allCodePaths = pkg.getAllCodePaths();
9216                } catch (PackageParserException e) {
9217                    // Ignored; we tried our best
9218                }
9219            }
9220
9221            cleanUp();
9222
9223            if (!allCodePaths.isEmpty()) {
9224                if (instructionSets == null) {
9225                    throw new IllegalStateException("instructionSet == null");
9226                }
9227                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9228                for (String codePath : allCodePaths) {
9229                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9230                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9231                        if (retCode < 0) {
9232                            Slog.w(TAG, "Couldn't remove dex file for package: "
9233                                    + " at location " + codePath + ", retcode=" + retCode);
9234                            // we don't consider this to be a failure of the core package deletion
9235                        }
9236                    }
9237                }
9238            }
9239        }
9240
9241        boolean doPostDeleteLI(boolean delete) {
9242            // XXX err, shouldn't we respect the delete flag?
9243            cleanUpResourcesLI();
9244            return true;
9245        }
9246    }
9247
9248    private boolean isAsecExternal(String cid) {
9249        final String asecPath = PackageHelper.getSdFilesystem(cid);
9250        return !asecPath.startsWith(mAsecInternalPath);
9251    }
9252
9253    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9254            PackageManagerException {
9255        if (copyRet < 0) {
9256            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9257                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9258                throw new PackageManagerException(copyRet, message);
9259            }
9260        }
9261    }
9262
9263    /**
9264     * Extract the MountService "container ID" from the full code path of an
9265     * .apk.
9266     */
9267    static String cidFromCodePath(String fullCodePath) {
9268        int eidx = fullCodePath.lastIndexOf("/");
9269        String subStr1 = fullCodePath.substring(0, eidx);
9270        int sidx = subStr1.lastIndexOf("/");
9271        return subStr1.substring(sidx+1, eidx);
9272    }
9273
9274    /**
9275     * Logic to handle installation of ASEC applications, including copying and
9276     * renaming logic.
9277     */
9278    class AsecInstallArgs extends InstallArgs {
9279        static final String RES_FILE_NAME = "pkg.apk";
9280        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9281
9282        String cid;
9283        String packagePath;
9284        String resourcePath;
9285        String legacyNativeLibraryDir;
9286
9287        /** New install */
9288        AsecInstallArgs(InstallParams params) {
9289            super(params.origin, params.observer, params.installFlags,
9290                    params.installerPackageName, params.getManifestDigest(),
9291                    params.getUser(), null /* instruction sets */,
9292                    params.packageAbiOverride);
9293        }
9294
9295        /** Existing install */
9296        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9297                        boolean isExternal, boolean isForwardLocked) {
9298            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9299                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9300                    instructionSets, null);
9301            // Hackily pretend we're still looking at a full code path
9302            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9303                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9304            }
9305
9306            // Extract cid from fullCodePath
9307            int eidx = fullCodePath.lastIndexOf("/");
9308            String subStr1 = fullCodePath.substring(0, eidx);
9309            int sidx = subStr1.lastIndexOf("/");
9310            cid = subStr1.substring(sidx+1, eidx);
9311            setMountPath(subStr1);
9312        }
9313
9314        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9315            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9316                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9317                    instructionSets, null);
9318            this.cid = cid;
9319            setMountPath(PackageHelper.getSdDir(cid));
9320        }
9321
9322        void createCopyFile() {
9323            cid = mInstallerService.allocateExternalStageCidLegacy();
9324        }
9325
9326        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9327            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9328                    abiOverride);
9329
9330            final File target;
9331            if (isExternal()) {
9332                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9333            } else {
9334                target = Environment.getDataDirectory();
9335            }
9336
9337            final StorageManager storage = StorageManager.from(mContext);
9338            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9339        }
9340
9341        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9342            if (origin.staged) {
9343                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9344                cid = origin.cid;
9345                setMountPath(PackageHelper.getSdDir(cid));
9346                return PackageManager.INSTALL_SUCCEEDED;
9347            }
9348
9349            if (temp) {
9350                createCopyFile();
9351            } else {
9352                /*
9353                 * Pre-emptively destroy the container since it's destroyed if
9354                 * copying fails due to it existing anyway.
9355                 */
9356                PackageHelper.destroySdDir(cid);
9357            }
9358
9359            final String newMountPath = imcs.copyPackageToContainer(
9360                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9361                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9362
9363            if (newMountPath != null) {
9364                setMountPath(newMountPath);
9365                return PackageManager.INSTALL_SUCCEEDED;
9366            } else {
9367                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9368            }
9369        }
9370
9371        @Override
9372        String getCodePath() {
9373            return packagePath;
9374        }
9375
9376        @Override
9377        String getResourcePath() {
9378            return resourcePath;
9379        }
9380
9381        @Override
9382        String getLegacyNativeLibraryPath() {
9383            return legacyNativeLibraryDir;
9384        }
9385
9386        int doPreInstall(int status) {
9387            if (status != PackageManager.INSTALL_SUCCEEDED) {
9388                // Destroy container
9389                PackageHelper.destroySdDir(cid);
9390            } else {
9391                boolean mounted = PackageHelper.isContainerMounted(cid);
9392                if (!mounted) {
9393                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9394                            Process.SYSTEM_UID);
9395                    if (newMountPath != null) {
9396                        setMountPath(newMountPath);
9397                    } else {
9398                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9399                    }
9400                }
9401            }
9402            return status;
9403        }
9404
9405        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9406            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9407            String newMountPath = null;
9408            if (PackageHelper.isContainerMounted(cid)) {
9409                // Unmount the container
9410                if (!PackageHelper.unMountSdDir(cid)) {
9411                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9412                    return false;
9413                }
9414            }
9415            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9416                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9417                        " which might be stale. Will try to clean up.");
9418                // Clean up the stale container and proceed to recreate.
9419                if (!PackageHelper.destroySdDir(newCacheId)) {
9420                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9421                    return false;
9422                }
9423                // Successfully cleaned up stale container. Try to rename again.
9424                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9425                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9426                            + " inspite of cleaning it up.");
9427                    return false;
9428                }
9429            }
9430            if (!PackageHelper.isContainerMounted(newCacheId)) {
9431                Slog.w(TAG, "Mounting container " + newCacheId);
9432                newMountPath = PackageHelper.mountSdDir(newCacheId,
9433                        getEncryptKey(), Process.SYSTEM_UID);
9434            } else {
9435                newMountPath = PackageHelper.getSdDir(newCacheId);
9436            }
9437            if (newMountPath == null) {
9438                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9439                return false;
9440            }
9441            Log.i(TAG, "Succesfully renamed " + cid +
9442                    " to " + newCacheId +
9443                    " at new path: " + newMountPath);
9444            cid = newCacheId;
9445
9446            final File beforeCodeFile = new File(packagePath);
9447            setMountPath(newMountPath);
9448            final File afterCodeFile = new File(packagePath);
9449
9450            // Reflect the rename in scanned details
9451            pkg.codePath = afterCodeFile.getAbsolutePath();
9452            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9453                    pkg.baseCodePath);
9454            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9455                    pkg.splitCodePaths);
9456
9457            // Reflect the rename in app info
9458            pkg.applicationInfo.setCodePath(pkg.codePath);
9459            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9460            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9461            pkg.applicationInfo.setResourcePath(pkg.codePath);
9462            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9463            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9464
9465            return true;
9466        }
9467
9468        private void setMountPath(String mountPath) {
9469            final File mountFile = new File(mountPath);
9470
9471            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9472            if (monolithicFile.exists()) {
9473                packagePath = monolithicFile.getAbsolutePath();
9474                if (isFwdLocked()) {
9475                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9476                } else {
9477                    resourcePath = packagePath;
9478                }
9479            } else {
9480                packagePath = mountFile.getAbsolutePath();
9481                resourcePath = packagePath;
9482            }
9483
9484            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9485        }
9486
9487        int doPostInstall(int status, int uid) {
9488            if (status != PackageManager.INSTALL_SUCCEEDED) {
9489                cleanUp();
9490            } else {
9491                final int groupOwner;
9492                final String protectedFile;
9493                if (isFwdLocked()) {
9494                    groupOwner = UserHandle.getSharedAppGid(uid);
9495                    protectedFile = RES_FILE_NAME;
9496                } else {
9497                    groupOwner = -1;
9498                    protectedFile = null;
9499                }
9500
9501                if (uid < Process.FIRST_APPLICATION_UID
9502                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9503                    Slog.e(TAG, "Failed to finalize " + cid);
9504                    PackageHelper.destroySdDir(cid);
9505                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9506                }
9507
9508                boolean mounted = PackageHelper.isContainerMounted(cid);
9509                if (!mounted) {
9510                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9511                }
9512            }
9513            return status;
9514        }
9515
9516        private void cleanUp() {
9517            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9518
9519            // Destroy secure container
9520            PackageHelper.destroySdDir(cid);
9521        }
9522
9523        private List<String> getAllCodePaths() {
9524            final File codeFile = new File(getCodePath());
9525            if (codeFile != null && codeFile.exists()) {
9526                try {
9527                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9528                    return pkg.getAllCodePaths();
9529                } catch (PackageParserException e) {
9530                    // Ignored; we tried our best
9531                }
9532            }
9533            return Collections.EMPTY_LIST;
9534        }
9535
9536        void cleanUpResourcesLI() {
9537            // Enumerate all code paths before deleting
9538            cleanUpResourcesLI(getAllCodePaths());
9539        }
9540
9541        private void cleanUpResourcesLI(List<String> allCodePaths) {
9542            cleanUp();
9543
9544            if (!allCodePaths.isEmpty()) {
9545                if (instructionSets == null) {
9546                    throw new IllegalStateException("instructionSet == null");
9547                }
9548                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9549                for (String codePath : allCodePaths) {
9550                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9551                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9552                        if (retCode < 0) {
9553                            Slog.w(TAG, "Couldn't remove dex file for package: "
9554                                    + " at location " + codePath + ", retcode=" + retCode);
9555                            // we don't consider this to be a failure of the core package deletion
9556                        }
9557                    }
9558                }
9559            }
9560        }
9561
9562        boolean matchContainer(String app) {
9563            if (cid.startsWith(app)) {
9564                return true;
9565            }
9566            return false;
9567        }
9568
9569        String getPackageName() {
9570            return getAsecPackageName(cid);
9571        }
9572
9573        boolean doPostDeleteLI(boolean delete) {
9574            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9575            final List<String> allCodePaths = getAllCodePaths();
9576            boolean mounted = PackageHelper.isContainerMounted(cid);
9577            if (mounted) {
9578                // Unmount first
9579                if (PackageHelper.unMountSdDir(cid)) {
9580                    mounted = false;
9581                }
9582            }
9583            if (!mounted && delete) {
9584                cleanUpResourcesLI(allCodePaths);
9585            }
9586            return !mounted;
9587        }
9588
9589        @Override
9590        int doPreCopy() {
9591            if (isFwdLocked()) {
9592                if (!PackageHelper.fixSdPermissions(cid,
9593                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9594                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9595                }
9596            }
9597
9598            return PackageManager.INSTALL_SUCCEEDED;
9599        }
9600
9601        @Override
9602        int doPostCopy(int uid) {
9603            if (isFwdLocked()) {
9604                if (uid < Process.FIRST_APPLICATION_UID
9605                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9606                                RES_FILE_NAME)) {
9607                    Slog.e(TAG, "Failed to finalize " + cid);
9608                    PackageHelper.destroySdDir(cid);
9609                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9610                }
9611            }
9612
9613            return PackageManager.INSTALL_SUCCEEDED;
9614        }
9615    }
9616
9617    static String getAsecPackageName(String packageCid) {
9618        int idx = packageCid.lastIndexOf("-");
9619        if (idx == -1) {
9620            return packageCid;
9621        }
9622        return packageCid.substring(0, idx);
9623    }
9624
9625    // Utility method used to create code paths based on package name and available index.
9626    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9627        String idxStr = "";
9628        int idx = 1;
9629        // Fall back to default value of idx=1 if prefix is not
9630        // part of oldCodePath
9631        if (oldCodePath != null) {
9632            String subStr = oldCodePath;
9633            // Drop the suffix right away
9634            if (suffix != null && subStr.endsWith(suffix)) {
9635                subStr = subStr.substring(0, subStr.length() - suffix.length());
9636            }
9637            // If oldCodePath already contains prefix find out the
9638            // ending index to either increment or decrement.
9639            int sidx = subStr.lastIndexOf(prefix);
9640            if (sidx != -1) {
9641                subStr = subStr.substring(sidx + prefix.length());
9642                if (subStr != null) {
9643                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9644                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9645                    }
9646                    try {
9647                        idx = Integer.parseInt(subStr);
9648                        if (idx <= 1) {
9649                            idx++;
9650                        } else {
9651                            idx--;
9652                        }
9653                    } catch(NumberFormatException e) {
9654                    }
9655                }
9656            }
9657        }
9658        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9659        return prefix + idxStr;
9660    }
9661
9662    private File getNextCodePath(String packageName) {
9663        int suffix = 1;
9664        File result;
9665        do {
9666            result = new File(mAppInstallDir, packageName + "-" + suffix);
9667            suffix++;
9668        } while (result.exists());
9669        return result;
9670    }
9671
9672    // Utility method used to ignore ADD/REMOVE events
9673    // by directory observer.
9674    private static boolean ignoreCodePath(String fullPathStr) {
9675        String apkName = deriveCodePathName(fullPathStr);
9676        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9677        if (idx != -1 && ((idx+1) < apkName.length())) {
9678            // Make sure the package ends with a numeral
9679            String version = apkName.substring(idx+1);
9680            try {
9681                Integer.parseInt(version);
9682                return true;
9683            } catch (NumberFormatException e) {}
9684        }
9685        return false;
9686    }
9687
9688    // Utility method that returns the relative package path with respect
9689    // to the installation directory. Like say for /data/data/com.test-1.apk
9690    // string com.test-1 is returned.
9691    static String deriveCodePathName(String codePath) {
9692        if (codePath == null) {
9693            return null;
9694        }
9695        final File codeFile = new File(codePath);
9696        final String name = codeFile.getName();
9697        if (codeFile.isDirectory()) {
9698            return name;
9699        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9700            final int lastDot = name.lastIndexOf('.');
9701            return name.substring(0, lastDot);
9702        } else {
9703            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9704            return null;
9705        }
9706    }
9707
9708    class PackageInstalledInfo {
9709        String name;
9710        int uid;
9711        // The set of users that originally had this package installed.
9712        int[] origUsers;
9713        // The set of users that now have this package installed.
9714        int[] newUsers;
9715        PackageParser.Package pkg;
9716        int returnCode;
9717        String returnMsg;
9718        PackageRemovedInfo removedInfo;
9719
9720        public void setError(int code, String msg) {
9721            returnCode = code;
9722            returnMsg = msg;
9723            Slog.w(TAG, msg);
9724        }
9725
9726        public void setError(String msg, PackageParserException e) {
9727            returnCode = e.error;
9728            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9729            Slog.w(TAG, msg, e);
9730        }
9731
9732        public void setError(String msg, PackageManagerException e) {
9733            returnCode = e.error;
9734            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9735            Slog.w(TAG, msg, e);
9736        }
9737
9738        // In some error cases we want to convey more info back to the observer
9739        String origPackage;
9740        String origPermission;
9741    }
9742
9743    /*
9744     * Install a non-existing package.
9745     */
9746    private void installNewPackageLI(PackageParser.Package pkg,
9747            int parseFlags, int scanFlags, UserHandle user,
9748            String installerPackageName, PackageInstalledInfo res) {
9749        // Remember this for later, in case we need to rollback this install
9750        String pkgName = pkg.packageName;
9751
9752        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9753        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9754        synchronized(mPackages) {
9755            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9756                // A package with the same name is already installed, though
9757                // it has been renamed to an older name.  The package we
9758                // are trying to install should be installed as an update to
9759                // the existing one, but that has not been requested, so bail.
9760                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9761                        + " without first uninstalling package running as "
9762                        + mSettings.mRenamedPackages.get(pkgName));
9763                return;
9764            }
9765            if (mPackages.containsKey(pkgName)) {
9766                // Don't allow installation over an existing package with the same name.
9767                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9768                        + " without first uninstalling.");
9769                return;
9770            }
9771        }
9772
9773        try {
9774            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9775                    System.currentTimeMillis(), user);
9776
9777            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9778            // delete the partially installed application. the data directory will have to be
9779            // restored if it was already existing
9780            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9781                // remove package from internal structures.  Note that we want deletePackageX to
9782                // delete the package data and cache directories that it created in
9783                // scanPackageLocked, unless those directories existed before we even tried to
9784                // install.
9785                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9786                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9787                                res.removedInfo, true);
9788            }
9789
9790        } catch (PackageManagerException e) {
9791            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9792        }
9793    }
9794
9795    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9796        // Upgrade keysets are being used.  Determine if new package has a superset of the
9797        // required keys.
9798        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9799        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9800        for (int i = 0; i < upgradeKeySets.length; i++) {
9801            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9802            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9803                return true;
9804            }
9805        }
9806        return false;
9807    }
9808
9809    private void replacePackageLI(PackageParser.Package pkg,
9810            int parseFlags, int scanFlags, UserHandle user,
9811            String installerPackageName, PackageInstalledInfo res) {
9812        PackageParser.Package oldPackage;
9813        String pkgName = pkg.packageName;
9814        int[] allUsers;
9815        boolean[] perUserInstalled;
9816
9817        // First find the old package info and check signatures
9818        synchronized(mPackages) {
9819            oldPackage = mPackages.get(pkgName);
9820            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9821            PackageSetting ps = mSettings.mPackages.get(pkgName);
9822            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9823                // default to original signature matching
9824                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9825                    != PackageManager.SIGNATURE_MATCH) {
9826                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9827                            "New package has a different signature: " + pkgName);
9828                    return;
9829                }
9830            } else {
9831                if(!checkUpgradeKeySetLP(ps, pkg)) {
9832                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9833                            "New package not signed by keys specified by upgrade-keysets: "
9834                            + pkgName);
9835                    return;
9836                }
9837            }
9838
9839            // In case of rollback, remember per-user/profile install state
9840            allUsers = sUserManager.getUserIds();
9841            perUserInstalled = new boolean[allUsers.length];
9842            for (int i = 0; i < allUsers.length; i++) {
9843                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9844            }
9845        }
9846
9847        boolean sysPkg = (isSystemApp(oldPackage));
9848        if (sysPkg) {
9849            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9850                    user, allUsers, perUserInstalled, installerPackageName, res);
9851        } else {
9852            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9853                    user, allUsers, perUserInstalled, installerPackageName, res);
9854        }
9855    }
9856
9857    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9858            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9859            int[] allUsers, boolean[] perUserInstalled,
9860            String installerPackageName, PackageInstalledInfo res) {
9861        String pkgName = deletedPackage.packageName;
9862        boolean deletedPkg = true;
9863        boolean updatedSettings = false;
9864
9865        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9866                + deletedPackage);
9867        long origUpdateTime;
9868        if (pkg.mExtras != null) {
9869            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9870        } else {
9871            origUpdateTime = 0;
9872        }
9873
9874        // First delete the existing package while retaining the data directory
9875        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9876                res.removedInfo, true)) {
9877            // If the existing package wasn't successfully deleted
9878            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9879            deletedPkg = false;
9880        } else {
9881            // Successfully deleted the old package; proceed with replace.
9882
9883            // If deleted package lived in a container, give users a chance to
9884            // relinquish resources before killing.
9885            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9886                if (DEBUG_INSTALL) {
9887                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9888                }
9889                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9890                final ArrayList<String> pkgList = new ArrayList<String>(1);
9891                pkgList.add(deletedPackage.applicationInfo.packageName);
9892                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9893            }
9894
9895            deleteCodeCacheDirsLI(pkgName);
9896            try {
9897                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9898                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9899                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9900                updatedSettings = true;
9901            } catch (PackageManagerException e) {
9902                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9903            }
9904        }
9905
9906        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9907            // remove package from internal structures.  Note that we want deletePackageX to
9908            // delete the package data and cache directories that it created in
9909            // scanPackageLocked, unless those directories existed before we even tried to
9910            // install.
9911            if(updatedSettings) {
9912                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9913                deletePackageLI(
9914                        pkgName, null, true, allUsers, perUserInstalled,
9915                        PackageManager.DELETE_KEEP_DATA,
9916                                res.removedInfo, true);
9917            }
9918            // Since we failed to install the new package we need to restore the old
9919            // package that we deleted.
9920            if (deletedPkg) {
9921                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9922                File restoreFile = new File(deletedPackage.codePath);
9923                // Parse old package
9924                boolean oldOnSd = isExternal(deletedPackage);
9925                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9926                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9927                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9928                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9929                try {
9930                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9931                } catch (PackageManagerException e) {
9932                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9933                            + e.getMessage());
9934                    return;
9935                }
9936                // Restore of old package succeeded. Update permissions.
9937                // writer
9938                synchronized (mPackages) {
9939                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9940                            UPDATE_PERMISSIONS_ALL);
9941                    // can downgrade to reader
9942                    mSettings.writeLPr();
9943                }
9944                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9945            }
9946        }
9947    }
9948
9949    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9950            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9951            int[] allUsers, boolean[] perUserInstalled,
9952            String installerPackageName, PackageInstalledInfo res) {
9953        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9954                + ", old=" + deletedPackage);
9955        boolean updatedSettings = false;
9956        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9957        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9958            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9959        }
9960        String packageName = deletedPackage.packageName;
9961        if (packageName == null) {
9962            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9963                    "Attempt to delete null packageName.");
9964            return;
9965        }
9966        PackageParser.Package oldPkg;
9967        PackageSetting oldPkgSetting;
9968        // reader
9969        synchronized (mPackages) {
9970            oldPkg = mPackages.get(packageName);
9971            oldPkgSetting = mSettings.mPackages.get(packageName);
9972            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9973                    (oldPkgSetting == null)) {
9974                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9975                        "Couldn't find package:" + packageName + " information");
9976                return;
9977            }
9978        }
9979
9980        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9981
9982        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9983        res.removedInfo.removedPackage = packageName;
9984        // Remove existing system package
9985        removePackageLI(oldPkgSetting, true);
9986        // writer
9987        synchronized (mPackages) {
9988            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9989                // We didn't need to disable the .apk as a current system package,
9990                // which means we are replacing another update that is already
9991                // installed.  We need to make sure to delete the older one's .apk.
9992                res.removedInfo.args = createInstallArgsForExisting(0,
9993                        deletedPackage.applicationInfo.getCodePath(),
9994                        deletedPackage.applicationInfo.getResourcePath(),
9995                        deletedPackage.applicationInfo.nativeLibraryRootDir,
9996                        getAppDexInstructionSets(deletedPackage.applicationInfo));
9997            } else {
9998                res.removedInfo.args = null;
9999            }
10000        }
10001
10002        // Successfully disabled the old package. Now proceed with re-installation
10003        deleteCodeCacheDirsLI(packageName);
10004
10005        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10006        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10007
10008        PackageParser.Package newPackage = null;
10009        try {
10010            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10011            if (newPackage.mExtras != null) {
10012                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10013                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10014                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10015
10016                // is the update attempting to change shared user? that isn't going to work...
10017                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10018                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10019                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10020                            + " to " + newPkgSetting.sharedUser);
10021                    updatedSettings = true;
10022                }
10023            }
10024
10025            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10026                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10027                updatedSettings = true;
10028            }
10029
10030        } catch (PackageManagerException e) {
10031            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10032        }
10033
10034        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10035            // Re installation failed. Restore old information
10036            // Remove new pkg information
10037            if (newPackage != null) {
10038                removeInstalledPackageLI(newPackage, true);
10039            }
10040            // Add back the old system package
10041            try {
10042                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10043            } catch (PackageManagerException e) {
10044                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10045            }
10046            // Restore the old system information in Settings
10047            synchronized(mPackages) {
10048                if (updatedSettings) {
10049                    mSettings.enableSystemPackageLPw(packageName);
10050                    mSettings.setInstallerPackageName(packageName,
10051                            oldPkgSetting.installerPackageName);
10052                }
10053                mSettings.writeLPr();
10054            }
10055        }
10056    }
10057
10058    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10059            int[] allUsers, boolean[] perUserInstalled,
10060            PackageInstalledInfo res) {
10061        String pkgName = newPackage.packageName;
10062        synchronized (mPackages) {
10063            //write settings. the installStatus will be incomplete at this stage.
10064            //note that the new package setting would have already been
10065            //added to mPackages. It hasn't been persisted yet.
10066            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10067            mSettings.writeLPr();
10068        }
10069
10070        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10071
10072        synchronized (mPackages) {
10073            updatePermissionsLPw(newPackage.packageName, newPackage,
10074                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10075                            ? UPDATE_PERMISSIONS_ALL : 0));
10076            // For system-bundled packages, we assume that installing an upgraded version
10077            // of the package implies that the user actually wants to run that new code,
10078            // so we enable the package.
10079            if (isSystemApp(newPackage)) {
10080                // NB: implicit assumption that system package upgrades apply to all users
10081                if (DEBUG_INSTALL) {
10082                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10083                }
10084                PackageSetting ps = mSettings.mPackages.get(pkgName);
10085                if (ps != null) {
10086                    if (res.origUsers != null) {
10087                        for (int userHandle : res.origUsers) {
10088                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10089                                    userHandle, installerPackageName);
10090                        }
10091                    }
10092                    // Also convey the prior install/uninstall state
10093                    if (allUsers != null && perUserInstalled != null) {
10094                        for (int i = 0; i < allUsers.length; i++) {
10095                            if (DEBUG_INSTALL) {
10096                                Slog.d(TAG, "    user " + allUsers[i]
10097                                        + " => " + perUserInstalled[i]);
10098                            }
10099                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10100                        }
10101                        // these install state changes will be persisted in the
10102                        // upcoming call to mSettings.writeLPr().
10103                    }
10104                }
10105            }
10106            res.name = pkgName;
10107            res.uid = newPackage.applicationInfo.uid;
10108            res.pkg = newPackage;
10109            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10110            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10111            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10112            //to update install status
10113            mSettings.writeLPr();
10114        }
10115    }
10116
10117    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10118        final int installFlags = args.installFlags;
10119        String installerPackageName = args.installerPackageName;
10120        File tmpPackageFile = new File(args.getCodePath());
10121        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10122        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10123        boolean replace = false;
10124        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10125        // Result object to be returned
10126        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10127
10128        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10129        // Retrieve PackageSettings and parse package
10130        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10131                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10132                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10133        PackageParser pp = new PackageParser();
10134        pp.setSeparateProcesses(mSeparateProcesses);
10135        pp.setDisplayMetrics(mMetrics);
10136
10137        final PackageParser.Package pkg;
10138        try {
10139            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10140        } catch (PackageParserException e) {
10141            res.setError("Failed parse during installPackageLI", e);
10142            return;
10143        }
10144
10145        // Mark that we have an install time CPU ABI override.
10146        pkg.cpuAbiOverride = args.abiOverride;
10147
10148        String pkgName = res.name = pkg.packageName;
10149        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10150            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10151                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10152                return;
10153            }
10154        }
10155
10156        try {
10157            pp.collectCertificates(pkg, parseFlags);
10158            pp.collectManifestDigest(pkg);
10159        } catch (PackageParserException e) {
10160            res.setError("Failed collect during installPackageLI", e);
10161            return;
10162        }
10163
10164        /* If the installer passed in a manifest digest, compare it now. */
10165        if (args.manifestDigest != null) {
10166            if (DEBUG_INSTALL) {
10167                final String parsedManifest = pkg.manifestDigest == null ? "null"
10168                        : pkg.manifestDigest.toString();
10169                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10170                        + parsedManifest);
10171            }
10172
10173            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10174                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10175                return;
10176            }
10177        } else if (DEBUG_INSTALL) {
10178            final String parsedManifest = pkg.manifestDigest == null
10179                    ? "null" : pkg.manifestDigest.toString();
10180            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10181        }
10182
10183        // Get rid of all references to package scan path via parser.
10184        pp = null;
10185        String oldCodePath = null;
10186        boolean systemApp = false;
10187        synchronized (mPackages) {
10188            // Check whether the newly-scanned package wants to define an already-defined perm
10189            int N = pkg.permissions.size();
10190            for (int i = N-1; i >= 0; i--) {
10191                PackageParser.Permission perm = pkg.permissions.get(i);
10192                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10193                if (bp != null) {
10194                    // If the defining package is signed with our cert, it's okay.  This
10195                    // also includes the "updating the same package" case, of course.
10196                    // "updating same package" could also involve key-rotation.
10197                    final boolean sigsOk;
10198                    if (!bp.sourcePackage.equals(pkg.packageName)
10199                            || !(bp.packageSetting instanceof PackageSetting)
10200                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10201                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10202                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10203                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10204                    } else {
10205                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10206                    }
10207                    if (!sigsOk) {
10208                        // If the owning package is the system itself, we log but allow
10209                        // install to proceed; we fail the install on all other permission
10210                        // redefinitions.
10211                        if (!bp.sourcePackage.equals("android")) {
10212                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10213                                    + pkg.packageName + " attempting to redeclare permission "
10214                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10215                            res.origPermission = perm.info.name;
10216                            res.origPackage = bp.sourcePackage;
10217                            return;
10218                        } else {
10219                            Slog.w(TAG, "Package " + pkg.packageName
10220                                    + " attempting to redeclare system permission "
10221                                    + perm.info.name + "; ignoring new declaration");
10222                            pkg.permissions.remove(i);
10223                        }
10224                    }
10225                }
10226            }
10227
10228            // Check if installing already existing package
10229            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10230                String oldName = mSettings.mRenamedPackages.get(pkgName);
10231                if (pkg.mOriginalPackages != null
10232                        && pkg.mOriginalPackages.contains(oldName)
10233                        && mPackages.containsKey(oldName)) {
10234                    // This package is derived from an original package,
10235                    // and this device has been updating from that original
10236                    // name.  We must continue using the original name, so
10237                    // rename the new package here.
10238                    pkg.setPackageName(oldName);
10239                    pkgName = pkg.packageName;
10240                    replace = true;
10241                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10242                            + oldName + " pkgName=" + pkgName);
10243                } else if (mPackages.containsKey(pkgName)) {
10244                    // This package, under its official name, already exists
10245                    // on the device; we should replace it.
10246                    replace = true;
10247                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10248                }
10249            }
10250            PackageSetting ps = mSettings.mPackages.get(pkgName);
10251            if (ps != null) {
10252                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10253                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10254                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10255                    systemApp = (ps.pkg.applicationInfo.flags &
10256                            ApplicationInfo.FLAG_SYSTEM) != 0;
10257                }
10258                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10259            }
10260        }
10261
10262        if (systemApp && onSd) {
10263            // Disable updates to system apps on sdcard
10264            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10265                    "Cannot install updates to system apps on sdcard");
10266            return;
10267        }
10268
10269        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10270            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10271            return;
10272        }
10273
10274        if (replace) {
10275            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10276                    installerPackageName, res);
10277        } else {
10278            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10279                    args.user, installerPackageName, res);
10280        }
10281        synchronized (mPackages) {
10282            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10283            if (ps != null) {
10284                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10285            }
10286        }
10287    }
10288
10289    private static boolean isForwardLocked(PackageParser.Package pkg) {
10290        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10291    }
10292
10293    private static boolean isForwardLocked(ApplicationInfo info) {
10294        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10295    }
10296
10297    private boolean isForwardLocked(PackageSetting ps) {
10298        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10299    }
10300
10301    private static boolean isMultiArch(PackageSetting ps) {
10302        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10303    }
10304
10305    private static boolean isMultiArch(ApplicationInfo info) {
10306        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10307    }
10308
10309    private static boolean isExternal(PackageParser.Package pkg) {
10310        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10311    }
10312
10313    private static boolean isExternal(PackageSetting ps) {
10314        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10315    }
10316
10317    private static boolean isExternal(ApplicationInfo info) {
10318        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10319    }
10320
10321    private static boolean isSystemApp(PackageParser.Package pkg) {
10322        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10323    }
10324
10325    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10326        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10327    }
10328
10329    private static boolean isSystemApp(ApplicationInfo info) {
10330        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10331    }
10332
10333    private static boolean isSystemApp(PackageSetting ps) {
10334        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10335    }
10336
10337    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10338        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10339    }
10340
10341    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10342        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10343    }
10344
10345    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10346        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10347    }
10348
10349    private int packageFlagsToInstallFlags(PackageSetting ps) {
10350        int installFlags = 0;
10351        if (isExternal(ps)) {
10352            installFlags |= PackageManager.INSTALL_EXTERNAL;
10353        }
10354        if (isForwardLocked(ps)) {
10355            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10356        }
10357        return installFlags;
10358    }
10359
10360    private void deleteTempPackageFiles() {
10361        final FilenameFilter filter = new FilenameFilter() {
10362            public boolean accept(File dir, String name) {
10363                return name.startsWith("vmdl") && name.endsWith(".tmp");
10364            }
10365        };
10366        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10367            file.delete();
10368        }
10369    }
10370
10371    @Override
10372    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10373            int flags) {
10374        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10375                flags);
10376    }
10377
10378    @Override
10379    public void deletePackage(final String packageName,
10380            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10381        mContext.enforceCallingOrSelfPermission(
10382                android.Manifest.permission.DELETE_PACKAGES, null);
10383        final int uid = Binder.getCallingUid();
10384        if (UserHandle.getUserId(uid) != userId) {
10385            mContext.enforceCallingPermission(
10386                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10387                    "deletePackage for user " + userId);
10388        }
10389        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10390            try {
10391                observer.onPackageDeleted(packageName,
10392                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10393            } catch (RemoteException re) {
10394            }
10395            return;
10396        }
10397
10398        boolean uninstallBlocked = false;
10399        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10400            int[] users = sUserManager.getUserIds();
10401            for (int i = 0; i < users.length; ++i) {
10402                if (getBlockUninstallForUser(packageName, users[i])) {
10403                    uninstallBlocked = true;
10404                    break;
10405                }
10406            }
10407        } else {
10408            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10409        }
10410        if (uninstallBlocked) {
10411            try {
10412                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10413                        null);
10414            } catch (RemoteException re) {
10415            }
10416            return;
10417        }
10418
10419        if (DEBUG_REMOVE) {
10420            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10421        }
10422        // Queue up an async operation since the package deletion may take a little while.
10423        mHandler.post(new Runnable() {
10424            public void run() {
10425                mHandler.removeCallbacks(this);
10426                final int returnCode = deletePackageX(packageName, userId, flags);
10427                if (observer != null) {
10428                    try {
10429                        observer.onPackageDeleted(packageName, returnCode, null);
10430                    } catch (RemoteException e) {
10431                        Log.i(TAG, "Observer no longer exists.");
10432                    } //end catch
10433                } //end if
10434            } //end run
10435        });
10436    }
10437
10438    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10439        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10440                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10441        try {
10442            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10443                    || dpm.isDeviceOwner(packageName))) {
10444                return true;
10445            }
10446        } catch (RemoteException e) {
10447        }
10448        return false;
10449    }
10450
10451    /**
10452     *  This method is an internal method that could be get invoked either
10453     *  to delete an installed package or to clean up a failed installation.
10454     *  After deleting an installed package, a broadcast is sent to notify any
10455     *  listeners that the package has been installed. For cleaning up a failed
10456     *  installation, the broadcast is not necessary since the package's
10457     *  installation wouldn't have sent the initial broadcast either
10458     *  The key steps in deleting a package are
10459     *  deleting the package information in internal structures like mPackages,
10460     *  deleting the packages base directories through installd
10461     *  updating mSettings to reflect current status
10462     *  persisting settings for later use
10463     *  sending a broadcast if necessary
10464     */
10465    private int deletePackageX(String packageName, int userId, int flags) {
10466        final PackageRemovedInfo info = new PackageRemovedInfo();
10467        final boolean res;
10468
10469        if (isPackageDeviceAdmin(packageName, userId)) {
10470            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10471            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10472        }
10473
10474        boolean removedForAllUsers = false;
10475        boolean systemUpdate = false;
10476
10477        // for the uninstall-updates case and restricted profiles, remember the per-
10478        // userhandle installed state
10479        int[] allUsers;
10480        boolean[] perUserInstalled;
10481        synchronized (mPackages) {
10482            PackageSetting ps = mSettings.mPackages.get(packageName);
10483            allUsers = sUserManager.getUserIds();
10484            perUserInstalled = new boolean[allUsers.length];
10485            for (int i = 0; i < allUsers.length; i++) {
10486                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10487            }
10488        }
10489
10490        synchronized (mInstallLock) {
10491            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10492            res = deletePackageLI(packageName,
10493                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10494                            ? UserHandle.ALL : new UserHandle(userId),
10495                    true, allUsers, perUserInstalled,
10496                    flags | REMOVE_CHATTY, info, true);
10497            systemUpdate = info.isRemovedPackageSystemUpdate;
10498            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10499                removedForAllUsers = true;
10500            }
10501            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10502                    + " removedForAllUsers=" + removedForAllUsers);
10503        }
10504
10505        if (res) {
10506            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10507
10508            // If the removed package was a system update, the old system package
10509            // was re-enabled; we need to broadcast this information
10510            if (systemUpdate) {
10511                Bundle extras = new Bundle(1);
10512                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10513                        ? info.removedAppId : info.uid);
10514                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10515
10516                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10517                        extras, null, null, null);
10518                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10519                        extras, null, null, null);
10520                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10521                        null, packageName, null, null);
10522            }
10523        }
10524        // Force a gc here.
10525        Runtime.getRuntime().gc();
10526        // Delete the resources here after sending the broadcast to let
10527        // other processes clean up before deleting resources.
10528        if (info.args != null) {
10529            synchronized (mInstallLock) {
10530                info.args.doPostDeleteLI(true);
10531            }
10532        }
10533
10534        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10535    }
10536
10537    static class PackageRemovedInfo {
10538        String removedPackage;
10539        int uid = -1;
10540        int removedAppId = -1;
10541        int[] removedUsers = null;
10542        boolean isRemovedPackageSystemUpdate = false;
10543        // Clean up resources deleted packages.
10544        InstallArgs args = null;
10545
10546        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10547            Bundle extras = new Bundle(1);
10548            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10549            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10550            if (replacing) {
10551                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10552            }
10553            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10554            if (removedPackage != null) {
10555                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10556                        extras, null, null, removedUsers);
10557                if (fullRemove && !replacing) {
10558                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10559                            extras, null, null, removedUsers);
10560                }
10561            }
10562            if (removedAppId >= 0) {
10563                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10564                        removedUsers);
10565            }
10566        }
10567    }
10568
10569    /*
10570     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10571     * flag is not set, the data directory is removed as well.
10572     * make sure this flag is set for partially installed apps. If not its meaningless to
10573     * delete a partially installed application.
10574     */
10575    private void removePackageDataLI(PackageSetting ps,
10576            int[] allUserHandles, boolean[] perUserInstalled,
10577            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10578        String packageName = ps.name;
10579        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10580        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10581        // Retrieve object to delete permissions for shared user later on
10582        final PackageSetting deletedPs;
10583        // reader
10584        synchronized (mPackages) {
10585            deletedPs = mSettings.mPackages.get(packageName);
10586            if (outInfo != null) {
10587                outInfo.removedPackage = packageName;
10588                outInfo.removedUsers = deletedPs != null
10589                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10590                        : null;
10591            }
10592        }
10593        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10594            removeDataDirsLI(packageName);
10595            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10596        }
10597        // writer
10598        synchronized (mPackages) {
10599            if (deletedPs != null) {
10600                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10601                    if (outInfo != null) {
10602                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10603                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10604                    }
10605                    if (deletedPs != null) {
10606                        updatePermissionsLPw(deletedPs.name, null, 0);
10607                        if (deletedPs.sharedUser != null) {
10608                            // remove permissions associated with package
10609                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10610                        }
10611                    }
10612                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10613                }
10614                // make sure to preserve per-user disabled state if this removal was just
10615                // a downgrade of a system app to the factory package
10616                if (allUserHandles != null && perUserInstalled != null) {
10617                    if (DEBUG_REMOVE) {
10618                        Slog.d(TAG, "Propagating install state across downgrade");
10619                    }
10620                    for (int i = 0; i < allUserHandles.length; i++) {
10621                        if (DEBUG_REMOVE) {
10622                            Slog.d(TAG, "    user " + allUserHandles[i]
10623                                    + " => " + perUserInstalled[i]);
10624                        }
10625                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10626                    }
10627                }
10628            }
10629            // can downgrade to reader
10630            if (writeSettings) {
10631                // Save settings now
10632                mSettings.writeLPr();
10633            }
10634        }
10635        if (outInfo != null) {
10636            // A user ID was deleted here. Go through all users and remove it
10637            // from KeyStore.
10638            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10639        }
10640    }
10641
10642    static boolean locationIsPrivileged(File path) {
10643        try {
10644            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10645                    .getCanonicalPath();
10646            return path.getCanonicalPath().startsWith(privilegedAppDir);
10647        } catch (IOException e) {
10648            Slog.e(TAG, "Unable to access code path " + path);
10649        }
10650        return false;
10651    }
10652
10653    /*
10654     * Tries to delete system package.
10655     */
10656    private boolean deleteSystemPackageLI(PackageSetting newPs,
10657            int[] allUserHandles, boolean[] perUserInstalled,
10658            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10659        final boolean applyUserRestrictions
10660                = (allUserHandles != null) && (perUserInstalled != null);
10661        PackageSetting disabledPs = null;
10662        // Confirm if the system package has been updated
10663        // An updated system app can be deleted. This will also have to restore
10664        // the system pkg from system partition
10665        // reader
10666        synchronized (mPackages) {
10667            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10668        }
10669        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10670                + " disabledPs=" + disabledPs);
10671        if (disabledPs == null) {
10672            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10673            return false;
10674        } else if (DEBUG_REMOVE) {
10675            Slog.d(TAG, "Deleting system pkg from data partition");
10676        }
10677        if (DEBUG_REMOVE) {
10678            if (applyUserRestrictions) {
10679                Slog.d(TAG, "Remembering install states:");
10680                for (int i = 0; i < allUserHandles.length; i++) {
10681                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10682                }
10683            }
10684        }
10685        // Delete the updated package
10686        outInfo.isRemovedPackageSystemUpdate = true;
10687        if (disabledPs.versionCode < newPs.versionCode) {
10688            // Delete data for downgrades
10689            flags &= ~PackageManager.DELETE_KEEP_DATA;
10690        } else {
10691            // Preserve data by setting flag
10692            flags |= PackageManager.DELETE_KEEP_DATA;
10693        }
10694        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10695                allUserHandles, perUserInstalled, outInfo, writeSettings);
10696        if (!ret) {
10697            return false;
10698        }
10699        // writer
10700        synchronized (mPackages) {
10701            // Reinstate the old system package
10702            mSettings.enableSystemPackageLPw(newPs.name);
10703            // Remove any native libraries from the upgraded package.
10704            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10705        }
10706        // Install the system package
10707        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10708        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10709        if (locationIsPrivileged(disabledPs.codePath)) {
10710            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10711        }
10712
10713        final PackageParser.Package newPkg;
10714        try {
10715            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10716        } catch (PackageManagerException e) {
10717            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10718            return false;
10719        }
10720
10721        // writer
10722        synchronized (mPackages) {
10723            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10724            updatePermissionsLPw(newPkg.packageName, newPkg,
10725                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10726            if (applyUserRestrictions) {
10727                if (DEBUG_REMOVE) {
10728                    Slog.d(TAG, "Propagating install state across reinstall");
10729                }
10730                for (int i = 0; i < allUserHandles.length; i++) {
10731                    if (DEBUG_REMOVE) {
10732                        Slog.d(TAG, "    user " + allUserHandles[i]
10733                                + " => " + perUserInstalled[i]);
10734                    }
10735                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10736                }
10737                // Regardless of writeSettings we need to ensure that this restriction
10738                // state propagation is persisted
10739                mSettings.writeAllUsersPackageRestrictionsLPr();
10740            }
10741            // can downgrade to reader here
10742            if (writeSettings) {
10743                mSettings.writeLPr();
10744            }
10745        }
10746        return true;
10747    }
10748
10749    private boolean deleteInstalledPackageLI(PackageSetting ps,
10750            boolean deleteCodeAndResources, int flags,
10751            int[] allUserHandles, boolean[] perUserInstalled,
10752            PackageRemovedInfo outInfo, boolean writeSettings) {
10753        if (outInfo != null) {
10754            outInfo.uid = ps.appId;
10755        }
10756
10757        // Delete package data from internal structures and also remove data if flag is set
10758        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10759
10760        // Delete application code and resources
10761        if (deleteCodeAndResources && (outInfo != null)) {
10762            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10763                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10764                    getAppDexInstructionSets(ps));
10765            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10766        }
10767        return true;
10768    }
10769
10770    @Override
10771    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10772            int userId) {
10773        mContext.enforceCallingOrSelfPermission(
10774                android.Manifest.permission.DELETE_PACKAGES, null);
10775        synchronized (mPackages) {
10776            PackageSetting ps = mSettings.mPackages.get(packageName);
10777            if (ps == null) {
10778                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10779                return false;
10780            }
10781            if (!ps.getInstalled(userId)) {
10782                // Can't block uninstall for an app that is not installed or enabled.
10783                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10784                return false;
10785            }
10786            ps.setBlockUninstall(blockUninstall, userId);
10787            mSettings.writePackageRestrictionsLPr(userId);
10788        }
10789        return true;
10790    }
10791
10792    @Override
10793    public boolean getBlockUninstallForUser(String packageName, int userId) {
10794        synchronized (mPackages) {
10795            PackageSetting ps = mSettings.mPackages.get(packageName);
10796            if (ps == null) {
10797                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10798                return false;
10799            }
10800            return ps.getBlockUninstall(userId);
10801        }
10802    }
10803
10804    /*
10805     * This method handles package deletion in general
10806     */
10807    private boolean deletePackageLI(String packageName, UserHandle user,
10808            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10809            int flags, PackageRemovedInfo outInfo,
10810            boolean writeSettings) {
10811        if (packageName == null) {
10812            Slog.w(TAG, "Attempt to delete null packageName.");
10813            return false;
10814        }
10815        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10816        PackageSetting ps;
10817        boolean dataOnly = false;
10818        int removeUser = -1;
10819        int appId = -1;
10820        synchronized (mPackages) {
10821            ps = mSettings.mPackages.get(packageName);
10822            if (ps == null) {
10823                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10824                return false;
10825            }
10826            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10827                    && user.getIdentifier() != UserHandle.USER_ALL) {
10828                // The caller is asking that the package only be deleted for a single
10829                // user.  To do this, we just mark its uninstalled state and delete
10830                // its data.  If this is a system app, we only allow this to happen if
10831                // they have set the special DELETE_SYSTEM_APP which requests different
10832                // semantics than normal for uninstalling system apps.
10833                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10834                ps.setUserState(user.getIdentifier(),
10835                        COMPONENT_ENABLED_STATE_DEFAULT,
10836                        false, //installed
10837                        true,  //stopped
10838                        true,  //notLaunched
10839                        false, //hidden
10840                        null, null, null,
10841                        false // blockUninstall
10842                        );
10843                if (!isSystemApp(ps)) {
10844                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10845                        // Other user still have this package installed, so all
10846                        // we need to do is clear this user's data and save that
10847                        // it is uninstalled.
10848                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10849                        removeUser = user.getIdentifier();
10850                        appId = ps.appId;
10851                        mSettings.writePackageRestrictionsLPr(removeUser);
10852                    } else {
10853                        // We need to set it back to 'installed' so the uninstall
10854                        // broadcasts will be sent correctly.
10855                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10856                        ps.setInstalled(true, user.getIdentifier());
10857                    }
10858                } else {
10859                    // This is a system app, so we assume that the
10860                    // other users still have this package installed, so all
10861                    // we need to do is clear this user's data and save that
10862                    // it is uninstalled.
10863                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10864                    removeUser = user.getIdentifier();
10865                    appId = ps.appId;
10866                    mSettings.writePackageRestrictionsLPr(removeUser);
10867                }
10868            }
10869        }
10870
10871        if (removeUser >= 0) {
10872            // From above, we determined that we are deleting this only
10873            // for a single user.  Continue the work here.
10874            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10875            if (outInfo != null) {
10876                outInfo.removedPackage = packageName;
10877                outInfo.removedAppId = appId;
10878                outInfo.removedUsers = new int[] {removeUser};
10879            }
10880            mInstaller.clearUserData(packageName, removeUser);
10881            removeKeystoreDataIfNeeded(removeUser, appId);
10882            schedulePackageCleaning(packageName, removeUser, false);
10883            return true;
10884        }
10885
10886        if (dataOnly) {
10887            // Delete application data first
10888            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10889            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10890            return true;
10891        }
10892
10893        boolean ret = false;
10894        if (isSystemApp(ps)) {
10895            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10896            // When an updated system application is deleted we delete the existing resources as well and
10897            // fall back to existing code in system partition
10898            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10899                    flags, outInfo, writeSettings);
10900        } else {
10901            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10902            // Kill application pre-emptively especially for apps on sd.
10903            killApplication(packageName, ps.appId, "uninstall pkg");
10904            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10905                    allUserHandles, perUserInstalled,
10906                    outInfo, writeSettings);
10907        }
10908
10909        return ret;
10910    }
10911
10912    private final class ClearStorageConnection implements ServiceConnection {
10913        IMediaContainerService mContainerService;
10914
10915        @Override
10916        public void onServiceConnected(ComponentName name, IBinder service) {
10917            synchronized (this) {
10918                mContainerService = IMediaContainerService.Stub.asInterface(service);
10919                notifyAll();
10920            }
10921        }
10922
10923        @Override
10924        public void onServiceDisconnected(ComponentName name) {
10925        }
10926    }
10927
10928    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10929        final boolean mounted;
10930        if (Environment.isExternalStorageEmulated()) {
10931            mounted = true;
10932        } else {
10933            final String status = Environment.getExternalStorageState();
10934
10935            mounted = status.equals(Environment.MEDIA_MOUNTED)
10936                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10937        }
10938
10939        if (!mounted) {
10940            return;
10941        }
10942
10943        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10944        int[] users;
10945        if (userId == UserHandle.USER_ALL) {
10946            users = sUserManager.getUserIds();
10947        } else {
10948            users = new int[] { userId };
10949        }
10950        final ClearStorageConnection conn = new ClearStorageConnection();
10951        if (mContext.bindServiceAsUser(
10952                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10953            try {
10954                for (int curUser : users) {
10955                    long timeout = SystemClock.uptimeMillis() + 5000;
10956                    synchronized (conn) {
10957                        long now = SystemClock.uptimeMillis();
10958                        while (conn.mContainerService == null && now < timeout) {
10959                            try {
10960                                conn.wait(timeout - now);
10961                            } catch (InterruptedException e) {
10962                            }
10963                        }
10964                    }
10965                    if (conn.mContainerService == null) {
10966                        return;
10967                    }
10968
10969                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10970                    clearDirectory(conn.mContainerService,
10971                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10972                    if (allData) {
10973                        clearDirectory(conn.mContainerService,
10974                                userEnv.buildExternalStorageAppDataDirs(packageName));
10975                        clearDirectory(conn.mContainerService,
10976                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10977                    }
10978                }
10979            } finally {
10980                mContext.unbindService(conn);
10981            }
10982        }
10983    }
10984
10985    @Override
10986    public void clearApplicationUserData(final String packageName,
10987            final IPackageDataObserver observer, final int userId) {
10988        mContext.enforceCallingOrSelfPermission(
10989                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10990        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
10991        // Queue up an async operation since the package deletion may take a little while.
10992        mHandler.post(new Runnable() {
10993            public void run() {
10994                mHandler.removeCallbacks(this);
10995                final boolean succeeded;
10996                synchronized (mInstallLock) {
10997                    succeeded = clearApplicationUserDataLI(packageName, userId);
10998                }
10999                clearExternalStorageDataSync(packageName, userId, true);
11000                if (succeeded) {
11001                    // invoke DeviceStorageMonitor's update method to clear any notifications
11002                    DeviceStorageMonitorInternal
11003                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11004                    if (dsm != null) {
11005                        dsm.checkMemory();
11006                    }
11007                }
11008                if(observer != null) {
11009                    try {
11010                        observer.onRemoveCompleted(packageName, succeeded);
11011                    } catch (RemoteException e) {
11012                        Log.i(TAG, "Observer no longer exists.");
11013                    }
11014                } //end if observer
11015            } //end run
11016        });
11017    }
11018
11019    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11020        if (packageName == null) {
11021            Slog.w(TAG, "Attempt to delete null packageName.");
11022            return false;
11023        }
11024
11025        // Try finding details about the requested package
11026        PackageParser.Package pkg;
11027        synchronized (mPackages) {
11028            pkg = mPackages.get(packageName);
11029            if (pkg == null) {
11030                final PackageSetting ps = mSettings.mPackages.get(packageName);
11031                if (ps != null) {
11032                    pkg = ps.pkg;
11033                }
11034            }
11035        }
11036
11037        if (pkg == null) {
11038            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11039        }
11040
11041        // Always delete data directories for package, even if we found no other
11042        // record of app. This helps users recover from UID mismatches without
11043        // resorting to a full data wipe.
11044        int retCode = mInstaller.clearUserData(packageName, userId);
11045        if (retCode < 0) {
11046            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11047            return false;
11048        }
11049
11050        if (pkg == null) {
11051            return false;
11052        }
11053
11054        if (pkg != null && pkg.applicationInfo != null) {
11055            final int appId = pkg.applicationInfo.uid;
11056            removeKeystoreDataIfNeeded(userId, appId);
11057        }
11058
11059        // Create a native library symlink only if we have native libraries
11060        // and if the native libraries are 32 bit libraries. We do not provide
11061        // this symlink for 64 bit libraries.
11062        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11063                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11064            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11065            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11066                Slog.w(TAG, "Failed linking native library dir");
11067                return false;
11068            }
11069        }
11070
11071        return true;
11072    }
11073
11074    /**
11075     * Remove entries from the keystore daemon. Will only remove it if the
11076     * {@code appId} is valid.
11077     */
11078    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11079        if (appId < 0) {
11080            return;
11081        }
11082
11083        final KeyStore keyStore = KeyStore.getInstance();
11084        if (keyStore != null) {
11085            if (userId == UserHandle.USER_ALL) {
11086                for (final int individual : sUserManager.getUserIds()) {
11087                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11088                }
11089            } else {
11090                keyStore.clearUid(UserHandle.getUid(userId, appId));
11091            }
11092        } else {
11093            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11094        }
11095    }
11096
11097    @Override
11098    public void deleteApplicationCacheFiles(final String packageName,
11099            final IPackageDataObserver observer) {
11100        mContext.enforceCallingOrSelfPermission(
11101                android.Manifest.permission.DELETE_CACHE_FILES, null);
11102        // Queue up an async operation since the package deletion may take a little while.
11103        final int userId = UserHandle.getCallingUserId();
11104        mHandler.post(new Runnable() {
11105            public void run() {
11106                mHandler.removeCallbacks(this);
11107                final boolean succeded;
11108                synchronized (mInstallLock) {
11109                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11110                }
11111                clearExternalStorageDataSync(packageName, userId, false);
11112                if(observer != null) {
11113                    try {
11114                        observer.onRemoveCompleted(packageName, succeded);
11115                    } catch (RemoteException e) {
11116                        Log.i(TAG, "Observer no longer exists.");
11117                    }
11118                } //end if observer
11119            } //end run
11120        });
11121    }
11122
11123    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11124        if (packageName == null) {
11125            Slog.w(TAG, "Attempt to delete null packageName.");
11126            return false;
11127        }
11128        PackageParser.Package p;
11129        synchronized (mPackages) {
11130            p = mPackages.get(packageName);
11131        }
11132        if (p == null) {
11133            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11134            return false;
11135        }
11136        final ApplicationInfo applicationInfo = p.applicationInfo;
11137        if (applicationInfo == null) {
11138            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11139            return false;
11140        }
11141        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11142        if (retCode < 0) {
11143            Slog.w(TAG, "Couldn't remove cache files for package: "
11144                       + packageName + " u" + userId);
11145            return false;
11146        }
11147        return true;
11148    }
11149
11150    @Override
11151    public void getPackageSizeInfo(final String packageName, int userHandle,
11152            final IPackageStatsObserver observer) {
11153        mContext.enforceCallingOrSelfPermission(
11154                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11155        if (packageName == null) {
11156            throw new IllegalArgumentException("Attempt to get size of null packageName");
11157        }
11158
11159        PackageStats stats = new PackageStats(packageName, userHandle);
11160
11161        /*
11162         * Queue up an async operation since the package measurement may take a
11163         * little while.
11164         */
11165        Message msg = mHandler.obtainMessage(INIT_COPY);
11166        msg.obj = new MeasureParams(stats, observer);
11167        mHandler.sendMessage(msg);
11168    }
11169
11170    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11171            PackageStats pStats) {
11172        if (packageName == null) {
11173            Slog.w(TAG, "Attempt to get size of null packageName.");
11174            return false;
11175        }
11176        PackageParser.Package p;
11177        boolean dataOnly = false;
11178        String libDirRoot = null;
11179        String asecPath = null;
11180        PackageSetting ps = null;
11181        synchronized (mPackages) {
11182            p = mPackages.get(packageName);
11183            ps = mSettings.mPackages.get(packageName);
11184            if(p == null) {
11185                dataOnly = true;
11186                if((ps == null) || (ps.pkg == null)) {
11187                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11188                    return false;
11189                }
11190                p = ps.pkg;
11191            }
11192            if (ps != null) {
11193                libDirRoot = ps.legacyNativeLibraryPathString;
11194            }
11195            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11196                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11197                if (secureContainerId != null) {
11198                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11199                }
11200            }
11201        }
11202        String publicSrcDir = null;
11203        if(!dataOnly) {
11204            final ApplicationInfo applicationInfo = p.applicationInfo;
11205            if (applicationInfo == null) {
11206                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11207                return false;
11208            }
11209            if (isForwardLocked(p)) {
11210                publicSrcDir = applicationInfo.getBaseResourcePath();
11211            }
11212        }
11213        // TODO: extend to measure size of split APKs
11214        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11215        // not just the first level.
11216        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11217        // just the primary.
11218        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11219        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11220                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11221        if (res < 0) {
11222            return false;
11223        }
11224
11225        // Fix-up for forward-locked applications in ASEC containers.
11226        if (!isExternal(p)) {
11227            pStats.codeSize += pStats.externalCodeSize;
11228            pStats.externalCodeSize = 0L;
11229        }
11230
11231        return true;
11232    }
11233
11234
11235    @Override
11236    public void addPackageToPreferred(String packageName) {
11237        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11238    }
11239
11240    @Override
11241    public void removePackageFromPreferred(String packageName) {
11242        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11243    }
11244
11245    @Override
11246    public List<PackageInfo> getPreferredPackages(int flags) {
11247        return new ArrayList<PackageInfo>();
11248    }
11249
11250    private int getUidTargetSdkVersionLockedLPr(int uid) {
11251        Object obj = mSettings.getUserIdLPr(uid);
11252        if (obj instanceof SharedUserSetting) {
11253            final SharedUserSetting sus = (SharedUserSetting) obj;
11254            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11255            final Iterator<PackageSetting> it = sus.packages.iterator();
11256            while (it.hasNext()) {
11257                final PackageSetting ps = it.next();
11258                if (ps.pkg != null) {
11259                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11260                    if (v < vers) vers = v;
11261                }
11262            }
11263            return vers;
11264        } else if (obj instanceof PackageSetting) {
11265            final PackageSetting ps = (PackageSetting) obj;
11266            if (ps.pkg != null) {
11267                return ps.pkg.applicationInfo.targetSdkVersion;
11268            }
11269        }
11270        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11271    }
11272
11273    @Override
11274    public void addPreferredActivity(IntentFilter filter, int match,
11275            ComponentName[] set, ComponentName activity, int userId) {
11276        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11277                "Adding preferred");
11278    }
11279
11280    private void addPreferredActivityInternal(IntentFilter filter, int match,
11281            ComponentName[] set, ComponentName activity, boolean always, int userId,
11282            String opname) {
11283        // writer
11284        int callingUid = Binder.getCallingUid();
11285        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11286        if (filter.countActions() == 0) {
11287            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11288            return;
11289        }
11290        synchronized (mPackages) {
11291            if (mContext.checkCallingOrSelfPermission(
11292                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11293                    != PackageManager.PERMISSION_GRANTED) {
11294                if (getUidTargetSdkVersionLockedLPr(callingUid)
11295                        < Build.VERSION_CODES.FROYO) {
11296                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11297                            + callingUid);
11298                    return;
11299                }
11300                mContext.enforceCallingOrSelfPermission(
11301                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11302            }
11303
11304            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11305            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11306                    + userId + ":");
11307            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11308            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11309            mSettings.writePackageRestrictionsLPr(userId);
11310        }
11311    }
11312
11313    @Override
11314    public void replacePreferredActivity(IntentFilter filter, int match,
11315            ComponentName[] set, ComponentName activity, int userId) {
11316        if (filter.countActions() != 1) {
11317            throw new IllegalArgumentException(
11318                    "replacePreferredActivity expects filter to have only 1 action.");
11319        }
11320        if (filter.countDataAuthorities() != 0
11321                || filter.countDataPaths() != 0
11322                || filter.countDataSchemes() > 1
11323                || filter.countDataTypes() != 0) {
11324            throw new IllegalArgumentException(
11325                    "replacePreferredActivity expects filter to have no data authorities, " +
11326                    "paths, or types; and at most one scheme.");
11327        }
11328
11329        final int callingUid = Binder.getCallingUid();
11330        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11331        synchronized (mPackages) {
11332            if (mContext.checkCallingOrSelfPermission(
11333                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11334                    != PackageManager.PERMISSION_GRANTED) {
11335                if (getUidTargetSdkVersionLockedLPr(callingUid)
11336                        < Build.VERSION_CODES.FROYO) {
11337                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11338                            + Binder.getCallingUid());
11339                    return;
11340                }
11341                mContext.enforceCallingOrSelfPermission(
11342                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11343            }
11344
11345            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11346            if (pir != null) {
11347                // Get all of the existing entries that exactly match this filter.
11348                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11349                if (existing != null && existing.size() == 1) {
11350                    PreferredActivity cur = existing.get(0);
11351                    if (DEBUG_PREFERRED) {
11352                        Slog.i(TAG, "Checking replace of preferred:");
11353                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11354                        if (!cur.mPref.mAlways) {
11355                            Slog.i(TAG, "  -- CUR; not mAlways!");
11356                        } else {
11357                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11358                            Slog.i(TAG, "  -- CUR: mSet="
11359                                    + Arrays.toString(cur.mPref.mSetComponents));
11360                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11361                            Slog.i(TAG, "  -- NEW: mMatch="
11362                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11363                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11364                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11365                        }
11366                    }
11367                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11368                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11369                            && cur.mPref.sameSet(set)) {
11370                        if (DEBUG_PREFERRED) {
11371                            Slog.i(TAG, "Replacing with same preferred activity "
11372                                    + cur.mPref.mShortComponent + " for user "
11373                                    + userId + ":");
11374                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11375                        } else {
11376                            Slog.i(TAG, "Replacing with same preferred activity "
11377                                    + cur.mPref.mShortComponent + " for user "
11378                                    + userId);
11379                        }
11380                        return;
11381                    }
11382                }
11383
11384                if (existing != null) {
11385                    if (DEBUG_PREFERRED) {
11386                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11387                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11388                    }
11389                    for (int i = 0; i < existing.size(); i++) {
11390                        PreferredActivity pa = existing.get(i);
11391                        if (DEBUG_PREFERRED) {
11392                            Slog.i(TAG, "Removing existing preferred activity "
11393                                    + pa.mPref.mComponent + ":");
11394                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11395                        }
11396                        pir.removeFilter(pa);
11397                    }
11398                }
11399            }
11400            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11401                    "Replacing preferred");
11402        }
11403    }
11404
11405    @Override
11406    public void clearPackagePreferredActivities(String packageName) {
11407        final int uid = Binder.getCallingUid();
11408        // writer
11409        synchronized (mPackages) {
11410            PackageParser.Package pkg = mPackages.get(packageName);
11411            if (pkg == null || pkg.applicationInfo.uid != uid) {
11412                if (mContext.checkCallingOrSelfPermission(
11413                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11414                        != PackageManager.PERMISSION_GRANTED) {
11415                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11416                            < Build.VERSION_CODES.FROYO) {
11417                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11418                                + Binder.getCallingUid());
11419                        return;
11420                    }
11421                    mContext.enforceCallingOrSelfPermission(
11422                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11423                }
11424            }
11425
11426            int user = UserHandle.getCallingUserId();
11427            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11428                mSettings.writePackageRestrictionsLPr(user);
11429                scheduleWriteSettingsLocked();
11430            }
11431        }
11432    }
11433
11434    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11435    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11436        ArrayList<PreferredActivity> removed = null;
11437        boolean changed = false;
11438        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11439            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11440            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11441            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11442                continue;
11443            }
11444            Iterator<PreferredActivity> it = pir.filterIterator();
11445            while (it.hasNext()) {
11446                PreferredActivity pa = it.next();
11447                // Mark entry for removal only if it matches the package name
11448                // and the entry is of type "always".
11449                if (packageName == null ||
11450                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11451                                && pa.mPref.mAlways)) {
11452                    if (removed == null) {
11453                        removed = new ArrayList<PreferredActivity>();
11454                    }
11455                    removed.add(pa);
11456                }
11457            }
11458            if (removed != null) {
11459                for (int j=0; j<removed.size(); j++) {
11460                    PreferredActivity pa = removed.get(j);
11461                    pir.removeFilter(pa);
11462                }
11463                changed = true;
11464            }
11465        }
11466        return changed;
11467    }
11468
11469    @Override
11470    public void resetPreferredActivities(int userId) {
11471        /* TODO: Actually use userId. Why is it being passed in? */
11472        mContext.enforceCallingOrSelfPermission(
11473                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11474        // writer
11475        synchronized (mPackages) {
11476            int user = UserHandle.getCallingUserId();
11477            clearPackagePreferredActivitiesLPw(null, user);
11478            mSettings.readDefaultPreferredAppsLPw(this, user);
11479            mSettings.writePackageRestrictionsLPr(user);
11480            scheduleWriteSettingsLocked();
11481        }
11482    }
11483
11484    @Override
11485    public int getPreferredActivities(List<IntentFilter> outFilters,
11486            List<ComponentName> outActivities, String packageName) {
11487
11488        int num = 0;
11489        final int userId = UserHandle.getCallingUserId();
11490        // reader
11491        synchronized (mPackages) {
11492            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11493            if (pir != null) {
11494                final Iterator<PreferredActivity> it = pir.filterIterator();
11495                while (it.hasNext()) {
11496                    final PreferredActivity pa = it.next();
11497                    if (packageName == null
11498                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11499                                    && pa.mPref.mAlways)) {
11500                        if (outFilters != null) {
11501                            outFilters.add(new IntentFilter(pa));
11502                        }
11503                        if (outActivities != null) {
11504                            outActivities.add(pa.mPref.mComponent);
11505                        }
11506                    }
11507                }
11508            }
11509        }
11510
11511        return num;
11512    }
11513
11514    @Override
11515    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11516            int userId) {
11517        int callingUid = Binder.getCallingUid();
11518        if (callingUid != Process.SYSTEM_UID) {
11519            throw new SecurityException(
11520                    "addPersistentPreferredActivity can only be run by the system");
11521        }
11522        if (filter.countActions() == 0) {
11523            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11524            return;
11525        }
11526        synchronized (mPackages) {
11527            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11528                    " :");
11529            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11530            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11531                    new PersistentPreferredActivity(filter, activity));
11532            mSettings.writePackageRestrictionsLPr(userId);
11533        }
11534    }
11535
11536    @Override
11537    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11538        int callingUid = Binder.getCallingUid();
11539        if (callingUid != Process.SYSTEM_UID) {
11540            throw new SecurityException(
11541                    "clearPackagePersistentPreferredActivities can only be run by the system");
11542        }
11543        ArrayList<PersistentPreferredActivity> removed = null;
11544        boolean changed = false;
11545        synchronized (mPackages) {
11546            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11547                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11548                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11549                        .valueAt(i);
11550                if (userId != thisUserId) {
11551                    continue;
11552                }
11553                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11554                while (it.hasNext()) {
11555                    PersistentPreferredActivity ppa = it.next();
11556                    // Mark entry for removal only if it matches the package name.
11557                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11558                        if (removed == null) {
11559                            removed = new ArrayList<PersistentPreferredActivity>();
11560                        }
11561                        removed.add(ppa);
11562                    }
11563                }
11564                if (removed != null) {
11565                    for (int j=0; j<removed.size(); j++) {
11566                        PersistentPreferredActivity ppa = removed.get(j);
11567                        ppir.removeFilter(ppa);
11568                    }
11569                    changed = true;
11570                }
11571            }
11572
11573            if (changed) {
11574                mSettings.writePackageRestrictionsLPr(userId);
11575            }
11576        }
11577    }
11578
11579    @Override
11580    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11581            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11582        mContext.enforceCallingOrSelfPermission(
11583                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11584        int callingUid = Binder.getCallingUid();
11585        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11586        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11587        if (intentFilter.countActions() == 0) {
11588            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11589            return;
11590        }
11591        synchronized (mPackages) {
11592            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11593                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11594            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11595            mSettings.writePackageRestrictionsLPr(sourceUserId);
11596        }
11597    }
11598
11599    @Override
11600    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11601            int ownerUserId) {
11602        mContext.enforceCallingOrSelfPermission(
11603                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11604        int callingUid = Binder.getCallingUid();
11605        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11606        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11607        int callingUserId = UserHandle.getUserId(callingUid);
11608        synchronized (mPackages) {
11609            CrossProfileIntentResolver resolver =
11610                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11611            HashSet<CrossProfileIntentFilter> set =
11612                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11613            for (CrossProfileIntentFilter filter : set) {
11614                if (filter.getOwnerPackage().equals(ownerPackage)
11615                        && filter.getOwnerUserId() == callingUserId) {
11616                    resolver.removeFilter(filter);
11617                }
11618            }
11619            mSettings.writePackageRestrictionsLPr(sourceUserId);
11620        }
11621    }
11622
11623    // Enforcing that callingUid is owning pkg on userId
11624    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11625        // The system owns everything.
11626        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11627            return;
11628        }
11629        int callingUserId = UserHandle.getUserId(callingUid);
11630        if (callingUserId != userId) {
11631            throw new SecurityException("calling uid " + callingUid
11632                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11633                    + callingUserId);
11634        }
11635        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11636        if (pi == null) {
11637            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11638                    + callingUserId);
11639        }
11640        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11641            throw new SecurityException("Calling uid " + callingUid
11642                    + " does not own package " + pkg);
11643        }
11644    }
11645
11646    @Override
11647    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11648        Intent intent = new Intent(Intent.ACTION_MAIN);
11649        intent.addCategory(Intent.CATEGORY_HOME);
11650
11651        final int callingUserId = UserHandle.getCallingUserId();
11652        List<ResolveInfo> list = queryIntentActivities(intent, null,
11653                PackageManager.GET_META_DATA, callingUserId);
11654        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11655                true, false, false, callingUserId);
11656
11657        allHomeCandidates.clear();
11658        if (list != null) {
11659            for (ResolveInfo ri : list) {
11660                allHomeCandidates.add(ri);
11661            }
11662        }
11663        return (preferred == null || preferred.activityInfo == null)
11664                ? null
11665                : new ComponentName(preferred.activityInfo.packageName,
11666                        preferred.activityInfo.name);
11667    }
11668
11669    @Override
11670    public void setApplicationEnabledSetting(String appPackageName,
11671            int newState, int flags, int userId, String callingPackage) {
11672        if (!sUserManager.exists(userId)) return;
11673        if (callingPackage == null) {
11674            callingPackage = Integer.toString(Binder.getCallingUid());
11675        }
11676        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11677    }
11678
11679    @Override
11680    public void setComponentEnabledSetting(ComponentName componentName,
11681            int newState, int flags, int userId) {
11682        if (!sUserManager.exists(userId)) return;
11683        setEnabledSetting(componentName.getPackageName(),
11684                componentName.getClassName(), newState, flags, userId, null);
11685    }
11686
11687    private void setEnabledSetting(final String packageName, String className, int newState,
11688            final int flags, int userId, String callingPackage) {
11689        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11690              || newState == COMPONENT_ENABLED_STATE_ENABLED
11691              || newState == COMPONENT_ENABLED_STATE_DISABLED
11692              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11693              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11694            throw new IllegalArgumentException("Invalid new component state: "
11695                    + newState);
11696        }
11697        PackageSetting pkgSetting;
11698        final int uid = Binder.getCallingUid();
11699        final int permission = mContext.checkCallingOrSelfPermission(
11700                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11701        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11702        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11703        boolean sendNow = false;
11704        boolean isApp = (className == null);
11705        String componentName = isApp ? packageName : className;
11706        int packageUid = -1;
11707        ArrayList<String> components;
11708
11709        // writer
11710        synchronized (mPackages) {
11711            pkgSetting = mSettings.mPackages.get(packageName);
11712            if (pkgSetting == null) {
11713                if (className == null) {
11714                    throw new IllegalArgumentException(
11715                            "Unknown package: " + packageName);
11716                }
11717                throw new IllegalArgumentException(
11718                        "Unknown component: " + packageName
11719                        + "/" + className);
11720            }
11721            // Allow root and verify that userId is not being specified by a different user
11722            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11723                throw new SecurityException(
11724                        "Permission Denial: attempt to change component state from pid="
11725                        + Binder.getCallingPid()
11726                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11727            }
11728            if (className == null) {
11729                // We're dealing with an application/package level state change
11730                if (pkgSetting.getEnabled(userId) == newState) {
11731                    // Nothing to do
11732                    return;
11733                }
11734                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11735                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11736                    // Don't care about who enables an app.
11737                    callingPackage = null;
11738                }
11739                pkgSetting.setEnabled(newState, userId, callingPackage);
11740                // pkgSetting.pkg.mSetEnabled = newState;
11741            } else {
11742                // We're dealing with a component level state change
11743                // First, verify that this is a valid class name.
11744                PackageParser.Package pkg = pkgSetting.pkg;
11745                if (pkg == null || !pkg.hasComponentClassName(className)) {
11746                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11747                        throw new IllegalArgumentException("Component class " + className
11748                                + " does not exist in " + packageName);
11749                    } else {
11750                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11751                                + className + " does not exist in " + packageName);
11752                    }
11753                }
11754                switch (newState) {
11755                case COMPONENT_ENABLED_STATE_ENABLED:
11756                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11757                        return;
11758                    }
11759                    break;
11760                case COMPONENT_ENABLED_STATE_DISABLED:
11761                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11762                        return;
11763                    }
11764                    break;
11765                case COMPONENT_ENABLED_STATE_DEFAULT:
11766                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11767                        return;
11768                    }
11769                    break;
11770                default:
11771                    Slog.e(TAG, "Invalid new component state: " + newState);
11772                    return;
11773                }
11774            }
11775            mSettings.writePackageRestrictionsLPr(userId);
11776            components = mPendingBroadcasts.get(userId, packageName);
11777            final boolean newPackage = components == null;
11778            if (newPackage) {
11779                components = new ArrayList<String>();
11780            }
11781            if (!components.contains(componentName)) {
11782                components.add(componentName);
11783            }
11784            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11785                sendNow = true;
11786                // Purge entry from pending broadcast list if another one exists already
11787                // since we are sending one right away.
11788                mPendingBroadcasts.remove(userId, packageName);
11789            } else {
11790                if (newPackage) {
11791                    mPendingBroadcasts.put(userId, packageName, components);
11792                }
11793                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11794                    // Schedule a message
11795                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11796                }
11797            }
11798        }
11799
11800        long callingId = Binder.clearCallingIdentity();
11801        try {
11802            if (sendNow) {
11803                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11804                sendPackageChangedBroadcast(packageName,
11805                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11806            }
11807        } finally {
11808            Binder.restoreCallingIdentity(callingId);
11809        }
11810    }
11811
11812    private void sendPackageChangedBroadcast(String packageName,
11813            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11814        if (DEBUG_INSTALL)
11815            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11816                    + componentNames);
11817        Bundle extras = new Bundle(4);
11818        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11819        String nameList[] = new String[componentNames.size()];
11820        componentNames.toArray(nameList);
11821        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11822        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11823        extras.putInt(Intent.EXTRA_UID, packageUid);
11824        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11825                new int[] {UserHandle.getUserId(packageUid)});
11826    }
11827
11828    @Override
11829    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11830        if (!sUserManager.exists(userId)) return;
11831        final int uid = Binder.getCallingUid();
11832        final int permission = mContext.checkCallingOrSelfPermission(
11833                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11834        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11835        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11836        // writer
11837        synchronized (mPackages) {
11838            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11839                    uid, userId)) {
11840                scheduleWritePackageRestrictionsLocked(userId);
11841            }
11842        }
11843    }
11844
11845    @Override
11846    public String getInstallerPackageName(String packageName) {
11847        // reader
11848        synchronized (mPackages) {
11849            return mSettings.getInstallerPackageNameLPr(packageName);
11850        }
11851    }
11852
11853    @Override
11854    public int getApplicationEnabledSetting(String packageName, int userId) {
11855        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11856        int uid = Binder.getCallingUid();
11857        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11858        // reader
11859        synchronized (mPackages) {
11860            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11861        }
11862    }
11863
11864    @Override
11865    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11866        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11867        int uid = Binder.getCallingUid();
11868        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11869        // reader
11870        synchronized (mPackages) {
11871            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11872        }
11873    }
11874
11875    @Override
11876    public void enterSafeMode() {
11877        enforceSystemOrRoot("Only the system can request entering safe mode");
11878
11879        if (!mSystemReady) {
11880            mSafeMode = true;
11881        }
11882    }
11883
11884    @Override
11885    public void systemReady() {
11886        mSystemReady = true;
11887
11888        // Read the compatibilty setting when the system is ready.
11889        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11890                mContext.getContentResolver(),
11891                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11892        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11893        if (DEBUG_SETTINGS) {
11894            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11895        }
11896
11897        synchronized (mPackages) {
11898            // Verify that all of the preferred activity components actually
11899            // exist.  It is possible for applications to be updated and at
11900            // that point remove a previously declared activity component that
11901            // had been set as a preferred activity.  We try to clean this up
11902            // the next time we encounter that preferred activity, but it is
11903            // possible for the user flow to never be able to return to that
11904            // situation so here we do a sanity check to make sure we haven't
11905            // left any junk around.
11906            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11907            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11908                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11909                removed.clear();
11910                for (PreferredActivity pa : pir.filterSet()) {
11911                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11912                        removed.add(pa);
11913                    }
11914                }
11915                if (removed.size() > 0) {
11916                    for (int r=0; r<removed.size(); r++) {
11917                        PreferredActivity pa = removed.get(r);
11918                        Slog.w(TAG, "Removing dangling preferred activity: "
11919                                + pa.mPref.mComponent);
11920                        pir.removeFilter(pa);
11921                    }
11922                    mSettings.writePackageRestrictionsLPr(
11923                            mSettings.mPreferredActivities.keyAt(i));
11924                }
11925            }
11926        }
11927        sUserManager.systemReady();
11928
11929        // Kick off any messages waiting for system ready
11930        if (mPostSystemReadyMessages != null) {
11931            for (Message msg : mPostSystemReadyMessages) {
11932                msg.sendToTarget();
11933            }
11934            mPostSystemReadyMessages = null;
11935        }
11936    }
11937
11938    @Override
11939    public boolean isSafeMode() {
11940        return mSafeMode;
11941    }
11942
11943    @Override
11944    public boolean hasSystemUidErrors() {
11945        return mHasSystemUidErrors;
11946    }
11947
11948    static String arrayToString(int[] array) {
11949        StringBuffer buf = new StringBuffer(128);
11950        buf.append('[');
11951        if (array != null) {
11952            for (int i=0; i<array.length; i++) {
11953                if (i > 0) buf.append(", ");
11954                buf.append(array[i]);
11955            }
11956        }
11957        buf.append(']');
11958        return buf.toString();
11959    }
11960
11961    static class DumpState {
11962        public static final int DUMP_LIBS = 1 << 0;
11963        public static final int DUMP_FEATURES = 1 << 1;
11964        public static final int DUMP_RESOLVERS = 1 << 2;
11965        public static final int DUMP_PERMISSIONS = 1 << 3;
11966        public static final int DUMP_PACKAGES = 1 << 4;
11967        public static final int DUMP_SHARED_USERS = 1 << 5;
11968        public static final int DUMP_MESSAGES = 1 << 6;
11969        public static final int DUMP_PROVIDERS = 1 << 7;
11970        public static final int DUMP_VERIFIERS = 1 << 8;
11971        public static final int DUMP_PREFERRED = 1 << 9;
11972        public static final int DUMP_PREFERRED_XML = 1 << 10;
11973        public static final int DUMP_KEYSETS = 1 << 11;
11974        public static final int DUMP_VERSION = 1 << 12;
11975        public static final int DUMP_INSTALLS = 1 << 13;
11976
11977        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11978
11979        private int mTypes;
11980
11981        private int mOptions;
11982
11983        private boolean mTitlePrinted;
11984
11985        private SharedUserSetting mSharedUser;
11986
11987        public boolean isDumping(int type) {
11988            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11989                return true;
11990            }
11991
11992            return (mTypes & type) != 0;
11993        }
11994
11995        public void setDump(int type) {
11996            mTypes |= type;
11997        }
11998
11999        public boolean isOptionEnabled(int option) {
12000            return (mOptions & option) != 0;
12001        }
12002
12003        public void setOptionEnabled(int option) {
12004            mOptions |= option;
12005        }
12006
12007        public boolean onTitlePrinted() {
12008            final boolean printed = mTitlePrinted;
12009            mTitlePrinted = true;
12010            return printed;
12011        }
12012
12013        public boolean getTitlePrinted() {
12014            return mTitlePrinted;
12015        }
12016
12017        public void setTitlePrinted(boolean enabled) {
12018            mTitlePrinted = enabled;
12019        }
12020
12021        public SharedUserSetting getSharedUser() {
12022            return mSharedUser;
12023        }
12024
12025        public void setSharedUser(SharedUserSetting user) {
12026            mSharedUser = user;
12027        }
12028    }
12029
12030    @Override
12031    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12032        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12033                != PackageManager.PERMISSION_GRANTED) {
12034            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12035                    + Binder.getCallingPid()
12036                    + ", uid=" + Binder.getCallingUid()
12037                    + " without permission "
12038                    + android.Manifest.permission.DUMP);
12039            return;
12040        }
12041
12042        DumpState dumpState = new DumpState();
12043        boolean fullPreferred = false;
12044        boolean checkin = false;
12045
12046        String packageName = null;
12047
12048        int opti = 0;
12049        while (opti < args.length) {
12050            String opt = args[opti];
12051            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12052                break;
12053            }
12054            opti++;
12055            if ("-a".equals(opt)) {
12056                // Right now we only know how to print all.
12057            } else if ("-h".equals(opt)) {
12058                pw.println("Package manager dump options:");
12059                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12060                pw.println("    --checkin: dump for a checkin");
12061                pw.println("    -f: print details of intent filters");
12062                pw.println("    -h: print this help");
12063                pw.println("  cmd may be one of:");
12064                pw.println("    l[ibraries]: list known shared libraries");
12065                pw.println("    f[ibraries]: list device features");
12066                pw.println("    k[eysets]: print known keysets");
12067                pw.println("    r[esolvers]: dump intent resolvers");
12068                pw.println("    perm[issions]: dump permissions");
12069                pw.println("    pref[erred]: print preferred package settings");
12070                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12071                pw.println("    prov[iders]: dump content providers");
12072                pw.println("    p[ackages]: dump installed packages");
12073                pw.println("    s[hared-users]: dump shared user IDs");
12074                pw.println("    m[essages]: print collected runtime messages");
12075                pw.println("    v[erifiers]: print package verifier info");
12076                pw.println("    version: print database version info");
12077                pw.println("    write: write current settings now");
12078                pw.println("    <package.name>: info about given package");
12079                pw.println("    installs: details about install sessions");
12080                return;
12081            } else if ("--checkin".equals(opt)) {
12082                checkin = true;
12083            } else if ("-f".equals(opt)) {
12084                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12085            } else {
12086                pw.println("Unknown argument: " + opt + "; use -h for help");
12087            }
12088        }
12089
12090        // Is the caller requesting to dump a particular piece of data?
12091        if (opti < args.length) {
12092            String cmd = args[opti];
12093            opti++;
12094            // Is this a package name?
12095            if ("android".equals(cmd) || cmd.contains(".")) {
12096                packageName = cmd;
12097                // When dumping a single package, we always dump all of its
12098                // filter information since the amount of data will be reasonable.
12099                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12100            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12101                dumpState.setDump(DumpState.DUMP_LIBS);
12102            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12103                dumpState.setDump(DumpState.DUMP_FEATURES);
12104            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12105                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12106            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12107                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12108            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12109                dumpState.setDump(DumpState.DUMP_PREFERRED);
12110            } else if ("preferred-xml".equals(cmd)) {
12111                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12112                if (opti < args.length && "--full".equals(args[opti])) {
12113                    fullPreferred = true;
12114                    opti++;
12115                }
12116            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12117                dumpState.setDump(DumpState.DUMP_PACKAGES);
12118            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12119                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12120            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12121                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12122            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12123                dumpState.setDump(DumpState.DUMP_MESSAGES);
12124            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12125                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12126            } else if ("version".equals(cmd)) {
12127                dumpState.setDump(DumpState.DUMP_VERSION);
12128            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12129                dumpState.setDump(DumpState.DUMP_KEYSETS);
12130            } else if ("installs".equals(cmd)) {
12131                dumpState.setDump(DumpState.DUMP_INSTALLS);
12132            } else if ("write".equals(cmd)) {
12133                synchronized (mPackages) {
12134                    mSettings.writeLPr();
12135                    pw.println("Settings written.");
12136                    return;
12137                }
12138            }
12139        }
12140
12141        if (checkin) {
12142            pw.println("vers,1");
12143        }
12144
12145        // reader
12146        synchronized (mPackages) {
12147            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12148                if (!checkin) {
12149                    if (dumpState.onTitlePrinted())
12150                        pw.println();
12151                    pw.println("Database versions:");
12152                    pw.print("  SDK Version:");
12153                    pw.print(" internal=");
12154                    pw.print(mSettings.mInternalSdkPlatform);
12155                    pw.print(" external=");
12156                    pw.println(mSettings.mExternalSdkPlatform);
12157                    pw.print("  DB Version:");
12158                    pw.print(" internal=");
12159                    pw.print(mSettings.mInternalDatabaseVersion);
12160                    pw.print(" external=");
12161                    pw.println(mSettings.mExternalDatabaseVersion);
12162                }
12163            }
12164
12165            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12166                if (!checkin) {
12167                    if (dumpState.onTitlePrinted())
12168                        pw.println();
12169                    pw.println("Verifiers:");
12170                    pw.print("  Required: ");
12171                    pw.print(mRequiredVerifierPackage);
12172                    pw.print(" (uid=");
12173                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12174                    pw.println(")");
12175                } else if (mRequiredVerifierPackage != null) {
12176                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12177                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12178                }
12179            }
12180
12181            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12182                boolean printedHeader = false;
12183                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12184                while (it.hasNext()) {
12185                    String name = it.next();
12186                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12187                    if (!checkin) {
12188                        if (!printedHeader) {
12189                            if (dumpState.onTitlePrinted())
12190                                pw.println();
12191                            pw.println("Libraries:");
12192                            printedHeader = true;
12193                        }
12194                        pw.print("  ");
12195                    } else {
12196                        pw.print("lib,");
12197                    }
12198                    pw.print(name);
12199                    if (!checkin) {
12200                        pw.print(" -> ");
12201                    }
12202                    if (ent.path != null) {
12203                        if (!checkin) {
12204                            pw.print("(jar) ");
12205                            pw.print(ent.path);
12206                        } else {
12207                            pw.print(",jar,");
12208                            pw.print(ent.path);
12209                        }
12210                    } else {
12211                        if (!checkin) {
12212                            pw.print("(apk) ");
12213                            pw.print(ent.apk);
12214                        } else {
12215                            pw.print(",apk,");
12216                            pw.print(ent.apk);
12217                        }
12218                    }
12219                    pw.println();
12220                }
12221            }
12222
12223            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12224                if (dumpState.onTitlePrinted())
12225                    pw.println();
12226                if (!checkin) {
12227                    pw.println("Features:");
12228                }
12229                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12230                while (it.hasNext()) {
12231                    String name = it.next();
12232                    if (!checkin) {
12233                        pw.print("  ");
12234                    } else {
12235                        pw.print("feat,");
12236                    }
12237                    pw.println(name);
12238                }
12239            }
12240
12241            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12242                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12243                        : "Activity Resolver Table:", "  ", packageName,
12244                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12245                    dumpState.setTitlePrinted(true);
12246                }
12247                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12248                        : "Receiver Resolver Table:", "  ", packageName,
12249                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12250                    dumpState.setTitlePrinted(true);
12251                }
12252                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12253                        : "Service Resolver Table:", "  ", packageName,
12254                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12255                    dumpState.setTitlePrinted(true);
12256                }
12257                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12258                        : "Provider Resolver Table:", "  ", packageName,
12259                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12260                    dumpState.setTitlePrinted(true);
12261                }
12262            }
12263
12264            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12265                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12266                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12267                    int user = mSettings.mPreferredActivities.keyAt(i);
12268                    if (pir.dump(pw,
12269                            dumpState.getTitlePrinted()
12270                                ? "\nPreferred Activities User " + user + ":"
12271                                : "Preferred Activities User " + user + ":", "  ",
12272                            packageName, true)) {
12273                        dumpState.setTitlePrinted(true);
12274                    }
12275                }
12276            }
12277
12278            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12279                pw.flush();
12280                FileOutputStream fout = new FileOutputStream(fd);
12281                BufferedOutputStream str = new BufferedOutputStream(fout);
12282                XmlSerializer serializer = new FastXmlSerializer();
12283                try {
12284                    serializer.setOutput(str, "utf-8");
12285                    serializer.startDocument(null, true);
12286                    serializer.setFeature(
12287                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12288                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12289                    serializer.endDocument();
12290                    serializer.flush();
12291                } catch (IllegalArgumentException e) {
12292                    pw.println("Failed writing: " + e);
12293                } catch (IllegalStateException e) {
12294                    pw.println("Failed writing: " + e);
12295                } catch (IOException e) {
12296                    pw.println("Failed writing: " + e);
12297                }
12298            }
12299
12300            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12301                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12302                if (packageName == null) {
12303                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12304                        if (iperm == 0) {
12305                            if (dumpState.onTitlePrinted())
12306                                pw.println();
12307                            pw.println("AppOp Permissions:");
12308                        }
12309                        pw.print("  AppOp Permission ");
12310                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12311                        pw.println(":");
12312                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12313                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12314                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12315                        }
12316                    }
12317                }
12318            }
12319
12320            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12321                boolean printedSomething = false;
12322                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12323                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12324                        continue;
12325                    }
12326                    if (!printedSomething) {
12327                        if (dumpState.onTitlePrinted())
12328                            pw.println();
12329                        pw.println("Registered ContentProviders:");
12330                        printedSomething = true;
12331                    }
12332                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12333                    pw.print("    "); pw.println(p.toString());
12334                }
12335                printedSomething = false;
12336                for (Map.Entry<String, PackageParser.Provider> entry :
12337                        mProvidersByAuthority.entrySet()) {
12338                    PackageParser.Provider p = entry.getValue();
12339                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12340                        continue;
12341                    }
12342                    if (!printedSomething) {
12343                        if (dumpState.onTitlePrinted())
12344                            pw.println();
12345                        pw.println("ContentProvider Authorities:");
12346                        printedSomething = true;
12347                    }
12348                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12349                    pw.print("    "); pw.println(p.toString());
12350                    if (p.info != null && p.info.applicationInfo != null) {
12351                        final String appInfo = p.info.applicationInfo.toString();
12352                        pw.print("      applicationInfo="); pw.println(appInfo);
12353                    }
12354                }
12355            }
12356
12357            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12358                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12359            }
12360
12361            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12362                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12363            }
12364
12365            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12366                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12367            }
12368
12369            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12370                // XXX should handle packageName != null by dumping only install data that
12371                // the given package is involved with.
12372                if (dumpState.onTitlePrinted()) pw.println();
12373                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12374            }
12375
12376            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12377                if (dumpState.onTitlePrinted()) pw.println();
12378                mSettings.dumpReadMessagesLPr(pw, dumpState);
12379
12380                pw.println();
12381                pw.println("Package warning messages:");
12382                final File fname = getSettingsProblemFile();
12383                FileInputStream in = null;
12384                try {
12385                    in = new FileInputStream(fname);
12386                    final int avail = in.available();
12387                    final byte[] data = new byte[avail];
12388                    in.read(data);
12389                    pw.print(new String(data));
12390                } catch (FileNotFoundException e) {
12391                } catch (IOException e) {
12392                } finally {
12393                    if (in != null) {
12394                        try {
12395                            in.close();
12396                        } catch (IOException e) {
12397                        }
12398                    }
12399                }
12400            }
12401        }
12402    }
12403
12404    // ------- apps on sdcard specific code -------
12405    static final boolean DEBUG_SD_INSTALL = false;
12406
12407    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12408
12409    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12410
12411    private boolean mMediaMounted = false;
12412
12413    static String getEncryptKey() {
12414        try {
12415            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12416                    SD_ENCRYPTION_KEYSTORE_NAME);
12417            if (sdEncKey == null) {
12418                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12419                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12420                if (sdEncKey == null) {
12421                    Slog.e(TAG, "Failed to create encryption keys");
12422                    return null;
12423                }
12424            }
12425            return sdEncKey;
12426        } catch (NoSuchAlgorithmException nsae) {
12427            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12428            return null;
12429        } catch (IOException ioe) {
12430            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12431            return null;
12432        }
12433    }
12434
12435    /*
12436     * Update media status on PackageManager.
12437     */
12438    @Override
12439    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12440        int callingUid = Binder.getCallingUid();
12441        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12442            throw new SecurityException("Media status can only be updated by the system");
12443        }
12444        // reader; this apparently protects mMediaMounted, but should probably
12445        // be a different lock in that case.
12446        synchronized (mPackages) {
12447            Log.i(TAG, "Updating external media status from "
12448                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12449                    + (mediaStatus ? "mounted" : "unmounted"));
12450            if (DEBUG_SD_INSTALL)
12451                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12452                        + ", mMediaMounted=" + mMediaMounted);
12453            if (mediaStatus == mMediaMounted) {
12454                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12455                        : 0, -1);
12456                mHandler.sendMessage(msg);
12457                return;
12458            }
12459            mMediaMounted = mediaStatus;
12460        }
12461        // Queue up an async operation since the package installation may take a
12462        // little while.
12463        mHandler.post(new Runnable() {
12464            public void run() {
12465                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12466            }
12467        });
12468    }
12469
12470    /**
12471     * Called by MountService when the initial ASECs to scan are available.
12472     * Should block until all the ASEC containers are finished being scanned.
12473     */
12474    public void scanAvailableAsecs() {
12475        updateExternalMediaStatusInner(true, false, false);
12476        if (mShouldRestoreconData) {
12477            SELinuxMMAC.setRestoreconDone();
12478            mShouldRestoreconData = false;
12479        }
12480    }
12481
12482    /*
12483     * Collect information of applications on external media, map them against
12484     * existing containers and update information based on current mount status.
12485     * Please note that we always have to report status if reportStatus has been
12486     * set to true especially when unloading packages.
12487     */
12488    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12489            boolean externalStorage) {
12490        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12491        int[] uidArr = EmptyArray.INT;
12492
12493        final String[] list = PackageHelper.getSecureContainerList();
12494        if (ArrayUtils.isEmpty(list)) {
12495            Log.i(TAG, "No secure containers found");
12496        } else {
12497            // Process list of secure containers and categorize them
12498            // as active or stale based on their package internal state.
12499
12500            // reader
12501            synchronized (mPackages) {
12502                for (String cid : list) {
12503                    // Leave stages untouched for now; installer service owns them
12504                    if (PackageInstallerService.isStageName(cid)) continue;
12505
12506                    if (DEBUG_SD_INSTALL)
12507                        Log.i(TAG, "Processing container " + cid);
12508                    String pkgName = getAsecPackageName(cid);
12509                    if (pkgName == null) {
12510                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12511                        continue;
12512                    }
12513                    if (DEBUG_SD_INSTALL)
12514                        Log.i(TAG, "Looking for pkg : " + pkgName);
12515
12516                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12517                    if (ps == null) {
12518                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12519                        continue;
12520                    }
12521
12522                    /*
12523                     * Skip packages that are not external if we're unmounting
12524                     * external storage.
12525                     */
12526                    if (externalStorage && !isMounted && !isExternal(ps)) {
12527                        continue;
12528                    }
12529
12530                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12531                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12532                    // The package status is changed only if the code path
12533                    // matches between settings and the container id.
12534                    if (ps.codePathString != null
12535                            && ps.codePathString.startsWith(args.getCodePath())) {
12536                        if (DEBUG_SD_INSTALL) {
12537                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12538                                    + " at code path: " + ps.codePathString);
12539                        }
12540
12541                        // We do have a valid package installed on sdcard
12542                        processCids.put(args, ps.codePathString);
12543                        final int uid = ps.appId;
12544                        if (uid != -1) {
12545                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12546                        }
12547                    } else {
12548                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12549                                + ps.codePathString);
12550                    }
12551                }
12552            }
12553
12554            Arrays.sort(uidArr);
12555        }
12556
12557        // Process packages with valid entries.
12558        if (isMounted) {
12559            if (DEBUG_SD_INSTALL)
12560                Log.i(TAG, "Loading packages");
12561            loadMediaPackages(processCids, uidArr);
12562            startCleaningPackages();
12563            mInstallerService.onSecureContainersAvailable();
12564        } else {
12565            if (DEBUG_SD_INSTALL)
12566                Log.i(TAG, "Unloading packages");
12567            unloadMediaPackages(processCids, uidArr, reportStatus);
12568        }
12569    }
12570
12571    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12572            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12573        int size = pkgList.size();
12574        if (size > 0) {
12575            // Send broadcasts here
12576            Bundle extras = new Bundle();
12577            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12578                    .toArray(new String[size]));
12579            if (uidArr != null) {
12580                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12581            }
12582            if (replacing) {
12583                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12584            }
12585            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12586                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12587            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12588        }
12589    }
12590
12591   /*
12592     * Look at potentially valid container ids from processCids If package
12593     * information doesn't match the one on record or package scanning fails,
12594     * the cid is added to list of removeCids. We currently don't delete stale
12595     * containers.
12596     */
12597    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12598        ArrayList<String> pkgList = new ArrayList<String>();
12599        Set<AsecInstallArgs> keys = processCids.keySet();
12600
12601        for (AsecInstallArgs args : keys) {
12602            String codePath = processCids.get(args);
12603            if (DEBUG_SD_INSTALL)
12604                Log.i(TAG, "Loading container : " + args.cid);
12605            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12606            try {
12607                // Make sure there are no container errors first.
12608                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12609                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12610                            + " when installing from sdcard");
12611                    continue;
12612                }
12613                // Check code path here.
12614                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12615                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12616                            + " does not match one in settings " + codePath);
12617                    continue;
12618                }
12619                // Parse package
12620                int parseFlags = mDefParseFlags;
12621                if (args.isExternal()) {
12622                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12623                }
12624                if (args.isFwdLocked()) {
12625                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12626                }
12627
12628                synchronized (mInstallLock) {
12629                    PackageParser.Package pkg = null;
12630                    try {
12631                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12632                    } catch (PackageManagerException e) {
12633                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12634                    }
12635                    // Scan the package
12636                    if (pkg != null) {
12637                        /*
12638                         * TODO why is the lock being held? doPostInstall is
12639                         * called in other places without the lock. This needs
12640                         * to be straightened out.
12641                         */
12642                        // writer
12643                        synchronized (mPackages) {
12644                            retCode = PackageManager.INSTALL_SUCCEEDED;
12645                            pkgList.add(pkg.packageName);
12646                            // Post process args
12647                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12648                                    pkg.applicationInfo.uid);
12649                        }
12650                    } else {
12651                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12652                    }
12653                }
12654
12655            } finally {
12656                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12657                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12658                }
12659            }
12660        }
12661        // writer
12662        synchronized (mPackages) {
12663            // If the platform SDK has changed since the last time we booted,
12664            // we need to re-grant app permission to catch any new ones that
12665            // appear. This is really a hack, and means that apps can in some
12666            // cases get permissions that the user didn't initially explicitly
12667            // allow... it would be nice to have some better way to handle
12668            // this situation.
12669            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12670            if (regrantPermissions)
12671                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12672                        + mSdkVersion + "; regranting permissions for external storage");
12673            mSettings.mExternalSdkPlatform = mSdkVersion;
12674
12675            // Make sure group IDs have been assigned, and any permission
12676            // changes in other apps are accounted for
12677            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12678                    | (regrantPermissions
12679                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12680                            : 0));
12681
12682            mSettings.updateExternalDatabaseVersion();
12683
12684            // can downgrade to reader
12685            // Persist settings
12686            mSettings.writeLPr();
12687        }
12688        // Send a broadcast to let everyone know we are done processing
12689        if (pkgList.size() > 0) {
12690            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12691        }
12692    }
12693
12694   /*
12695     * Utility method to unload a list of specified containers
12696     */
12697    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12698        // Just unmount all valid containers.
12699        for (AsecInstallArgs arg : cidArgs) {
12700            synchronized (mInstallLock) {
12701                arg.doPostDeleteLI(false);
12702           }
12703       }
12704   }
12705
12706    /*
12707     * Unload packages mounted on external media. This involves deleting package
12708     * data from internal structures, sending broadcasts about diabled packages,
12709     * gc'ing to free up references, unmounting all secure containers
12710     * corresponding to packages on external media, and posting a
12711     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12712     * that we always have to post this message if status has been requested no
12713     * matter what.
12714     */
12715    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12716            final boolean reportStatus) {
12717        if (DEBUG_SD_INSTALL)
12718            Log.i(TAG, "unloading media packages");
12719        ArrayList<String> pkgList = new ArrayList<String>();
12720        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12721        final Set<AsecInstallArgs> keys = processCids.keySet();
12722        for (AsecInstallArgs args : keys) {
12723            String pkgName = args.getPackageName();
12724            if (DEBUG_SD_INSTALL)
12725                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12726            // Delete package internally
12727            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12728            synchronized (mInstallLock) {
12729                boolean res = deletePackageLI(pkgName, null, false, null, null,
12730                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12731                if (res) {
12732                    pkgList.add(pkgName);
12733                } else {
12734                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12735                    failedList.add(args);
12736                }
12737            }
12738        }
12739
12740        // reader
12741        synchronized (mPackages) {
12742            // We didn't update the settings after removing each package;
12743            // write them now for all packages.
12744            mSettings.writeLPr();
12745        }
12746
12747        // We have to absolutely send UPDATED_MEDIA_STATUS only
12748        // after confirming that all the receivers processed the ordered
12749        // broadcast when packages get disabled, force a gc to clean things up.
12750        // and unload all the containers.
12751        if (pkgList.size() > 0) {
12752            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12753                    new IIntentReceiver.Stub() {
12754                public void performReceive(Intent intent, int resultCode, String data,
12755                        Bundle extras, boolean ordered, boolean sticky,
12756                        int sendingUser) throws RemoteException {
12757                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12758                            reportStatus ? 1 : 0, 1, keys);
12759                    mHandler.sendMessage(msg);
12760                }
12761            });
12762        } else {
12763            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12764                    keys);
12765            mHandler.sendMessage(msg);
12766        }
12767    }
12768
12769    /** Binder call */
12770    @Override
12771    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12772            final int flags) {
12773        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12774        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12775        int returnCode = PackageManager.MOVE_SUCCEEDED;
12776        int currInstallFlags = 0;
12777        int newInstallFlags = 0;
12778
12779        File codeFile = null;
12780        String installerPackageName = null;
12781        String packageAbiOverride = null;
12782
12783        // reader
12784        synchronized (mPackages) {
12785            final PackageParser.Package pkg = mPackages.get(packageName);
12786            final PackageSetting ps = mSettings.mPackages.get(packageName);
12787            if (pkg == null || ps == null) {
12788                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12789            } else {
12790                // Disable moving fwd locked apps and system packages
12791                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12792                    Slog.w(TAG, "Cannot move system application");
12793                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12794                } else if (pkg.mOperationPending) {
12795                    Slog.w(TAG, "Attempt to move package which has pending operations");
12796                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12797                } else {
12798                    // Find install location first
12799                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12800                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12801                        Slog.w(TAG, "Ambigous flags specified for move location.");
12802                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12803                    } else {
12804                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12805                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12806                        currInstallFlags = isExternal(pkg)
12807                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12808
12809                        if (newInstallFlags == currInstallFlags) {
12810                            Slog.w(TAG, "No move required. Trying to move to same location");
12811                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12812                        } else {
12813                            if (isForwardLocked(pkg)) {
12814                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12815                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12816                            }
12817                        }
12818                    }
12819                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12820                        pkg.mOperationPending = true;
12821                    }
12822                }
12823
12824                codeFile = new File(pkg.codePath);
12825                installerPackageName = ps.installerPackageName;
12826                packageAbiOverride = ps.cpuAbiOverrideString;
12827            }
12828        }
12829
12830        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12831            try {
12832                observer.packageMoved(packageName, returnCode);
12833            } catch (RemoteException ignored) {
12834            }
12835            return;
12836        }
12837
12838        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12839            @Override
12840            public void onUserActionRequired(Intent intent) throws RemoteException {
12841                throw new IllegalStateException();
12842            }
12843
12844            @Override
12845            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12846                    Bundle extras) throws RemoteException {
12847                Slog.d(TAG, "Install result for move: "
12848                        + PackageManager.installStatusToString(returnCode, msg));
12849
12850                // We usually have a new package now after the install, but if
12851                // we failed we need to clear the pending flag on the original
12852                // package object.
12853                synchronized (mPackages) {
12854                    final PackageParser.Package pkg = mPackages.get(packageName);
12855                    if (pkg != null) {
12856                        pkg.mOperationPending = false;
12857                    }
12858                }
12859
12860                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12861                switch (status) {
12862                    case PackageInstaller.STATUS_SUCCESS:
12863                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12864                        break;
12865                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12866                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12867                        break;
12868                    default:
12869                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12870                        break;
12871                }
12872            }
12873        };
12874
12875        // Treat a move like reinstalling an existing app, which ensures that we
12876        // process everythign uniformly, like unpacking native libraries.
12877        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12878
12879        final Message msg = mHandler.obtainMessage(INIT_COPY);
12880        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12881        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12882                installerPackageName, null, user, packageAbiOverride);
12883        mHandler.sendMessage(msg);
12884    }
12885
12886    @Override
12887    public boolean setInstallLocation(int loc) {
12888        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12889                null);
12890        if (getInstallLocation() == loc) {
12891            return true;
12892        }
12893        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12894                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12895            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12896                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12897            return true;
12898        }
12899        return false;
12900   }
12901
12902    @Override
12903    public int getInstallLocation() {
12904        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12905                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12906                PackageHelper.APP_INSTALL_AUTO);
12907    }
12908
12909    /** Called by UserManagerService */
12910    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12911        mDirtyUsers.remove(userHandle);
12912        mSettings.removeUserLPw(userHandle);
12913        mPendingBroadcasts.remove(userHandle);
12914        if (mInstaller != null) {
12915            // Technically, we shouldn't be doing this with the package lock
12916            // held.  However, this is very rare, and there is already so much
12917            // other disk I/O going on, that we'll let it slide for now.
12918            mInstaller.removeUserDataDirs(userHandle);
12919        }
12920        mUserNeedsBadging.delete(userHandle);
12921        removeUnusedPackagesLILPw(userManager, userHandle);
12922    }
12923
12924    /**
12925     * We're removing userHandle and would like to remove any downloaded packages
12926     * that are no longer in use by any other user.
12927     * @param userHandle the user being removed
12928     */
12929    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12930        final boolean DEBUG_CLEAN_APKS = false;
12931        int [] users = userManager.getUserIdsLPr();
12932        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12933        while (psit.hasNext()) {
12934            PackageSetting ps = psit.next();
12935            if (ps.pkg == null) {
12936                continue;
12937            }
12938            final String packageName = ps.pkg.packageName;
12939            // Skip over if system app
12940            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12941                continue;
12942            }
12943            if (DEBUG_CLEAN_APKS) {
12944                Slog.i(TAG, "Checking package " + packageName);
12945            }
12946            boolean keep = false;
12947            for (int i = 0; i < users.length; i++) {
12948                if (users[i] != userHandle && ps.getInstalled(users[i])) {
12949                    keep = true;
12950                    if (DEBUG_CLEAN_APKS) {
12951                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
12952                                + users[i]);
12953                    }
12954                    break;
12955                }
12956            }
12957            if (!keep) {
12958                if (DEBUG_CLEAN_APKS) {
12959                    Slog.i(TAG, "  Removing package " + packageName);
12960                }
12961                mHandler.post(new Runnable() {
12962                    public void run() {
12963                        deletePackageX(packageName, userHandle, 0);
12964                    } //end run
12965                });
12966            }
12967        }
12968    }
12969
12970    /** Called by UserManagerService */
12971    void createNewUserLILPw(int userHandle, File path) {
12972        if (mInstaller != null) {
12973            mInstaller.createUserConfig(userHandle);
12974            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12975        }
12976    }
12977
12978    @Override
12979    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12980        mContext.enforceCallingOrSelfPermission(
12981                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12982                "Only package verification agents can read the verifier device identity");
12983
12984        synchronized (mPackages) {
12985            return mSettings.getVerifierDeviceIdentityLPw();
12986        }
12987    }
12988
12989    @Override
12990    public void setPermissionEnforced(String permission, boolean enforced) {
12991        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12992        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12993            synchronized (mPackages) {
12994                if (mSettings.mReadExternalStorageEnforced == null
12995                        || mSettings.mReadExternalStorageEnforced != enforced) {
12996                    mSettings.mReadExternalStorageEnforced = enforced;
12997                    mSettings.writeLPr();
12998                }
12999            }
13000            // kill any non-foreground processes so we restart them and
13001            // grant/revoke the GID.
13002            final IActivityManager am = ActivityManagerNative.getDefault();
13003            if (am != null) {
13004                final long token = Binder.clearCallingIdentity();
13005                try {
13006                    am.killProcessesBelowForeground("setPermissionEnforcement");
13007                } catch (RemoteException e) {
13008                } finally {
13009                    Binder.restoreCallingIdentity(token);
13010                }
13011            }
13012        } else {
13013            throw new IllegalArgumentException("No selective enforcement for " + permission);
13014        }
13015    }
13016
13017    @Override
13018    @Deprecated
13019    public boolean isPermissionEnforced(String permission) {
13020        return true;
13021    }
13022
13023    @Override
13024    public boolean isStorageLow() {
13025        final long token = Binder.clearCallingIdentity();
13026        try {
13027            final DeviceStorageMonitorInternal
13028                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13029            if (dsm != null) {
13030                return dsm.isMemoryLow();
13031            } else {
13032                return false;
13033            }
13034        } finally {
13035            Binder.restoreCallingIdentity(token);
13036        }
13037    }
13038
13039    @Override
13040    public IPackageInstaller getPackageInstaller() {
13041        return mInstallerService;
13042    }
13043
13044    private boolean userNeedsBadging(int userId) {
13045        int index = mUserNeedsBadging.indexOfKey(userId);
13046        if (index < 0) {
13047            final UserInfo userInfo;
13048            final long token = Binder.clearCallingIdentity();
13049            try {
13050                userInfo = sUserManager.getUserInfo(userId);
13051            } finally {
13052                Binder.restoreCallingIdentity(token);
13053            }
13054            final boolean b;
13055            if (userInfo != null && userInfo.isManagedProfile()) {
13056                b = true;
13057            } else {
13058                b = false;
13059            }
13060            mUserNeedsBadging.put(userId, b);
13061            return b;
13062        }
13063        return mUserNeedsBadging.valueAt(index);
13064    }
13065
13066    @Override
13067    public KeySet getKeySetByAlias(String packageName, String alias) {
13068        if (packageName == null || alias == null) {
13069            return null;
13070        }
13071        synchronized(mPackages) {
13072            final PackageParser.Package pkg = mPackages.get(packageName);
13073            if (pkg == null) {
13074                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13075                throw new IllegalArgumentException("Unknown package: " + packageName);
13076            }
13077            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13078            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13079        }
13080    }
13081
13082    @Override
13083    public KeySet getSigningKeySet(String packageName) {
13084        if (packageName == null) {
13085            return null;
13086        }
13087        synchronized(mPackages) {
13088            final PackageParser.Package pkg = mPackages.get(packageName);
13089            if (pkg == null) {
13090                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13091                throw new IllegalArgumentException("Unknown package: " + packageName);
13092            }
13093            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13094                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13095                throw new SecurityException("May not access signing KeySet of other apps.");
13096            }
13097            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13098            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13099        }
13100    }
13101
13102    @Override
13103    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13104        if (packageName == null || ks == null) {
13105            return false;
13106        }
13107        synchronized(mPackages) {
13108            final PackageParser.Package pkg = mPackages.get(packageName);
13109            if (pkg == null) {
13110                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13111                throw new IllegalArgumentException("Unknown package: " + packageName);
13112            }
13113            IBinder ksh = ks.getToken();
13114            if (ksh instanceof KeySetHandle) {
13115                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13116                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13117            }
13118            return false;
13119        }
13120    }
13121
13122    @Override
13123    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13124        if (packageName == null || ks == null) {
13125            return false;
13126        }
13127        synchronized(mPackages) {
13128            final PackageParser.Package pkg = mPackages.get(packageName);
13129            if (pkg == null) {
13130                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13131                throw new IllegalArgumentException("Unknown package: " + packageName);
13132            }
13133            IBinder ksh = ks.getToken();
13134            if (ksh instanceof KeySetHandle) {
13135                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13136                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13137            }
13138            return false;
13139        }
13140    }
13141}
13142