PackageManagerService.java revision f1317857cdf815b95822db16621a566fb12baf20
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 mResolveActivity;
2165            }
2166        }
2167        return null;
2168    }
2169
2170    @Override
2171    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2172            String resolvedType) {
2173        synchronized (mPackages) {
2174            PackageParser.Activity a = mActivities.mActivities.get(component);
2175            if (a == null) {
2176                return false;
2177            }
2178            for (int i=0; i<a.intents.size(); i++) {
2179                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2180                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2181                    return true;
2182                }
2183            }
2184            return false;
2185        }
2186    }
2187
2188    @Override
2189    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2190        if (!sUserManager.exists(userId)) return null;
2191        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2192        synchronized (mPackages) {
2193            PackageParser.Activity a = mReceivers.mActivities.get(component);
2194            if (DEBUG_PACKAGE_INFO) Log.v(
2195                TAG, "getReceiverInfo " + component + ": " + a);
2196            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2197                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2198                if (ps == null) return null;
2199                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2200                        userId);
2201            }
2202        }
2203        return null;
2204    }
2205
2206    @Override
2207    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2208        if (!sUserManager.exists(userId)) return null;
2209        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2210        synchronized (mPackages) {
2211            PackageParser.Service s = mServices.mServices.get(component);
2212            if (DEBUG_PACKAGE_INFO) Log.v(
2213                TAG, "getServiceInfo " + component + ": " + s);
2214            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2215                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2216                if (ps == null) return null;
2217                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2218                        userId);
2219            }
2220        }
2221        return null;
2222    }
2223
2224    @Override
2225    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2226        if (!sUserManager.exists(userId)) return null;
2227        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2228        synchronized (mPackages) {
2229            PackageParser.Provider p = mProviders.mProviders.get(component);
2230            if (DEBUG_PACKAGE_INFO) Log.v(
2231                TAG, "getProviderInfo " + component + ": " + p);
2232            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2233                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2234                if (ps == null) return null;
2235                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2236                        userId);
2237            }
2238        }
2239        return null;
2240    }
2241
2242    @Override
2243    public String[] getSystemSharedLibraryNames() {
2244        Set<String> libSet;
2245        synchronized (mPackages) {
2246            libSet = mSharedLibraries.keySet();
2247            int size = libSet.size();
2248            if (size > 0) {
2249                String[] libs = new String[size];
2250                libSet.toArray(libs);
2251                return libs;
2252            }
2253        }
2254        return null;
2255    }
2256
2257    @Override
2258    public FeatureInfo[] getSystemAvailableFeatures() {
2259        Collection<FeatureInfo> featSet;
2260        synchronized (mPackages) {
2261            featSet = mAvailableFeatures.values();
2262            int size = featSet.size();
2263            if (size > 0) {
2264                FeatureInfo[] features = new FeatureInfo[size+1];
2265                featSet.toArray(features);
2266                FeatureInfo fi = new FeatureInfo();
2267                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2268                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2269                features[size] = fi;
2270                return features;
2271            }
2272        }
2273        return null;
2274    }
2275
2276    @Override
2277    public boolean hasSystemFeature(String name) {
2278        synchronized (mPackages) {
2279            return mAvailableFeatures.containsKey(name);
2280        }
2281    }
2282
2283    private void checkValidCaller(int uid, int userId) {
2284        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2285            return;
2286
2287        throw new SecurityException("Caller uid=" + uid
2288                + " is not privileged to communicate with user=" + userId);
2289    }
2290
2291    @Override
2292    public int checkPermission(String permName, String pkgName) {
2293        synchronized (mPackages) {
2294            PackageParser.Package p = mPackages.get(pkgName);
2295            if (p != null && p.mExtras != null) {
2296                PackageSetting ps = (PackageSetting)p.mExtras;
2297                if (ps.sharedUser != null) {
2298                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2299                        return PackageManager.PERMISSION_GRANTED;
2300                    }
2301                } else if (ps.grantedPermissions.contains(permName)) {
2302                    return PackageManager.PERMISSION_GRANTED;
2303                }
2304            }
2305        }
2306        return PackageManager.PERMISSION_DENIED;
2307    }
2308
2309    @Override
2310    public int checkUidPermission(String permName, int uid) {
2311        synchronized (mPackages) {
2312            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2313            if (obj != null) {
2314                GrantedPermissions gp = (GrantedPermissions)obj;
2315                if (gp.grantedPermissions.contains(permName)) {
2316                    return PackageManager.PERMISSION_GRANTED;
2317                }
2318            } else {
2319                HashSet<String> perms = mSystemPermissions.get(uid);
2320                if (perms != null && perms.contains(permName)) {
2321                    return PackageManager.PERMISSION_GRANTED;
2322                }
2323            }
2324        }
2325        return PackageManager.PERMISSION_DENIED;
2326    }
2327
2328    /**
2329     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2330     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2331     * @param checkShell TODO(yamasani):
2332     * @param message the message to log on security exception
2333     */
2334    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2335            boolean checkShell, String message) {
2336        if (userId < 0) {
2337            throw new IllegalArgumentException("Invalid userId " + userId);
2338        }
2339        if (checkShell) {
2340            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2341        }
2342        if (userId == UserHandle.getUserId(callingUid)) return;
2343        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2344            if (requireFullPermission) {
2345                mContext.enforceCallingOrSelfPermission(
2346                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2347            } else {
2348                try {
2349                    mContext.enforceCallingOrSelfPermission(
2350                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2351                } catch (SecurityException se) {
2352                    mContext.enforceCallingOrSelfPermission(
2353                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2354                }
2355            }
2356        }
2357    }
2358
2359    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2360        if (callingUid == Process.SHELL_UID) {
2361            if (userHandle >= 0
2362                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2363                throw new SecurityException("Shell does not have permission to access user "
2364                        + userHandle);
2365            } else if (userHandle < 0) {
2366                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2367                        + Debug.getCallers(3));
2368            }
2369        }
2370    }
2371
2372    private BasePermission findPermissionTreeLP(String permName) {
2373        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2374            if (permName.startsWith(bp.name) &&
2375                    permName.length() > bp.name.length() &&
2376                    permName.charAt(bp.name.length()) == '.') {
2377                return bp;
2378            }
2379        }
2380        return null;
2381    }
2382
2383    private BasePermission checkPermissionTreeLP(String permName) {
2384        if (permName != null) {
2385            BasePermission bp = findPermissionTreeLP(permName);
2386            if (bp != null) {
2387                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2388                    return bp;
2389                }
2390                throw new SecurityException("Calling uid "
2391                        + Binder.getCallingUid()
2392                        + " is not allowed to add to permission tree "
2393                        + bp.name + " owned by uid " + bp.uid);
2394            }
2395        }
2396        throw new SecurityException("No permission tree found for " + permName);
2397    }
2398
2399    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2400        if (s1 == null) {
2401            return s2 == null;
2402        }
2403        if (s2 == null) {
2404            return false;
2405        }
2406        if (s1.getClass() != s2.getClass()) {
2407            return false;
2408        }
2409        return s1.equals(s2);
2410    }
2411
2412    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2413        if (pi1.icon != pi2.icon) return false;
2414        if (pi1.logo != pi2.logo) return false;
2415        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2416        if (!compareStrings(pi1.name, pi2.name)) return false;
2417        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2418        // We'll take care of setting this one.
2419        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2420        // These are not currently stored in settings.
2421        //if (!compareStrings(pi1.group, pi2.group)) return false;
2422        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2423        //if (pi1.labelRes != pi2.labelRes) return false;
2424        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2425        return true;
2426    }
2427
2428    int permissionInfoFootprint(PermissionInfo info) {
2429        int size = info.name.length();
2430        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2431        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2432        return size;
2433    }
2434
2435    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2436        int size = 0;
2437        for (BasePermission perm : mSettings.mPermissions.values()) {
2438            if (perm.uid == tree.uid) {
2439                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2440            }
2441        }
2442        return size;
2443    }
2444
2445    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2446        // We calculate the max size of permissions defined by this uid and throw
2447        // if that plus the size of 'info' would exceed our stated maximum.
2448        if (tree.uid != Process.SYSTEM_UID) {
2449            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2450            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2451                throw new SecurityException("Permission tree size cap exceeded");
2452            }
2453        }
2454    }
2455
2456    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2457        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2458            throw new SecurityException("Label must be specified in permission");
2459        }
2460        BasePermission tree = checkPermissionTreeLP(info.name);
2461        BasePermission bp = mSettings.mPermissions.get(info.name);
2462        boolean added = bp == null;
2463        boolean changed = true;
2464        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2465        if (added) {
2466            enforcePermissionCapLocked(info, tree);
2467            bp = new BasePermission(info.name, tree.sourcePackage,
2468                    BasePermission.TYPE_DYNAMIC);
2469        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2470            throw new SecurityException(
2471                    "Not allowed to modify non-dynamic permission "
2472                    + info.name);
2473        } else {
2474            if (bp.protectionLevel == fixedLevel
2475                    && bp.perm.owner.equals(tree.perm.owner)
2476                    && bp.uid == tree.uid
2477                    && comparePermissionInfos(bp.perm.info, info)) {
2478                changed = false;
2479            }
2480        }
2481        bp.protectionLevel = fixedLevel;
2482        info = new PermissionInfo(info);
2483        info.protectionLevel = fixedLevel;
2484        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2485        bp.perm.info.packageName = tree.perm.info.packageName;
2486        bp.uid = tree.uid;
2487        if (added) {
2488            mSettings.mPermissions.put(info.name, bp);
2489        }
2490        if (changed) {
2491            if (!async) {
2492                mSettings.writeLPr();
2493            } else {
2494                scheduleWriteSettingsLocked();
2495            }
2496        }
2497        return added;
2498    }
2499
2500    @Override
2501    public boolean addPermission(PermissionInfo info) {
2502        synchronized (mPackages) {
2503            return addPermissionLocked(info, false);
2504        }
2505    }
2506
2507    @Override
2508    public boolean addPermissionAsync(PermissionInfo info) {
2509        synchronized (mPackages) {
2510            return addPermissionLocked(info, true);
2511        }
2512    }
2513
2514    @Override
2515    public void removePermission(String name) {
2516        synchronized (mPackages) {
2517            checkPermissionTreeLP(name);
2518            BasePermission bp = mSettings.mPermissions.get(name);
2519            if (bp != null) {
2520                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2521                    throw new SecurityException(
2522                            "Not allowed to modify non-dynamic permission "
2523                            + name);
2524                }
2525                mSettings.mPermissions.remove(name);
2526                mSettings.writeLPr();
2527            }
2528        }
2529    }
2530
2531    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2532        int index = pkg.requestedPermissions.indexOf(bp.name);
2533        if (index == -1) {
2534            throw new SecurityException("Package " + pkg.packageName
2535                    + " has not requested permission " + bp.name);
2536        }
2537        boolean isNormal =
2538                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2539                        == PermissionInfo.PROTECTION_NORMAL);
2540        boolean isDangerous =
2541                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2542                        == PermissionInfo.PROTECTION_DANGEROUS);
2543        boolean isDevelopment =
2544                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2545
2546        if (!isNormal && !isDangerous && !isDevelopment) {
2547            throw new SecurityException("Permission " + bp.name
2548                    + " is not a changeable permission type");
2549        }
2550
2551        if (isNormal || isDangerous) {
2552            if (pkg.requestedPermissionsRequired.get(index)) {
2553                throw new SecurityException("Can't change " + bp.name
2554                        + ". It is required by the application");
2555            }
2556        }
2557    }
2558
2559    @Override
2560    public void grantPermission(String packageName, String permissionName) {
2561        mContext.enforceCallingOrSelfPermission(
2562                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2563        synchronized (mPackages) {
2564            final PackageParser.Package pkg = mPackages.get(packageName);
2565            if (pkg == null) {
2566                throw new IllegalArgumentException("Unknown package: " + packageName);
2567            }
2568            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2569            if (bp == null) {
2570                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2571            }
2572
2573            checkGrantRevokePermissions(pkg, bp);
2574
2575            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2576            if (ps == null) {
2577                return;
2578            }
2579            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2580            if (gp.grantedPermissions.add(permissionName)) {
2581                if (ps.haveGids) {
2582                    gp.gids = appendInts(gp.gids, bp.gids);
2583                }
2584                mSettings.writeLPr();
2585            }
2586        }
2587    }
2588
2589    @Override
2590    public void revokePermission(String packageName, String permissionName) {
2591        int changedAppId = -1;
2592
2593        synchronized (mPackages) {
2594            final PackageParser.Package pkg = mPackages.get(packageName);
2595            if (pkg == null) {
2596                throw new IllegalArgumentException("Unknown package: " + packageName);
2597            }
2598            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2599                mContext.enforceCallingOrSelfPermission(
2600                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2601            }
2602            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2603            if (bp == null) {
2604                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2605            }
2606
2607            checkGrantRevokePermissions(pkg, bp);
2608
2609            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2610            if (ps == null) {
2611                return;
2612            }
2613            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2614            if (gp.grantedPermissions.remove(permissionName)) {
2615                gp.grantedPermissions.remove(permissionName);
2616                if (ps.haveGids) {
2617                    gp.gids = removeInts(gp.gids, bp.gids);
2618                }
2619                mSettings.writeLPr();
2620                changedAppId = ps.appId;
2621            }
2622        }
2623
2624        if (changedAppId >= 0) {
2625            // We changed the perm on someone, kill its processes.
2626            IActivityManager am = ActivityManagerNative.getDefault();
2627            if (am != null) {
2628                final int callingUserId = UserHandle.getCallingUserId();
2629                final long ident = Binder.clearCallingIdentity();
2630                try {
2631                    //XXX we should only revoke for the calling user's app permissions,
2632                    // but for now we impact all users.
2633                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2634                    //        "revoke " + permissionName);
2635                    int[] users = sUserManager.getUserIds();
2636                    for (int user : users) {
2637                        am.killUid(UserHandle.getUid(user, changedAppId),
2638                                "revoke " + permissionName);
2639                    }
2640                } catch (RemoteException e) {
2641                } finally {
2642                    Binder.restoreCallingIdentity(ident);
2643                }
2644            }
2645        }
2646    }
2647
2648    @Override
2649    public boolean isProtectedBroadcast(String actionName) {
2650        synchronized (mPackages) {
2651            return mProtectedBroadcasts.contains(actionName);
2652        }
2653    }
2654
2655    @Override
2656    public int checkSignatures(String pkg1, String pkg2) {
2657        synchronized (mPackages) {
2658            final PackageParser.Package p1 = mPackages.get(pkg1);
2659            final PackageParser.Package p2 = mPackages.get(pkg2);
2660            if (p1 == null || p1.mExtras == null
2661                    || p2 == null || p2.mExtras == null) {
2662                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2663            }
2664            return compareSignatures(p1.mSignatures, p2.mSignatures);
2665        }
2666    }
2667
2668    @Override
2669    public int checkUidSignatures(int uid1, int uid2) {
2670        // Map to base uids.
2671        uid1 = UserHandle.getAppId(uid1);
2672        uid2 = UserHandle.getAppId(uid2);
2673        // reader
2674        synchronized (mPackages) {
2675            Signature[] s1;
2676            Signature[] s2;
2677            Object obj = mSettings.getUserIdLPr(uid1);
2678            if (obj != null) {
2679                if (obj instanceof SharedUserSetting) {
2680                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2681                } else if (obj instanceof PackageSetting) {
2682                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2683                } else {
2684                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2685                }
2686            } else {
2687                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2688            }
2689            obj = mSettings.getUserIdLPr(uid2);
2690            if (obj != null) {
2691                if (obj instanceof SharedUserSetting) {
2692                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2693                } else if (obj instanceof PackageSetting) {
2694                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2695                } else {
2696                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2697                }
2698            } else {
2699                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2700            }
2701            return compareSignatures(s1, s2);
2702        }
2703    }
2704
2705    /**
2706     * Compares two sets of signatures. Returns:
2707     * <br />
2708     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2709     * <br />
2710     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2715     * <br />
2716     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2717     */
2718    static int compareSignatures(Signature[] s1, Signature[] s2) {
2719        if (s1 == null) {
2720            return s2 == null
2721                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2722                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2723        }
2724
2725        if (s2 == null) {
2726            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2727        }
2728
2729        if (s1.length != s2.length) {
2730            return PackageManager.SIGNATURE_NO_MATCH;
2731        }
2732
2733        // Since both signature sets are of size 1, we can compare without HashSets.
2734        if (s1.length == 1) {
2735            return s1[0].equals(s2[0]) ?
2736                    PackageManager.SIGNATURE_MATCH :
2737                    PackageManager.SIGNATURE_NO_MATCH;
2738        }
2739
2740        HashSet<Signature> set1 = new HashSet<Signature>();
2741        for (Signature sig : s1) {
2742            set1.add(sig);
2743        }
2744        HashSet<Signature> set2 = new HashSet<Signature>();
2745        for (Signature sig : s2) {
2746            set2.add(sig);
2747        }
2748        // Make sure s2 contains all signatures in s1.
2749        if (set1.equals(set2)) {
2750            return PackageManager.SIGNATURE_MATCH;
2751        }
2752        return PackageManager.SIGNATURE_NO_MATCH;
2753    }
2754
2755    /**
2756     * If the database version for this type of package (internal storage or
2757     * external storage) is less than the version where package signatures
2758     * were updated, return true.
2759     */
2760    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2761        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2762                DatabaseVersion.SIGNATURE_END_ENTITY))
2763                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2764                        DatabaseVersion.SIGNATURE_END_ENTITY));
2765    }
2766
2767    /**
2768     * Used for backward compatibility to make sure any packages with
2769     * certificate chains get upgraded to the new style. {@code existingSigs}
2770     * will be in the old format (since they were stored on disk from before the
2771     * system upgrade) and {@code scannedSigs} will be in the newer format.
2772     */
2773    private int compareSignaturesCompat(PackageSignatures existingSigs,
2774            PackageParser.Package scannedPkg) {
2775        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2776            return PackageManager.SIGNATURE_NO_MATCH;
2777        }
2778
2779        HashSet<Signature> existingSet = new HashSet<Signature>();
2780        for (Signature sig : existingSigs.mSignatures) {
2781            existingSet.add(sig);
2782        }
2783        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2784        for (Signature sig : scannedPkg.mSignatures) {
2785            try {
2786                Signature[] chainSignatures = sig.getChainSignatures();
2787                for (Signature chainSig : chainSignatures) {
2788                    scannedCompatSet.add(chainSig);
2789                }
2790            } catch (CertificateEncodingException e) {
2791                scannedCompatSet.add(sig);
2792            }
2793        }
2794        /*
2795         * Make sure the expanded scanned set contains all signatures in the
2796         * existing one.
2797         */
2798        if (scannedCompatSet.equals(existingSet)) {
2799            // Migrate the old signatures to the new scheme.
2800            existingSigs.assignSignatures(scannedPkg.mSignatures);
2801            // The new KeySets will be re-added later in the scanning process.
2802            synchronized (mPackages) {
2803                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2804            }
2805            return PackageManager.SIGNATURE_MATCH;
2806        }
2807        return PackageManager.SIGNATURE_NO_MATCH;
2808    }
2809
2810    @Override
2811    public String[] getPackagesForUid(int uid) {
2812        uid = UserHandle.getAppId(uid);
2813        // reader
2814        synchronized (mPackages) {
2815            Object obj = mSettings.getUserIdLPr(uid);
2816            if (obj instanceof SharedUserSetting) {
2817                final SharedUserSetting sus = (SharedUserSetting) obj;
2818                final int N = sus.packages.size();
2819                final String[] res = new String[N];
2820                final Iterator<PackageSetting> it = sus.packages.iterator();
2821                int i = 0;
2822                while (it.hasNext()) {
2823                    res[i++] = it.next().name;
2824                }
2825                return res;
2826            } else if (obj instanceof PackageSetting) {
2827                final PackageSetting ps = (PackageSetting) obj;
2828                return new String[] { ps.name };
2829            }
2830        }
2831        return null;
2832    }
2833
2834    @Override
2835    public String getNameForUid(int uid) {
2836        // reader
2837        synchronized (mPackages) {
2838            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2839            if (obj instanceof SharedUserSetting) {
2840                final SharedUserSetting sus = (SharedUserSetting) obj;
2841                return sus.name + ":" + sus.userId;
2842            } else if (obj instanceof PackageSetting) {
2843                final PackageSetting ps = (PackageSetting) obj;
2844                return ps.name;
2845            }
2846        }
2847        return null;
2848    }
2849
2850    @Override
2851    public int getUidForSharedUser(String sharedUserName) {
2852        if(sharedUserName == null) {
2853            return -1;
2854        }
2855        // reader
2856        synchronized (mPackages) {
2857            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2858            if (suid == null) {
2859                return -1;
2860            }
2861            return suid.userId;
2862        }
2863    }
2864
2865    @Override
2866    public int getFlagsForUid(int uid) {
2867        synchronized (mPackages) {
2868            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2869            if (obj instanceof SharedUserSetting) {
2870                final SharedUserSetting sus = (SharedUserSetting) obj;
2871                return sus.pkgFlags;
2872            } else if (obj instanceof PackageSetting) {
2873                final PackageSetting ps = (PackageSetting) obj;
2874                return ps.pkgFlags;
2875            }
2876        }
2877        return 0;
2878    }
2879
2880    @Override
2881    public String[] getAppOpPermissionPackages(String permissionName) {
2882        synchronized (mPackages) {
2883            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2884            if (pkgs == null) {
2885                return null;
2886            }
2887            return pkgs.toArray(new String[pkgs.size()]);
2888        }
2889    }
2890
2891    @Override
2892    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2893            int flags, int userId) {
2894        if (!sUserManager.exists(userId)) return null;
2895        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2896        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2897        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2898    }
2899
2900    @Override
2901    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2902            IntentFilter filter, int match, ComponentName activity) {
2903        final int userId = UserHandle.getCallingUserId();
2904        if (DEBUG_PREFERRED) {
2905            Log.v(TAG, "setLastChosenActivity intent=" + intent
2906                + " resolvedType=" + resolvedType
2907                + " flags=" + flags
2908                + " filter=" + filter
2909                + " match=" + match
2910                + " activity=" + activity);
2911            filter.dump(new PrintStreamPrinter(System.out), "    ");
2912        }
2913        intent.setComponent(null);
2914        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2915        // Find any earlier preferred or last chosen entries and nuke them
2916        findPreferredActivity(intent, resolvedType,
2917                flags, query, 0, false, true, false, userId);
2918        // Add the new activity as the last chosen for this filter
2919        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2920                "Setting last chosen");
2921    }
2922
2923    @Override
2924    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2925        final int userId = UserHandle.getCallingUserId();
2926        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2927        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2928        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2929                false, false, false, userId);
2930    }
2931
2932    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2933            int flags, List<ResolveInfo> query, int userId) {
2934        if (query != null) {
2935            final int N = query.size();
2936            if (N == 1) {
2937                return query.get(0);
2938            } else if (N > 1) {
2939                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2940                // If there is more than one activity with the same priority,
2941                // then let the user decide between them.
2942                ResolveInfo r0 = query.get(0);
2943                ResolveInfo r1 = query.get(1);
2944                if (DEBUG_INTENT_MATCHING || debug) {
2945                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2946                            + r1.activityInfo.name + "=" + r1.priority);
2947                }
2948                // If the first activity has a higher priority, or a different
2949                // default, then it is always desireable to pick it.
2950                if (r0.priority != r1.priority
2951                        || r0.preferredOrder != r1.preferredOrder
2952                        || r0.isDefault != r1.isDefault) {
2953                    return query.get(0);
2954                }
2955                // If we have saved a preference for a preferred activity for
2956                // this Intent, use that.
2957                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2958                        flags, query, r0.priority, true, false, debug, userId);
2959                if (ri != null) {
2960                    return ri;
2961                }
2962                if (userId != 0) {
2963                    ri = new ResolveInfo(mResolveInfo);
2964                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2965                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2966                            ri.activityInfo.applicationInfo);
2967                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2968                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2969                    return ri;
2970                }
2971                return mResolveInfo;
2972            }
2973        }
2974        return null;
2975    }
2976
2977    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2978            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2979        final int N = query.size();
2980        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2981                .get(userId);
2982        // Get the list of persistent preferred activities that handle the intent
2983        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2984        List<PersistentPreferredActivity> pprefs = ppir != null
2985                ? ppir.queryIntent(intent, resolvedType,
2986                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2987                : null;
2988        if (pprefs != null && pprefs.size() > 0) {
2989            final int M = pprefs.size();
2990            for (int i=0; i<M; i++) {
2991                final PersistentPreferredActivity ppa = pprefs.get(i);
2992                if (DEBUG_PREFERRED || debug) {
2993                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2994                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2995                            + "\n  component=" + ppa.mComponent);
2996                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2997                }
2998                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2999                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3000                if (DEBUG_PREFERRED || debug) {
3001                    Slog.v(TAG, "Found persistent preferred activity:");
3002                    if (ai != null) {
3003                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3004                    } else {
3005                        Slog.v(TAG, "  null");
3006                    }
3007                }
3008                if (ai == null) {
3009                    // This previously registered persistent preferred activity
3010                    // component is no longer known. Ignore it and do NOT remove it.
3011                    continue;
3012                }
3013                for (int j=0; j<N; j++) {
3014                    final ResolveInfo ri = query.get(j);
3015                    if (!ri.activityInfo.applicationInfo.packageName
3016                            .equals(ai.applicationInfo.packageName)) {
3017                        continue;
3018                    }
3019                    if (!ri.activityInfo.name.equals(ai.name)) {
3020                        continue;
3021                    }
3022                    //  Found a persistent preference that can handle the intent.
3023                    if (DEBUG_PREFERRED || debug) {
3024                        Slog.v(TAG, "Returning persistent preferred activity: " +
3025                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3026                    }
3027                    return ri;
3028                }
3029            }
3030        }
3031        return null;
3032    }
3033
3034    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3035            List<ResolveInfo> query, int priority, boolean always,
3036            boolean removeMatches, boolean debug, int userId) {
3037        if (!sUserManager.exists(userId)) return null;
3038        // writer
3039        synchronized (mPackages) {
3040            if (intent.getSelector() != null) {
3041                intent = intent.getSelector();
3042            }
3043            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3044
3045            // Try to find a matching persistent preferred activity.
3046            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3047                    debug, userId);
3048
3049            // If a persistent preferred activity matched, use it.
3050            if (pri != null) {
3051                return pri;
3052            }
3053
3054            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3055            // Get the list of preferred activities that handle the intent
3056            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3057            List<PreferredActivity> prefs = pir != null
3058                    ? pir.queryIntent(intent, resolvedType,
3059                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3060                    : null;
3061            if (prefs != null && prefs.size() > 0) {
3062                boolean changed = false;
3063                try {
3064                    // First figure out how good the original match set is.
3065                    // We will only allow preferred activities that came
3066                    // from the same match quality.
3067                    int match = 0;
3068
3069                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3070
3071                    final int N = query.size();
3072                    for (int j=0; j<N; j++) {
3073                        final ResolveInfo ri = query.get(j);
3074                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3075                                + ": 0x" + Integer.toHexString(match));
3076                        if (ri.match > match) {
3077                            match = ri.match;
3078                        }
3079                    }
3080
3081                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3082                            + Integer.toHexString(match));
3083
3084                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3085                    final int M = prefs.size();
3086                    for (int i=0; i<M; i++) {
3087                        final PreferredActivity pa = prefs.get(i);
3088                        if (DEBUG_PREFERRED || debug) {
3089                            Slog.v(TAG, "Checking PreferredActivity ds="
3090                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3091                                    + "\n  component=" + pa.mPref.mComponent);
3092                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3093                        }
3094                        if (pa.mPref.mMatch != match) {
3095                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3096                                    + Integer.toHexString(pa.mPref.mMatch));
3097                            continue;
3098                        }
3099                        // If it's not an "always" type preferred activity and that's what we're
3100                        // looking for, skip it.
3101                        if (always && !pa.mPref.mAlways) {
3102                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3103                            continue;
3104                        }
3105                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3106                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3107                        if (DEBUG_PREFERRED || debug) {
3108                            Slog.v(TAG, "Found preferred activity:");
3109                            if (ai != null) {
3110                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3111                            } else {
3112                                Slog.v(TAG, "  null");
3113                            }
3114                        }
3115                        if (ai == null) {
3116                            // This previously registered preferred activity
3117                            // component is no longer known.  Most likely an update
3118                            // to the app was installed and in the new version this
3119                            // component no longer exists.  Clean it up by removing
3120                            // it from the preferred activities list, and skip it.
3121                            Slog.w(TAG, "Removing dangling preferred activity: "
3122                                    + pa.mPref.mComponent);
3123                            pir.removeFilter(pa);
3124                            changed = true;
3125                            continue;
3126                        }
3127                        for (int j=0; j<N; j++) {
3128                            final ResolveInfo ri = query.get(j);
3129                            if (!ri.activityInfo.applicationInfo.packageName
3130                                    .equals(ai.applicationInfo.packageName)) {
3131                                continue;
3132                            }
3133                            if (!ri.activityInfo.name.equals(ai.name)) {
3134                                continue;
3135                            }
3136
3137                            if (removeMatches) {
3138                                pir.removeFilter(pa);
3139                                changed = true;
3140                                if (DEBUG_PREFERRED) {
3141                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3142                                }
3143                                break;
3144                            }
3145
3146                            // Okay we found a previously set preferred or last chosen app.
3147                            // If the result set is different from when this
3148                            // was created, we need to clear it and re-ask the
3149                            // user their preference, if we're looking for an "always" type entry.
3150                            if (always && !pa.mPref.sameSet(query, priority)) {
3151                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3152                                        + intent + " type " + resolvedType);
3153                                if (DEBUG_PREFERRED) {
3154                                    Slog.v(TAG, "Removing preferred activity since set changed "
3155                                            + pa.mPref.mComponent);
3156                                }
3157                                pir.removeFilter(pa);
3158                                // Re-add the filter as a "last chosen" entry (!always)
3159                                PreferredActivity lastChosen = new PreferredActivity(
3160                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3161                                pir.addFilter(lastChosen);
3162                                changed = true;
3163                                return null;
3164                            }
3165
3166                            // Yay! Either the set matched or we're looking for the last chosen
3167                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3168                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3169                            return ri;
3170                        }
3171                    }
3172                } finally {
3173                    if (changed) {
3174                        if (DEBUG_PREFERRED) {
3175                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3176                        }
3177                        mSettings.writePackageRestrictionsLPr(userId);
3178                    }
3179                }
3180            }
3181        }
3182        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3183        return null;
3184    }
3185
3186    /*
3187     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3188     */
3189    @Override
3190    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3191            int targetUserId) {
3192        mContext.enforceCallingOrSelfPermission(
3193                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3194        List<CrossProfileIntentFilter> matches =
3195                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3196        if (matches != null) {
3197            int size = matches.size();
3198            for (int i = 0; i < size; i++) {
3199                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3200            }
3201        }
3202        return false;
3203    }
3204
3205    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3206            String resolvedType, int userId) {
3207        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3208        if (resolver != null) {
3209            return resolver.queryIntent(intent, resolvedType, false, userId);
3210        }
3211        return null;
3212    }
3213
3214    @Override
3215    public List<ResolveInfo> queryIntentActivities(Intent intent,
3216            String resolvedType, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return Collections.emptyList();
3218        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3219        ComponentName comp = intent.getComponent();
3220        if (comp == null) {
3221            if (intent.getSelector() != null) {
3222                intent = intent.getSelector();
3223                comp = intent.getComponent();
3224            }
3225        }
3226
3227        if (comp != null) {
3228            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3229            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3230            if (ai != null) {
3231                final ResolveInfo ri = new ResolveInfo();
3232                ri.activityInfo = ai;
3233                list.add(ri);
3234            }
3235            return list;
3236        }
3237
3238        // reader
3239        synchronized (mPackages) {
3240            final String pkgName = intent.getPackage();
3241            if (pkgName == null) {
3242                List<CrossProfileIntentFilter> matchingFilters =
3243                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3244                // Check for results that need to skip the current profile.
3245                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3246                        resolvedType, flags, userId);
3247                if (resolveInfo != null) {
3248                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3249                    result.add(resolveInfo);
3250                    return result;
3251                }
3252                // Check for cross profile results.
3253                resolveInfo = queryCrossProfileIntents(
3254                        matchingFilters, intent, resolvedType, flags, userId);
3255
3256                // Check for results in the current profile.
3257                List<ResolveInfo> result = mActivities.queryIntent(
3258                        intent, resolvedType, flags, userId);
3259                if (resolveInfo != null) {
3260                    result.add(resolveInfo);
3261                    Collections.sort(result, mResolvePrioritySorter);
3262                }
3263                return result;
3264            }
3265            final PackageParser.Package pkg = mPackages.get(pkgName);
3266            if (pkg != null) {
3267                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3268                        pkg.activities, userId);
3269            }
3270            return new ArrayList<ResolveInfo>();
3271        }
3272    }
3273
3274    private ResolveInfo querySkipCurrentProfileIntents(
3275            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3276            int flags, int sourceUserId) {
3277        if (matchingFilters != null) {
3278            int size = matchingFilters.size();
3279            for (int i = 0; i < size; i ++) {
3280                CrossProfileIntentFilter filter = matchingFilters.get(i);
3281                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3282                    // Checking if there are activities in the target user that can handle the
3283                    // intent.
3284                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3285                            flags, sourceUserId);
3286                    if (resolveInfo != null) {
3287                        return resolveInfo;
3288                    }
3289                }
3290            }
3291        }
3292        return null;
3293    }
3294
3295    // Return matching ResolveInfo if any for skip current profile intent filters.
3296    private ResolveInfo queryCrossProfileIntents(
3297            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3298            int flags, int sourceUserId) {
3299        if (matchingFilters != null) {
3300            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3301            // match the same intent. For performance reasons, it is better not to
3302            // run queryIntent twice for the same userId
3303            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3304            int size = matchingFilters.size();
3305            for (int i = 0; i < size; i++) {
3306                CrossProfileIntentFilter filter = matchingFilters.get(i);
3307                int targetUserId = filter.getTargetUserId();
3308                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3309                        && !alreadyTriedUserIds.get(targetUserId)) {
3310                    // Checking if there are activities in the target user that can handle the
3311                    // intent.
3312                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3313                            flags, sourceUserId);
3314                    if (resolveInfo != null) return resolveInfo;
3315                    alreadyTriedUserIds.put(targetUserId, true);
3316                }
3317            }
3318        }
3319        return null;
3320    }
3321
3322    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3323            String resolvedType, int flags, int sourceUserId) {
3324        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3325                resolvedType, flags, filter.getTargetUserId());
3326        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3327            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3328        }
3329        return null;
3330    }
3331
3332    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3333            int sourceUserId, int targetUserId) {
3334        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3335        String className;
3336        if (targetUserId == UserHandle.USER_OWNER) {
3337            className = FORWARD_INTENT_TO_USER_OWNER;
3338        } else {
3339            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3340        }
3341        ComponentName forwardingActivityComponentName = new ComponentName(
3342                mAndroidApplication.packageName, className);
3343        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3344                sourceUserId);
3345        if (targetUserId == UserHandle.USER_OWNER) {
3346            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3347            forwardingResolveInfo.noResourceId = true;
3348        }
3349        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3350        forwardingResolveInfo.priority = 0;
3351        forwardingResolveInfo.preferredOrder = 0;
3352        forwardingResolveInfo.match = 0;
3353        forwardingResolveInfo.isDefault = true;
3354        forwardingResolveInfo.filter = filter;
3355        forwardingResolveInfo.targetUserId = targetUserId;
3356        return forwardingResolveInfo;
3357    }
3358
3359    @Override
3360    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3361            Intent[] specifics, String[] specificTypes, Intent intent,
3362            String resolvedType, int flags, int userId) {
3363        if (!sUserManager.exists(userId)) return Collections.emptyList();
3364        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3365                false, "query intent activity options");
3366        final String resultsAction = intent.getAction();
3367
3368        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3369                | PackageManager.GET_RESOLVED_FILTER, userId);
3370
3371        if (DEBUG_INTENT_MATCHING) {
3372            Log.v(TAG, "Query " + intent + ": " + results);
3373        }
3374
3375        int specificsPos = 0;
3376        int N;
3377
3378        // todo: note that the algorithm used here is O(N^2).  This
3379        // isn't a problem in our current environment, but if we start running
3380        // into situations where we have more than 5 or 10 matches then this
3381        // should probably be changed to something smarter...
3382
3383        // First we go through and resolve each of the specific items
3384        // that were supplied, taking care of removing any corresponding
3385        // duplicate items in the generic resolve list.
3386        if (specifics != null) {
3387            for (int i=0; i<specifics.length; i++) {
3388                final Intent sintent = specifics[i];
3389                if (sintent == null) {
3390                    continue;
3391                }
3392
3393                if (DEBUG_INTENT_MATCHING) {
3394                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3395                }
3396
3397                String action = sintent.getAction();
3398                if (resultsAction != null && resultsAction.equals(action)) {
3399                    // If this action was explicitly requested, then don't
3400                    // remove things that have it.
3401                    action = null;
3402                }
3403
3404                ResolveInfo ri = null;
3405                ActivityInfo ai = null;
3406
3407                ComponentName comp = sintent.getComponent();
3408                if (comp == null) {
3409                    ri = resolveIntent(
3410                        sintent,
3411                        specificTypes != null ? specificTypes[i] : null,
3412                            flags, userId);
3413                    if (ri == null) {
3414                        continue;
3415                    }
3416                    if (ri == mResolveInfo) {
3417                        // ACK!  Must do something better with this.
3418                    }
3419                    ai = ri.activityInfo;
3420                    comp = new ComponentName(ai.applicationInfo.packageName,
3421                            ai.name);
3422                } else {
3423                    ai = getActivityInfo(comp, flags, userId);
3424                    if (ai == null) {
3425                        continue;
3426                    }
3427                }
3428
3429                // Look for any generic query activities that are duplicates
3430                // of this specific one, and remove them from the results.
3431                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3432                N = results.size();
3433                int j;
3434                for (j=specificsPos; j<N; j++) {
3435                    ResolveInfo sri = results.get(j);
3436                    if ((sri.activityInfo.name.equals(comp.getClassName())
3437                            && sri.activityInfo.applicationInfo.packageName.equals(
3438                                    comp.getPackageName()))
3439                        || (action != null && sri.filter.matchAction(action))) {
3440                        results.remove(j);
3441                        if (DEBUG_INTENT_MATCHING) Log.v(
3442                            TAG, "Removing duplicate item from " + j
3443                            + " due to specific " + specificsPos);
3444                        if (ri == null) {
3445                            ri = sri;
3446                        }
3447                        j--;
3448                        N--;
3449                    }
3450                }
3451
3452                // Add this specific item to its proper place.
3453                if (ri == null) {
3454                    ri = new ResolveInfo();
3455                    ri.activityInfo = ai;
3456                }
3457                results.add(specificsPos, ri);
3458                ri.specificIndex = i;
3459                specificsPos++;
3460            }
3461        }
3462
3463        // Now we go through the remaining generic results and remove any
3464        // duplicate actions that are found here.
3465        N = results.size();
3466        for (int i=specificsPos; i<N-1; i++) {
3467            final ResolveInfo rii = results.get(i);
3468            if (rii.filter == null) {
3469                continue;
3470            }
3471
3472            // Iterate over all of the actions of this result's intent
3473            // filter...  typically this should be just one.
3474            final Iterator<String> it = rii.filter.actionsIterator();
3475            if (it == null) {
3476                continue;
3477            }
3478            while (it.hasNext()) {
3479                final String action = it.next();
3480                if (resultsAction != null && resultsAction.equals(action)) {
3481                    // If this action was explicitly requested, then don't
3482                    // remove things that have it.
3483                    continue;
3484                }
3485                for (int j=i+1; j<N; j++) {
3486                    final ResolveInfo rij = results.get(j);
3487                    if (rij.filter != null && rij.filter.hasAction(action)) {
3488                        results.remove(j);
3489                        if (DEBUG_INTENT_MATCHING) Log.v(
3490                            TAG, "Removing duplicate item from " + j
3491                            + " due to action " + action + " at " + i);
3492                        j--;
3493                        N--;
3494                    }
3495                }
3496            }
3497
3498            // If the caller didn't request filter information, drop it now
3499            // so we don't have to marshall/unmarshall it.
3500            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3501                rii.filter = null;
3502            }
3503        }
3504
3505        // Filter out the caller activity if so requested.
3506        if (caller != null) {
3507            N = results.size();
3508            for (int i=0; i<N; i++) {
3509                ActivityInfo ainfo = results.get(i).activityInfo;
3510                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3511                        && caller.getClassName().equals(ainfo.name)) {
3512                    results.remove(i);
3513                    break;
3514                }
3515            }
3516        }
3517
3518        // If the caller didn't request filter information,
3519        // drop them now so we don't have to
3520        // marshall/unmarshall it.
3521        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3522            N = results.size();
3523            for (int i=0; i<N; i++) {
3524                results.get(i).filter = null;
3525            }
3526        }
3527
3528        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3529        return results;
3530    }
3531
3532    @Override
3533    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3534            int userId) {
3535        if (!sUserManager.exists(userId)) return Collections.emptyList();
3536        ComponentName comp = intent.getComponent();
3537        if (comp == null) {
3538            if (intent.getSelector() != null) {
3539                intent = intent.getSelector();
3540                comp = intent.getComponent();
3541            }
3542        }
3543        if (comp != null) {
3544            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3545            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3546            if (ai != null) {
3547                ResolveInfo ri = new ResolveInfo();
3548                ri.activityInfo = ai;
3549                list.add(ri);
3550            }
3551            return list;
3552        }
3553
3554        // reader
3555        synchronized (mPackages) {
3556            String pkgName = intent.getPackage();
3557            if (pkgName == null) {
3558                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3559            }
3560            final PackageParser.Package pkg = mPackages.get(pkgName);
3561            if (pkg != null) {
3562                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3563                        userId);
3564            }
3565            return null;
3566        }
3567    }
3568
3569    @Override
3570    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3571        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3572        if (!sUserManager.exists(userId)) return null;
3573        if (query != null) {
3574            if (query.size() >= 1) {
3575                // If there is more than one service with the same priority,
3576                // just arbitrarily pick the first one.
3577                return query.get(0);
3578            }
3579        }
3580        return null;
3581    }
3582
3583    @Override
3584    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3585            int userId) {
3586        if (!sUserManager.exists(userId)) return Collections.emptyList();
3587        ComponentName comp = intent.getComponent();
3588        if (comp == null) {
3589            if (intent.getSelector() != null) {
3590                intent = intent.getSelector();
3591                comp = intent.getComponent();
3592            }
3593        }
3594        if (comp != null) {
3595            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3596            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3597            if (si != null) {
3598                final ResolveInfo ri = new ResolveInfo();
3599                ri.serviceInfo = si;
3600                list.add(ri);
3601            }
3602            return list;
3603        }
3604
3605        // reader
3606        synchronized (mPackages) {
3607            String pkgName = intent.getPackage();
3608            if (pkgName == null) {
3609                return mServices.queryIntent(intent, resolvedType, flags, userId);
3610            }
3611            final PackageParser.Package pkg = mPackages.get(pkgName);
3612            if (pkg != null) {
3613                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3614                        userId);
3615            }
3616            return null;
3617        }
3618    }
3619
3620    @Override
3621    public List<ResolveInfo> queryIntentContentProviders(
3622            Intent intent, String resolvedType, int flags, int userId) {
3623        if (!sUserManager.exists(userId)) return Collections.emptyList();
3624        ComponentName comp = intent.getComponent();
3625        if (comp == null) {
3626            if (intent.getSelector() != null) {
3627                intent = intent.getSelector();
3628                comp = intent.getComponent();
3629            }
3630        }
3631        if (comp != null) {
3632            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3633            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3634            if (pi != null) {
3635                final ResolveInfo ri = new ResolveInfo();
3636                ri.providerInfo = pi;
3637                list.add(ri);
3638            }
3639            return list;
3640        }
3641
3642        // reader
3643        synchronized (mPackages) {
3644            String pkgName = intent.getPackage();
3645            if (pkgName == null) {
3646                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3647            }
3648            final PackageParser.Package pkg = mPackages.get(pkgName);
3649            if (pkg != null) {
3650                return mProviders.queryIntentForPackage(
3651                        intent, resolvedType, flags, pkg.providers, userId);
3652            }
3653            return null;
3654        }
3655    }
3656
3657    @Override
3658    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3659        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3660
3661        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3662
3663        // writer
3664        synchronized (mPackages) {
3665            ArrayList<PackageInfo> list;
3666            if (listUninstalled) {
3667                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3668                for (PackageSetting ps : mSettings.mPackages.values()) {
3669                    PackageInfo pi;
3670                    if (ps.pkg != null) {
3671                        pi = generatePackageInfo(ps.pkg, flags, userId);
3672                    } else {
3673                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3674                    }
3675                    if (pi != null) {
3676                        list.add(pi);
3677                    }
3678                }
3679            } else {
3680                list = new ArrayList<PackageInfo>(mPackages.size());
3681                for (PackageParser.Package p : mPackages.values()) {
3682                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3683                    if (pi != null) {
3684                        list.add(pi);
3685                    }
3686                }
3687            }
3688
3689            return new ParceledListSlice<PackageInfo>(list);
3690        }
3691    }
3692
3693    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3694            String[] permissions, boolean[] tmp, int flags, int userId) {
3695        int numMatch = 0;
3696        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3697        for (int i=0; i<permissions.length; i++) {
3698            if (gp.grantedPermissions.contains(permissions[i])) {
3699                tmp[i] = true;
3700                numMatch++;
3701            } else {
3702                tmp[i] = false;
3703            }
3704        }
3705        if (numMatch == 0) {
3706            return;
3707        }
3708        PackageInfo pi;
3709        if (ps.pkg != null) {
3710            pi = generatePackageInfo(ps.pkg, flags, userId);
3711        } else {
3712            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3713        }
3714        // The above might return null in cases of uninstalled apps or install-state
3715        // skew across users/profiles.
3716        if (pi != null) {
3717            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3718                if (numMatch == permissions.length) {
3719                    pi.requestedPermissions = permissions;
3720                } else {
3721                    pi.requestedPermissions = new String[numMatch];
3722                    numMatch = 0;
3723                    for (int i=0; i<permissions.length; i++) {
3724                        if (tmp[i]) {
3725                            pi.requestedPermissions[numMatch] = permissions[i];
3726                            numMatch++;
3727                        }
3728                    }
3729                }
3730            }
3731            list.add(pi);
3732        }
3733    }
3734
3735    @Override
3736    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3737            String[] permissions, int flags, int userId) {
3738        if (!sUserManager.exists(userId)) return null;
3739        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3740
3741        // writer
3742        synchronized (mPackages) {
3743            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3744            boolean[] tmpBools = new boolean[permissions.length];
3745            if (listUninstalled) {
3746                for (PackageSetting ps : mSettings.mPackages.values()) {
3747                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3748                }
3749            } else {
3750                for (PackageParser.Package pkg : mPackages.values()) {
3751                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3752                    if (ps != null) {
3753                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3754                                userId);
3755                    }
3756                }
3757            }
3758
3759            return new ParceledListSlice<PackageInfo>(list);
3760        }
3761    }
3762
3763    @Override
3764    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3765        if (!sUserManager.exists(userId)) return null;
3766        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3767
3768        // writer
3769        synchronized (mPackages) {
3770            ArrayList<ApplicationInfo> list;
3771            if (listUninstalled) {
3772                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3773                for (PackageSetting ps : mSettings.mPackages.values()) {
3774                    ApplicationInfo ai;
3775                    if (ps.pkg != null) {
3776                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3777                                ps.readUserState(userId), userId);
3778                    } else {
3779                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3780                    }
3781                    if (ai != null) {
3782                        list.add(ai);
3783                    }
3784                }
3785            } else {
3786                list = new ArrayList<ApplicationInfo>(mPackages.size());
3787                for (PackageParser.Package p : mPackages.values()) {
3788                    if (p.mExtras != null) {
3789                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3790                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3791                        if (ai != null) {
3792                            list.add(ai);
3793                        }
3794                    }
3795                }
3796            }
3797
3798            return new ParceledListSlice<ApplicationInfo>(list);
3799        }
3800    }
3801
3802    public List<ApplicationInfo> getPersistentApplications(int flags) {
3803        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3804
3805        // reader
3806        synchronized (mPackages) {
3807            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3808            final int userId = UserHandle.getCallingUserId();
3809            while (i.hasNext()) {
3810                final PackageParser.Package p = i.next();
3811                if (p.applicationInfo != null
3812                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3813                        && (!mSafeMode || isSystemApp(p))) {
3814                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3815                    if (ps != null) {
3816                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3817                                ps.readUserState(userId), userId);
3818                        if (ai != null) {
3819                            finalList.add(ai);
3820                        }
3821                    }
3822                }
3823            }
3824        }
3825
3826        return finalList;
3827    }
3828
3829    @Override
3830    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3831        if (!sUserManager.exists(userId)) return null;
3832        // reader
3833        synchronized (mPackages) {
3834            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3835            PackageSetting ps = provider != null
3836                    ? mSettings.mPackages.get(provider.owner.packageName)
3837                    : null;
3838            return ps != null
3839                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3840                    && (!mSafeMode || (provider.info.applicationInfo.flags
3841                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3842                    ? PackageParser.generateProviderInfo(provider, flags,
3843                            ps.readUserState(userId), userId)
3844                    : null;
3845        }
3846    }
3847
3848    /**
3849     * @deprecated
3850     */
3851    @Deprecated
3852    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3853        // reader
3854        synchronized (mPackages) {
3855            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3856                    .entrySet().iterator();
3857            final int userId = UserHandle.getCallingUserId();
3858            while (i.hasNext()) {
3859                Map.Entry<String, PackageParser.Provider> entry = i.next();
3860                PackageParser.Provider p = entry.getValue();
3861                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3862
3863                if (ps != null && p.syncable
3864                        && (!mSafeMode || (p.info.applicationInfo.flags
3865                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3866                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3867                            ps.readUserState(userId), userId);
3868                    if (info != null) {
3869                        outNames.add(entry.getKey());
3870                        outInfo.add(info);
3871                    }
3872                }
3873            }
3874        }
3875    }
3876
3877    @Override
3878    public List<ProviderInfo> queryContentProviders(String processName,
3879            int uid, int flags) {
3880        ArrayList<ProviderInfo> finalList = null;
3881        // reader
3882        synchronized (mPackages) {
3883            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3884            final int userId = processName != null ?
3885                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3886            while (i.hasNext()) {
3887                final PackageParser.Provider p = i.next();
3888                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3889                if (ps != null && p.info.authority != null
3890                        && (processName == null
3891                                || (p.info.processName.equals(processName)
3892                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3893                        && mSettings.isEnabledLPr(p.info, flags, userId)
3894                        && (!mSafeMode
3895                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3896                    if (finalList == null) {
3897                        finalList = new ArrayList<ProviderInfo>(3);
3898                    }
3899                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3900                            ps.readUserState(userId), userId);
3901                    if (info != null) {
3902                        finalList.add(info);
3903                    }
3904                }
3905            }
3906        }
3907
3908        if (finalList != null) {
3909            Collections.sort(finalList, mProviderInitOrderSorter);
3910        }
3911
3912        return finalList;
3913    }
3914
3915    @Override
3916    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3917            int flags) {
3918        // reader
3919        synchronized (mPackages) {
3920            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3921            return PackageParser.generateInstrumentationInfo(i, flags);
3922        }
3923    }
3924
3925    @Override
3926    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3927            int flags) {
3928        ArrayList<InstrumentationInfo> finalList =
3929            new ArrayList<InstrumentationInfo>();
3930
3931        // reader
3932        synchronized (mPackages) {
3933            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3934            while (i.hasNext()) {
3935                final PackageParser.Instrumentation p = i.next();
3936                if (targetPackage == null
3937                        || targetPackage.equals(p.info.targetPackage)) {
3938                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3939                            flags);
3940                    if (ii != null) {
3941                        finalList.add(ii);
3942                    }
3943                }
3944            }
3945        }
3946
3947        return finalList;
3948    }
3949
3950    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3951        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3952        if (overlays == null) {
3953            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3954            return;
3955        }
3956        for (PackageParser.Package opkg : overlays.values()) {
3957            // Not much to do if idmap fails: we already logged the error
3958            // and we certainly don't want to abort installation of pkg simply
3959            // because an overlay didn't fit properly. For these reasons,
3960            // ignore the return value of createIdmapForPackagePairLI.
3961            createIdmapForPackagePairLI(pkg, opkg);
3962        }
3963    }
3964
3965    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3966            PackageParser.Package opkg) {
3967        if (!opkg.mTrustedOverlay) {
3968            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
3969                    opkg.baseCodePath + ": overlay not trusted");
3970            return false;
3971        }
3972        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3973        if (overlaySet == null) {
3974            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
3975                    opkg.baseCodePath + " but target package has no known overlays");
3976            return false;
3977        }
3978        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3979        // TODO: generate idmap for split APKs
3980        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
3981            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
3982                    + opkg.baseCodePath);
3983            return false;
3984        }
3985        PackageParser.Package[] overlayArray =
3986            overlaySet.values().toArray(new PackageParser.Package[0]);
3987        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3988            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3989                return p1.mOverlayPriority - p2.mOverlayPriority;
3990            }
3991        };
3992        Arrays.sort(overlayArray, cmp);
3993
3994        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3995        int i = 0;
3996        for (PackageParser.Package p : overlayArray) {
3997            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
3998        }
3999        return true;
4000    }
4001
4002    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4003        final File[] files = dir.listFiles();
4004        if (ArrayUtils.isEmpty(files)) {
4005            Log.d(TAG, "No files in app dir " + dir);
4006            return;
4007        }
4008
4009        if (DEBUG_PACKAGE_SCANNING) {
4010            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4011                    + " flags=0x" + Integer.toHexString(parseFlags));
4012        }
4013
4014        for (File file : files) {
4015            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4016                    && !PackageInstallerService.isStageName(file.getName());
4017            if (!isPackage) {
4018                // Ignore entries which are not packages
4019                continue;
4020            }
4021            try {
4022                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4023                        scanFlags, currentTime, null);
4024            } catch (PackageManagerException e) {
4025                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4026
4027                // Delete invalid userdata apps
4028                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4029                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4030                    Slog.w(TAG, "Deleting invalid package at " + file);
4031                    if (file.isDirectory()) {
4032                        FileUtils.deleteContents(file);
4033                    }
4034                    file.delete();
4035                }
4036            }
4037        }
4038    }
4039
4040    private static File getSettingsProblemFile() {
4041        File dataDir = Environment.getDataDirectory();
4042        File systemDir = new File(dataDir, "system");
4043        File fname = new File(systemDir, "uiderrors.txt");
4044        return fname;
4045    }
4046
4047    static void reportSettingsProblem(int priority, String msg) {
4048        try {
4049            File fname = getSettingsProblemFile();
4050            FileOutputStream out = new FileOutputStream(fname, true);
4051            PrintWriter pw = new FastPrintWriter(out);
4052            SimpleDateFormat formatter = new SimpleDateFormat();
4053            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4054            pw.println(dateString + ": " + msg);
4055            pw.close();
4056            FileUtils.setPermissions(
4057                    fname.toString(),
4058                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4059                    -1, -1);
4060        } catch (java.io.IOException e) {
4061        }
4062        Slog.println(priority, TAG, msg);
4063    }
4064
4065    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4066            PackageParser.Package pkg, File srcFile, int parseFlags)
4067            throws PackageManagerException {
4068        if (ps != null
4069                && ps.codePath.equals(srcFile)
4070                && ps.timeStamp == srcFile.lastModified()
4071                && !isCompatSignatureUpdateNeeded(pkg)) {
4072            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4073            if (ps.signatures.mSignatures != null
4074                    && ps.signatures.mSignatures.length != 0
4075                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4076                // Optimization: reuse the existing cached certificates
4077                // if the package appears to be unchanged.
4078                pkg.mSignatures = ps.signatures.mSignatures;
4079                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4080                synchronized (mPackages) {
4081                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4082                }
4083                return;
4084            }
4085
4086            Slog.w(TAG, "PackageSetting for " + ps.name
4087                    + " is missing signatures.  Collecting certs again to recover them.");
4088        } else {
4089            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4090        }
4091
4092        try {
4093            pp.collectCertificates(pkg, parseFlags);
4094            pp.collectManifestDigest(pkg);
4095        } catch (PackageParserException e) {
4096            throw PackageManagerException.from(e);
4097        }
4098    }
4099
4100    /*
4101     *  Scan a package and return the newly parsed package.
4102     *  Returns null in case of errors and the error code is stored in mLastScanError
4103     */
4104    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4105            long currentTime, UserHandle user) throws PackageManagerException {
4106        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4107        parseFlags |= mDefParseFlags;
4108        PackageParser pp = new PackageParser();
4109        pp.setSeparateProcesses(mSeparateProcesses);
4110        pp.setOnlyCoreApps(mOnlyCore);
4111        pp.setDisplayMetrics(mMetrics);
4112
4113        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4114            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4115        }
4116
4117        final PackageParser.Package pkg;
4118        try {
4119            pkg = pp.parsePackage(scanFile, parseFlags);
4120        } catch (PackageParserException e) {
4121            throw PackageManagerException.from(e);
4122        }
4123
4124        PackageSetting ps = null;
4125        PackageSetting updatedPkg;
4126        // reader
4127        synchronized (mPackages) {
4128            // Look to see if we already know about this package.
4129            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4130            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4131                // This package has been renamed to its original name.  Let's
4132                // use that.
4133                ps = mSettings.peekPackageLPr(oldName);
4134            }
4135            // If there was no original package, see one for the real package name.
4136            if (ps == null) {
4137                ps = mSettings.peekPackageLPr(pkg.packageName);
4138            }
4139            // Check to see if this package could be hiding/updating a system
4140            // package.  Must look for it either under the original or real
4141            // package name depending on our state.
4142            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4143            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4144        }
4145        boolean updatedPkgBetter = false;
4146        // First check if this is a system package that may involve an update
4147        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4148            if (ps != null && !ps.codePath.equals(scanFile)) {
4149                // The path has changed from what was last scanned...  check the
4150                // version of the new path against what we have stored to determine
4151                // what to do.
4152                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4153                if (pkg.mVersionCode < ps.versionCode) {
4154                    // The system package has been updated and the code path does not match
4155                    // Ignore entry. Skip it.
4156                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4157                            + " ignored: updated version " + ps.versionCode
4158                            + " better than this " + pkg.mVersionCode);
4159                    if (!updatedPkg.codePath.equals(scanFile)) {
4160                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4161                                + ps.name + " changing from " + updatedPkg.codePathString
4162                                + " to " + scanFile);
4163                        updatedPkg.codePath = scanFile;
4164                        updatedPkg.codePathString = scanFile.toString();
4165                        // This is the point at which we know that the system-disk APK
4166                        // for this package has moved during a reboot (e.g. due to an OTA),
4167                        // so we need to reevaluate it for privilege policy.
4168                        if (locationIsPrivileged(scanFile)) {
4169                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4170                        }
4171                    }
4172                    updatedPkg.pkg = pkg;
4173                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4174                } else {
4175                    // The current app on the system partition is better than
4176                    // what we have updated to on the data partition; switch
4177                    // back to the system partition version.
4178                    // At this point, its safely assumed that package installation for
4179                    // apps in system partition will go through. If not there won't be a working
4180                    // version of the app
4181                    // writer
4182                    synchronized (mPackages) {
4183                        // Just remove the loaded entries from package lists.
4184                        mPackages.remove(ps.name);
4185                    }
4186                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4187                            + "reverting from " + ps.codePathString
4188                            + ": new version " + pkg.mVersionCode
4189                            + " better than installed " + ps.versionCode);
4190
4191                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4192                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4193                            getAppDexInstructionSets(ps));
4194                    synchronized (mInstallLock) {
4195                        args.cleanUpResourcesLI();
4196                    }
4197                    synchronized (mPackages) {
4198                        mSettings.enableSystemPackageLPw(ps.name);
4199                    }
4200                    updatedPkgBetter = true;
4201                }
4202            }
4203        }
4204
4205        if (updatedPkg != null) {
4206            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4207            // initially
4208            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4209
4210            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4211            // flag set initially
4212            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4213                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4214            }
4215        }
4216
4217        // Verify certificates against what was last scanned
4218        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4219
4220        /*
4221         * A new system app appeared, but we already had a non-system one of the
4222         * same name installed earlier.
4223         */
4224        boolean shouldHideSystemApp = false;
4225        if (updatedPkg == null && ps != null
4226                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4227            /*
4228             * Check to make sure the signatures match first. If they don't,
4229             * wipe the installed application and its data.
4230             */
4231            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4232                    != PackageManager.SIGNATURE_MATCH) {
4233                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4234                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4235                ps = null;
4236            } else {
4237                /*
4238                 * If the newly-added system app is an older version than the
4239                 * already installed version, hide it. It will be scanned later
4240                 * and re-added like an update.
4241                 */
4242                if (pkg.mVersionCode < ps.versionCode) {
4243                    shouldHideSystemApp = true;
4244                } else {
4245                    /*
4246                     * The newly found system app is a newer version that the
4247                     * one previously installed. Simply remove the
4248                     * already-installed application and replace it with our own
4249                     * while keeping the application data.
4250                     */
4251                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4252                            + ps.codePathString + ": new version " + pkg.mVersionCode
4253                            + " better than installed " + ps.versionCode);
4254                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4255                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4256                            getAppDexInstructionSets(ps));
4257                    synchronized (mInstallLock) {
4258                        args.cleanUpResourcesLI();
4259                    }
4260                }
4261            }
4262        }
4263
4264        // The apk is forward locked (not public) if its code and resources
4265        // are kept in different files. (except for app in either system or
4266        // vendor path).
4267        // TODO grab this value from PackageSettings
4268        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4269            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4270                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4271            }
4272        }
4273
4274        // TODO: extend to support forward-locked splits
4275        String resourcePath = null;
4276        String baseResourcePath = null;
4277        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4278            if (ps != null && ps.resourcePathString != null) {
4279                resourcePath = ps.resourcePathString;
4280                baseResourcePath = ps.resourcePathString;
4281            } else {
4282                // Should not happen at all. Just log an error.
4283                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4284            }
4285        } else {
4286            resourcePath = pkg.codePath;
4287            baseResourcePath = pkg.baseCodePath;
4288        }
4289
4290        // Set application objects path explicitly.
4291        pkg.applicationInfo.setCodePath(pkg.codePath);
4292        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4293        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4294        pkg.applicationInfo.setResourcePath(resourcePath);
4295        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4296        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4297
4298        // Note that we invoke the following method only if we are about to unpack an application
4299        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4300                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4301
4302        /*
4303         * If the system app should be overridden by a previously installed
4304         * data, hide the system app now and let the /data/app scan pick it up
4305         * again.
4306         */
4307        if (shouldHideSystemApp) {
4308            synchronized (mPackages) {
4309                /*
4310                 * We have to grant systems permissions before we hide, because
4311                 * grantPermissions will assume the package update is trying to
4312                 * expand its permissions.
4313                 */
4314                grantPermissionsLPw(pkg, true);
4315                mSettings.disableSystemPackageLPw(pkg.packageName);
4316            }
4317        }
4318
4319        return scannedPkg;
4320    }
4321
4322    private static String fixProcessName(String defProcessName,
4323            String processName, int uid) {
4324        if (processName == null) {
4325            return defProcessName;
4326        }
4327        return processName;
4328    }
4329
4330    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4331            throws PackageManagerException {
4332        if (pkgSetting.signatures.mSignatures != null) {
4333            // Already existing package. Make sure signatures match
4334            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4335                    == PackageManager.SIGNATURE_MATCH;
4336            if (!match) {
4337                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4338                        == PackageManager.SIGNATURE_MATCH;
4339            }
4340            if (!match) {
4341                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4342                        + pkg.packageName + " signatures do not match the "
4343                        + "previously installed version; ignoring!");
4344            }
4345        }
4346
4347        // Check for shared user signatures
4348        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4349            // Already existing package. Make sure signatures match
4350            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4351                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4352            if (!match) {
4353                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4354                        == PackageManager.SIGNATURE_MATCH;
4355            }
4356            if (!match) {
4357                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4358                        "Package " + pkg.packageName
4359                        + " has no signatures that match those in shared user "
4360                        + pkgSetting.sharedUser.name + "; ignoring!");
4361            }
4362        }
4363    }
4364
4365    /**
4366     * Enforces that only the system UID or root's UID can call a method exposed
4367     * via Binder.
4368     *
4369     * @param message used as message if SecurityException is thrown
4370     * @throws SecurityException if the caller is not system or root
4371     */
4372    private static final void enforceSystemOrRoot(String message) {
4373        final int uid = Binder.getCallingUid();
4374        if (uid != Process.SYSTEM_UID && uid != 0) {
4375            throw new SecurityException(message);
4376        }
4377    }
4378
4379    @Override
4380    public void performBootDexOpt() {
4381        enforceSystemOrRoot("Only the system can request dexopt be performed");
4382
4383        final HashSet<PackageParser.Package> pkgs;
4384        synchronized (mPackages) {
4385            pkgs = mDeferredDexOpt;
4386            mDeferredDexOpt = null;
4387        }
4388
4389        if (pkgs != null) {
4390            // Filter out packages that aren't recently used.
4391            //
4392            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4393            // should do a full dexopt.
4394            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4395                // TODO: add a property to control this?
4396                long dexOptLRUThresholdInMinutes;
4397                if (mLazyDexOpt) {
4398                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4399                } else {
4400                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4401                }
4402                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4403
4404                int total = pkgs.size();
4405                int skipped = 0;
4406                long now = System.currentTimeMillis();
4407                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4408                    PackageParser.Package pkg = i.next();
4409                    long then = pkg.mLastPackageUsageTimeInMills;
4410                    if (then + dexOptLRUThresholdInMills < now) {
4411                        if (DEBUG_DEXOPT) {
4412                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4413                                  ((then == 0) ? "never" : new Date(then)));
4414                        }
4415                        i.remove();
4416                        skipped++;
4417                    }
4418                }
4419                if (DEBUG_DEXOPT) {
4420                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4421                }
4422            }
4423
4424            int i = 0;
4425            for (PackageParser.Package pkg : pkgs) {
4426                i++;
4427                if (DEBUG_DEXOPT) {
4428                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4429                          + ": " + pkg.packageName);
4430                }
4431                if (!isFirstBoot()) {
4432                    try {
4433                        ActivityManagerNative.getDefault().showBootMessage(
4434                                mContext.getResources().getString(
4435                                        R.string.android_upgrading_apk,
4436                                        i, pkgs.size()), true);
4437                    } catch (RemoteException e) {
4438                    }
4439                }
4440                PackageParser.Package p = pkg;
4441                synchronized (mInstallLock) {
4442                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4443                            true /* include dependencies */);
4444                }
4445            }
4446        }
4447    }
4448
4449    @Override
4450    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4451        return performDexOpt(packageName, instructionSet, false);
4452    }
4453
4454    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4455        if (info.primaryCpuAbi == null) {
4456            return getPreferredInstructionSet();
4457        }
4458
4459        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4460    }
4461
4462    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4463        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4464        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4465        if (!dexopt && !updateUsage) {
4466            // We aren't going to dexopt or update usage, so bail early.
4467            return false;
4468        }
4469        PackageParser.Package p;
4470        final String targetInstructionSet;
4471        synchronized (mPackages) {
4472            p = mPackages.get(packageName);
4473            if (p == null) {
4474                return false;
4475            }
4476            if (updateUsage) {
4477                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4478            }
4479            mPackageUsage.write(false);
4480            if (!dexopt) {
4481                // We aren't going to dexopt, so bail early.
4482                return false;
4483            }
4484
4485            targetInstructionSet = instructionSet != null ? instructionSet :
4486                    getPrimaryInstructionSet(p.applicationInfo);
4487            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4488                return false;
4489            }
4490        }
4491
4492        synchronized (mInstallLock) {
4493            final String[] instructionSets = new String[] { targetInstructionSet };
4494            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4495                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4496        }
4497    }
4498
4499    public HashSet<String> getPackagesThatNeedDexOpt() {
4500        HashSet<String> pkgs = null;
4501        synchronized (mPackages) {
4502            for (PackageParser.Package p : mPackages.values()) {
4503                if (DEBUG_DEXOPT) {
4504                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4505                }
4506                if (!p.mDexOptPerformed.isEmpty()) {
4507                    continue;
4508                }
4509                if (pkgs == null) {
4510                    pkgs = new HashSet<String>();
4511                }
4512                pkgs.add(p.packageName);
4513            }
4514        }
4515        return pkgs;
4516    }
4517
4518    public void shutdown() {
4519        mPackageUsage.write(true);
4520    }
4521
4522    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4523             boolean forceDex, boolean defer, HashSet<String> done) {
4524        for (int i=0; i<libs.size(); i++) {
4525            PackageParser.Package libPkg;
4526            String libName;
4527            synchronized (mPackages) {
4528                libName = libs.get(i);
4529                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4530                if (lib != null && lib.apk != null) {
4531                    libPkg = mPackages.get(lib.apk);
4532                } else {
4533                    libPkg = null;
4534                }
4535            }
4536            if (libPkg != null && !done.contains(libName)) {
4537                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4538            }
4539        }
4540    }
4541
4542    static final int DEX_OPT_SKIPPED = 0;
4543    static final int DEX_OPT_PERFORMED = 1;
4544    static final int DEX_OPT_DEFERRED = 2;
4545    static final int DEX_OPT_FAILED = -1;
4546
4547    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4548            boolean forceDex, boolean defer, HashSet<String> done) {
4549        final String[] instructionSets = targetInstructionSets != null ?
4550                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4551
4552        if (done != null) {
4553            done.add(pkg.packageName);
4554            if (pkg.usesLibraries != null) {
4555                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4556            }
4557            if (pkg.usesOptionalLibraries != null) {
4558                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4559            }
4560        }
4561
4562        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4563            return DEX_OPT_SKIPPED;
4564        }
4565
4566        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4567
4568        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4569        boolean performedDexOpt = false;
4570        // There are three basic cases here:
4571        // 1.) we need to dexopt, either because we are forced or it is needed
4572        // 2.) we are defering a needed dexopt
4573        // 3.) we are skipping an unneeded dexopt
4574        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4575        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4576            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4577                continue;
4578            }
4579
4580            for (String path : paths) {
4581                try {
4582                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4583                    // patckage or the one we find does not match the image checksum (i.e. it was
4584                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4585                    // odex file and it matches the checksum of the image but not its base address,
4586                    // meaning we need to move it.
4587                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4588                            pkg.packageName, dexCodeInstructionSet, defer);
4589                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4590                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4591                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4592                                + " vmSafeMode=" + vmSafeMode);
4593                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4594                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4595                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4596
4597                        if (ret < 0) {
4598                            // Don't bother running dexopt again if we failed, it will probably
4599                            // just result in an error again. Also, don't bother dexopting for other
4600                            // paths & ISAs.
4601                            return DEX_OPT_FAILED;
4602                        }
4603
4604                        performedDexOpt = true;
4605                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4606                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4607                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4608                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4609                                pkg.packageName, dexCodeInstructionSet);
4610
4611                        if (ret < 0) {
4612                            // Don't bother running patchoat again if we failed, it will probably
4613                            // just result in an error again. Also, don't bother dexopting for other
4614                            // paths & ISAs.
4615                            return DEX_OPT_FAILED;
4616                        }
4617
4618                        performedDexOpt = true;
4619                    }
4620
4621                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4622                    // paths and instruction sets. We'll deal with them all together when we process
4623                    // our list of deferred dexopts.
4624                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4625                        if (mDeferredDexOpt == null) {
4626                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4627                        }
4628                        mDeferredDexOpt.add(pkg);
4629                        return DEX_OPT_DEFERRED;
4630                    }
4631                } catch (FileNotFoundException e) {
4632                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4633                    return DEX_OPT_FAILED;
4634                } catch (IOException e) {
4635                    Slog.w(TAG, "IOException reading apk: " + path, e);
4636                    return DEX_OPT_FAILED;
4637                } catch (StaleDexCacheError e) {
4638                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4639                    return DEX_OPT_FAILED;
4640                } catch (Exception e) {
4641                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4642                    return DEX_OPT_FAILED;
4643                }
4644            }
4645
4646            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4647            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4648            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4649            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4650            // it.
4651            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4652        }
4653
4654        // If we've gotten here, we're sure that no error occurred and that we haven't
4655        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4656        // we've skipped all of them because they are up to date. In both cases this
4657        // package doesn't need dexopt any longer.
4658        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4659    }
4660
4661    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4662        if (info.primaryCpuAbi != null) {
4663            if (info.secondaryCpuAbi != null) {
4664                return new String[] {
4665                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4666                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4667            } else {
4668                return new String[] {
4669                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4670            }
4671        }
4672
4673        return new String[] { getPreferredInstructionSet() };
4674    }
4675
4676    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4677        if (ps.primaryCpuAbiString != null) {
4678            if (ps.secondaryCpuAbiString != null) {
4679                return new String[] {
4680                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4681                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4682            } else {
4683                return new String[] {
4684                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4685            }
4686        }
4687
4688        return new String[] { getPreferredInstructionSet() };
4689    }
4690
4691    private static String getPreferredInstructionSet() {
4692        if (sPreferredInstructionSet == null) {
4693            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4694        }
4695
4696        return sPreferredInstructionSet;
4697    }
4698
4699    private static List<String> getAllInstructionSets() {
4700        final String[] allAbis = Build.SUPPORTED_ABIS;
4701        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4702
4703        for (String abi : allAbis) {
4704            final String instructionSet = VMRuntime.getInstructionSet(abi);
4705            if (!allInstructionSets.contains(instructionSet)) {
4706                allInstructionSets.add(instructionSet);
4707            }
4708        }
4709
4710        return allInstructionSets;
4711    }
4712
4713    /**
4714     * Returns the instruction set that should be used to compile dex code. In the presence of
4715     * a native bridge this might be different than the one shared libraries use.
4716     */
4717    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4718        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4719        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4720    }
4721
4722    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4723        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4724        for (String instructionSet : instructionSets) {
4725            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4726        }
4727        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4728    }
4729
4730    @Override
4731    public void forceDexOpt(String packageName) {
4732        enforceSystemOrRoot("forceDexOpt");
4733
4734        PackageParser.Package pkg;
4735        synchronized (mPackages) {
4736            pkg = mPackages.get(packageName);
4737            if (pkg == null) {
4738                throw new IllegalArgumentException("Missing package: " + packageName);
4739            }
4740        }
4741
4742        synchronized (mInstallLock) {
4743            final String[] instructionSets = new String[] {
4744                    getPrimaryInstructionSet(pkg.applicationInfo) };
4745            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4746            if (res != DEX_OPT_PERFORMED) {
4747                throw new IllegalStateException("Failed to dexopt: " + res);
4748            }
4749        }
4750    }
4751
4752    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4753                                boolean forceDex, boolean defer, boolean inclDependencies) {
4754        HashSet<String> done;
4755        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4756            done = new HashSet<String>();
4757            done.add(pkg.packageName);
4758        } else {
4759            done = null;
4760        }
4761        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4762    }
4763
4764    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4765        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4766            Slog.w(TAG, "Unable to update from " + oldPkg.name
4767                    + " to " + newPkg.packageName
4768                    + ": old package not in system partition");
4769            return false;
4770        } else if (mPackages.get(oldPkg.name) != null) {
4771            Slog.w(TAG, "Unable to update from " + oldPkg.name
4772                    + " to " + newPkg.packageName
4773                    + ": old package still exists");
4774            return false;
4775        }
4776        return true;
4777    }
4778
4779    File getDataPathForUser(int userId) {
4780        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4781    }
4782
4783    private File getDataPathForPackage(String packageName, int userId) {
4784        /*
4785         * Until we fully support multiple users, return the directory we
4786         * previously would have. The PackageManagerTests will need to be
4787         * revised when this is changed back..
4788         */
4789        if (userId == 0) {
4790            return new File(mAppDataDir, packageName);
4791        } else {
4792            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4793                + File.separator + packageName);
4794        }
4795    }
4796
4797    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4798        int[] users = sUserManager.getUserIds();
4799        int res = mInstaller.install(packageName, uid, uid, seinfo);
4800        if (res < 0) {
4801            return res;
4802        }
4803        for (int user : users) {
4804            if (user != 0) {
4805                res = mInstaller.createUserData(packageName,
4806                        UserHandle.getUid(user, uid), user, seinfo);
4807                if (res < 0) {
4808                    return res;
4809                }
4810            }
4811        }
4812        return res;
4813    }
4814
4815    private int removeDataDirsLI(String packageName) {
4816        int[] users = sUserManager.getUserIds();
4817        int res = 0;
4818        for (int user : users) {
4819            int resInner = mInstaller.remove(packageName, user);
4820            if (resInner < 0) {
4821                res = resInner;
4822            }
4823        }
4824
4825        return res;
4826    }
4827
4828    private int deleteCodeCacheDirsLI(String packageName) {
4829        int[] users = sUserManager.getUserIds();
4830        int res = 0;
4831        for (int user : users) {
4832            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4833            if (resInner < 0) {
4834                res = resInner;
4835            }
4836        }
4837        return res;
4838    }
4839
4840    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4841            PackageParser.Package changingLib) {
4842        if (file.path != null) {
4843            usesLibraryFiles.add(file.path);
4844            return;
4845        }
4846        PackageParser.Package p = mPackages.get(file.apk);
4847        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4848            // If we are doing this while in the middle of updating a library apk,
4849            // then we need to make sure to use that new apk for determining the
4850            // dependencies here.  (We haven't yet finished committing the new apk
4851            // to the package manager state.)
4852            if (p == null || p.packageName.equals(changingLib.packageName)) {
4853                p = changingLib;
4854            }
4855        }
4856        if (p != null) {
4857            usesLibraryFiles.addAll(p.getAllCodePaths());
4858        }
4859    }
4860
4861    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4862            PackageParser.Package changingLib) throws PackageManagerException {
4863        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4864            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4865            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4866            for (int i=0; i<N; i++) {
4867                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4868                if (file == null) {
4869                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4870                            "Package " + pkg.packageName + " requires unavailable shared library "
4871                            + pkg.usesLibraries.get(i) + "; failing!");
4872                }
4873                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4874            }
4875            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4876            for (int i=0; i<N; i++) {
4877                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4878                if (file == null) {
4879                    Slog.w(TAG, "Package " + pkg.packageName
4880                            + " desires unavailable shared library "
4881                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4882                } else {
4883                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4884                }
4885            }
4886            N = usesLibraryFiles.size();
4887            if (N > 0) {
4888                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4889            } else {
4890                pkg.usesLibraryFiles = null;
4891            }
4892        }
4893    }
4894
4895    private static boolean hasString(List<String> list, List<String> which) {
4896        if (list == null) {
4897            return false;
4898        }
4899        for (int i=list.size()-1; i>=0; i--) {
4900            for (int j=which.size()-1; j>=0; j--) {
4901                if (which.get(j).equals(list.get(i))) {
4902                    return true;
4903                }
4904            }
4905        }
4906        return false;
4907    }
4908
4909    private void updateAllSharedLibrariesLPw() {
4910        for (PackageParser.Package pkg : mPackages.values()) {
4911            try {
4912                updateSharedLibrariesLPw(pkg, null);
4913            } catch (PackageManagerException e) {
4914                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4915            }
4916        }
4917    }
4918
4919    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4920            PackageParser.Package changingPkg) {
4921        ArrayList<PackageParser.Package> res = null;
4922        for (PackageParser.Package pkg : mPackages.values()) {
4923            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4924                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4925                if (res == null) {
4926                    res = new ArrayList<PackageParser.Package>();
4927                }
4928                res.add(pkg);
4929                try {
4930                    updateSharedLibrariesLPw(pkg, changingPkg);
4931                } catch (PackageManagerException e) {
4932                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4933                }
4934            }
4935        }
4936        return res;
4937    }
4938
4939    /**
4940     * Derive the value of the {@code cpuAbiOverride} based on the provided
4941     * value and an optional stored value from the package settings.
4942     */
4943    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4944        String cpuAbiOverride = null;
4945
4946        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4947            cpuAbiOverride = null;
4948        } else if (abiOverride != null) {
4949            cpuAbiOverride = abiOverride;
4950        } else if (settings != null) {
4951            cpuAbiOverride = settings.cpuAbiOverrideString;
4952        }
4953
4954        return cpuAbiOverride;
4955    }
4956
4957    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4958            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4959        boolean success = false;
4960        try {
4961            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
4962                    currentTime, user);
4963            success = true;
4964            return res;
4965        } finally {
4966            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4967                removeDataDirsLI(pkg.packageName);
4968            }
4969        }
4970    }
4971
4972    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
4973            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4974        final File scanFile = new File(pkg.codePath);
4975        if (pkg.applicationInfo.getCodePath() == null ||
4976                pkg.applicationInfo.getResourcePath() == null) {
4977            // Bail out. The resource and code paths haven't been set.
4978            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4979                    "Code and resource paths haven't been set correctly");
4980        }
4981
4982        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4983            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4984        }
4985
4986        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4987            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4988        }
4989
4990        if (mCustomResolverComponentName != null &&
4991                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4992            setUpCustomResolverActivity(pkg);
4993        }
4994
4995        if (pkg.packageName.equals("android")) {
4996            synchronized (mPackages) {
4997                if (mAndroidApplication != null) {
4998                    Slog.w(TAG, "*************************************************");
4999                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5000                    Slog.w(TAG, " file=" + scanFile);
5001                    Slog.w(TAG, "*************************************************");
5002                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5003                            "Core android package being redefined.  Skipping.");
5004                }
5005
5006                // Set up information for our fall-back user intent resolution activity.
5007                mPlatformPackage = pkg;
5008                pkg.mVersionCode = mSdkVersion;
5009                mAndroidApplication = pkg.applicationInfo;
5010
5011                if (!mResolverReplaced) {
5012                    mResolveActivity.applicationInfo = mAndroidApplication;
5013                    mResolveActivity.name = ResolverActivity.class.getName();
5014                    mResolveActivity.packageName = mAndroidApplication.packageName;
5015                    mResolveActivity.processName = "system:ui";
5016                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5017                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5018                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5019                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5020                    mResolveActivity.exported = true;
5021                    mResolveActivity.enabled = true;
5022                    mResolveInfo.activityInfo = mResolveActivity;
5023                    mResolveInfo.priority = 0;
5024                    mResolveInfo.preferredOrder = 0;
5025                    mResolveInfo.match = 0;
5026                    mResolveComponentName = new ComponentName(
5027                            mAndroidApplication.packageName, mResolveActivity.name);
5028                }
5029            }
5030        }
5031
5032        if (DEBUG_PACKAGE_SCANNING) {
5033            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5034                Log.d(TAG, "Scanning package " + pkg.packageName);
5035        }
5036
5037        if (mPackages.containsKey(pkg.packageName)
5038                || mSharedLibraries.containsKey(pkg.packageName)) {
5039            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5040                    "Application package " + pkg.packageName
5041                    + " already installed.  Skipping duplicate.");
5042        }
5043
5044        // Initialize package source and resource directories
5045        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5046        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5047
5048        SharedUserSetting suid = null;
5049        PackageSetting pkgSetting = null;
5050
5051        if (!isSystemApp(pkg)) {
5052            // Only system apps can use these features.
5053            pkg.mOriginalPackages = null;
5054            pkg.mRealPackage = null;
5055            pkg.mAdoptPermissions = null;
5056        }
5057
5058        // writer
5059        synchronized (mPackages) {
5060            if (pkg.mSharedUserId != null) {
5061                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5062                if (suid == null) {
5063                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5064                            "Creating application package " + pkg.packageName
5065                            + " for shared user failed");
5066                }
5067                if (DEBUG_PACKAGE_SCANNING) {
5068                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5069                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5070                                + "): packages=" + suid.packages);
5071                }
5072            }
5073
5074            // Check if we are renaming from an original package name.
5075            PackageSetting origPackage = null;
5076            String realName = null;
5077            if (pkg.mOriginalPackages != null) {
5078                // This package may need to be renamed to a previously
5079                // installed name.  Let's check on that...
5080                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5081                if (pkg.mOriginalPackages.contains(renamed)) {
5082                    // This package had originally been installed as the
5083                    // original name, and we have already taken care of
5084                    // transitioning to the new one.  Just update the new
5085                    // one to continue using the old name.
5086                    realName = pkg.mRealPackage;
5087                    if (!pkg.packageName.equals(renamed)) {
5088                        // Callers into this function may have already taken
5089                        // care of renaming the package; only do it here if
5090                        // it is not already done.
5091                        pkg.setPackageName(renamed);
5092                    }
5093
5094                } else {
5095                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5096                        if ((origPackage = mSettings.peekPackageLPr(
5097                                pkg.mOriginalPackages.get(i))) != null) {
5098                            // We do have the package already installed under its
5099                            // original name...  should we use it?
5100                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5101                                // New package is not compatible with original.
5102                                origPackage = null;
5103                                continue;
5104                            } else if (origPackage.sharedUser != null) {
5105                                // Make sure uid is compatible between packages.
5106                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5107                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5108                                            + " to " + pkg.packageName + ": old uid "
5109                                            + origPackage.sharedUser.name
5110                                            + " differs from " + pkg.mSharedUserId);
5111                                    origPackage = null;
5112                                    continue;
5113                                }
5114                            } else {
5115                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5116                                        + pkg.packageName + " to old name " + origPackage.name);
5117                            }
5118                            break;
5119                        }
5120                    }
5121                }
5122            }
5123
5124            if (mTransferedPackages.contains(pkg.packageName)) {
5125                Slog.w(TAG, "Package " + pkg.packageName
5126                        + " was transferred to another, but its .apk remains");
5127            }
5128
5129            // Just create the setting, don't add it yet. For already existing packages
5130            // the PkgSetting exists already and doesn't have to be created.
5131            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5132                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5133                    pkg.applicationInfo.primaryCpuAbi,
5134                    pkg.applicationInfo.secondaryCpuAbi,
5135                    pkg.applicationInfo.flags, user, false);
5136            if (pkgSetting == null) {
5137                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5138                        "Creating application package " + pkg.packageName + " failed");
5139            }
5140
5141            if (pkgSetting.origPackage != null) {
5142                // If we are first transitioning from an original package,
5143                // fix up the new package's name now.  We need to do this after
5144                // looking up the package under its new name, so getPackageLP
5145                // can take care of fiddling things correctly.
5146                pkg.setPackageName(origPackage.name);
5147
5148                // File a report about this.
5149                String msg = "New package " + pkgSetting.realName
5150                        + " renamed to replace old package " + pkgSetting.name;
5151                reportSettingsProblem(Log.WARN, msg);
5152
5153                // Make a note of it.
5154                mTransferedPackages.add(origPackage.name);
5155
5156                // No longer need to retain this.
5157                pkgSetting.origPackage = null;
5158            }
5159
5160            if (realName != null) {
5161                // Make a note of it.
5162                mTransferedPackages.add(pkg.packageName);
5163            }
5164
5165            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5166                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5167            }
5168
5169            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5170                // Check all shared libraries and map to their actual file path.
5171                // We only do this here for apps not on a system dir, because those
5172                // are the only ones that can fail an install due to this.  We
5173                // will take care of the system apps by updating all of their
5174                // library paths after the scan is done.
5175                updateSharedLibrariesLPw(pkg, null);
5176            }
5177
5178            if (mFoundPolicyFile) {
5179                SELinuxMMAC.assignSeinfoValue(pkg);
5180            }
5181
5182            pkg.applicationInfo.uid = pkgSetting.appId;
5183            pkg.mExtras = pkgSetting;
5184            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5185                try {
5186                    verifySignaturesLP(pkgSetting, pkg);
5187                } catch (PackageManagerException e) {
5188                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5189                        throw e;
5190                    }
5191                    // The signature has changed, but this package is in the system
5192                    // image...  let's recover!
5193                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5194                    // However...  if this package is part of a shared user, but it
5195                    // doesn't match the signature of the shared user, let's fail.
5196                    // What this means is that you can't change the signatures
5197                    // associated with an overall shared user, which doesn't seem all
5198                    // that unreasonable.
5199                    if (pkgSetting.sharedUser != null) {
5200                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5201                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5202                            throw new PackageManagerException(
5203                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5204                                            "Signature mismatch for shared user : "
5205                                            + pkgSetting.sharedUser);
5206                        }
5207                    }
5208                    // File a report about this.
5209                    String msg = "System package " + pkg.packageName
5210                        + " signature changed; retaining data.";
5211                    reportSettingsProblem(Log.WARN, msg);
5212                }
5213            } else {
5214                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5215                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5216                            + pkg.packageName + " upgrade keys do not match the "
5217                            + "previously installed version");
5218                } else {
5219                    // signatures may have changed as result of upgrade
5220                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5221                }
5222            }
5223            // Verify that this new package doesn't have any content providers
5224            // that conflict with existing packages.  Only do this if the
5225            // package isn't already installed, since we don't want to break
5226            // things that are installed.
5227            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5228                final int N = pkg.providers.size();
5229                int i;
5230                for (i=0; i<N; i++) {
5231                    PackageParser.Provider p = pkg.providers.get(i);
5232                    if (p.info.authority != null) {
5233                        String names[] = p.info.authority.split(";");
5234                        for (int j = 0; j < names.length; j++) {
5235                            if (mProvidersByAuthority.containsKey(names[j])) {
5236                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5237                                final String otherPackageName =
5238                                        ((other != null && other.getComponentName() != null) ?
5239                                                other.getComponentName().getPackageName() : "?");
5240                                throw new PackageManagerException(
5241                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5242                                                "Can't install because provider name " + names[j]
5243                                                + " (in package " + pkg.applicationInfo.packageName
5244                                                + ") is already used by " + otherPackageName);
5245                            }
5246                        }
5247                    }
5248                }
5249            }
5250
5251            if (pkg.mAdoptPermissions != null) {
5252                // This package wants to adopt ownership of permissions from
5253                // another package.
5254                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5255                    final String origName = pkg.mAdoptPermissions.get(i);
5256                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5257                    if (orig != null) {
5258                        if (verifyPackageUpdateLPr(orig, pkg)) {
5259                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5260                                    + pkg.packageName);
5261                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5262                        }
5263                    }
5264                }
5265            }
5266        }
5267
5268        final String pkgName = pkg.packageName;
5269
5270        final long scanFileTime = scanFile.lastModified();
5271        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5272        pkg.applicationInfo.processName = fixProcessName(
5273                pkg.applicationInfo.packageName,
5274                pkg.applicationInfo.processName,
5275                pkg.applicationInfo.uid);
5276
5277        File dataPath;
5278        if (mPlatformPackage == pkg) {
5279            // The system package is special.
5280            dataPath = new File(Environment.getDataDirectory(), "system");
5281
5282            pkg.applicationInfo.dataDir = dataPath.getPath();
5283
5284        } else {
5285            // This is a normal package, need to make its data directory.
5286            dataPath = getDataPathForPackage(pkg.packageName, 0);
5287
5288            boolean uidError = false;
5289            if (dataPath.exists()) {
5290                int currentUid = 0;
5291                try {
5292                    StructStat stat = Os.stat(dataPath.getPath());
5293                    currentUid = stat.st_uid;
5294                } catch (ErrnoException e) {
5295                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5296                }
5297
5298                // If we have mismatched owners for the data path, we have a problem.
5299                if (currentUid != pkg.applicationInfo.uid) {
5300                    boolean recovered = false;
5301                    if (currentUid == 0) {
5302                        // The directory somehow became owned by root.  Wow.
5303                        // This is probably because the system was stopped while
5304                        // installd was in the middle of messing with its libs
5305                        // directory.  Ask installd to fix that.
5306                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5307                                pkg.applicationInfo.uid);
5308                        if (ret >= 0) {
5309                            recovered = true;
5310                            String msg = "Package " + pkg.packageName
5311                                    + " unexpectedly changed to uid 0; recovered to " +
5312                                    + pkg.applicationInfo.uid;
5313                            reportSettingsProblem(Log.WARN, msg);
5314                        }
5315                    }
5316                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5317                            || (scanFlags&SCAN_BOOTING) != 0)) {
5318                        // If this is a system app, we can at least delete its
5319                        // current data so the application will still work.
5320                        int ret = removeDataDirsLI(pkgName);
5321                        if (ret >= 0) {
5322                            // TODO: Kill the processes first
5323                            // Old data gone!
5324                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5325                                    ? "System package " : "Third party package ";
5326                            String msg = prefix + pkg.packageName
5327                                    + " has changed from uid: "
5328                                    + currentUid + " to "
5329                                    + pkg.applicationInfo.uid + "; old data erased";
5330                            reportSettingsProblem(Log.WARN, msg);
5331                            recovered = true;
5332
5333                            // And now re-install the app.
5334                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5335                                                   pkg.applicationInfo.seinfo);
5336                            if (ret == -1) {
5337                                // Ack should not happen!
5338                                msg = prefix + pkg.packageName
5339                                        + " could not have data directory re-created after delete.";
5340                                reportSettingsProblem(Log.WARN, msg);
5341                                throw new PackageManagerException(
5342                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5343                            }
5344                        }
5345                        if (!recovered) {
5346                            mHasSystemUidErrors = true;
5347                        }
5348                    } else if (!recovered) {
5349                        // If we allow this install to proceed, we will be broken.
5350                        // Abort, abort!
5351                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5352                                "scanPackageLI");
5353                    }
5354                    if (!recovered) {
5355                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5356                            + pkg.applicationInfo.uid + "/fs_"
5357                            + currentUid;
5358                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5359                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5360                        String msg = "Package " + pkg.packageName
5361                                + " has mismatched uid: "
5362                                + currentUid + " on disk, "
5363                                + pkg.applicationInfo.uid + " in settings";
5364                        // writer
5365                        synchronized (mPackages) {
5366                            mSettings.mReadMessages.append(msg);
5367                            mSettings.mReadMessages.append('\n');
5368                            uidError = true;
5369                            if (!pkgSetting.uidError) {
5370                                reportSettingsProblem(Log.ERROR, msg);
5371                            }
5372                        }
5373                    }
5374                }
5375                pkg.applicationInfo.dataDir = dataPath.getPath();
5376                if (mShouldRestoreconData) {
5377                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5378                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5379                                pkg.applicationInfo.uid);
5380                }
5381            } else {
5382                if (DEBUG_PACKAGE_SCANNING) {
5383                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5384                        Log.v(TAG, "Want this data dir: " + dataPath);
5385                }
5386                //invoke installer to do the actual installation
5387                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5388                                           pkg.applicationInfo.seinfo);
5389                if (ret < 0) {
5390                    // Error from installer
5391                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5392                            "Unable to create data dirs [errorCode=" + ret + "]");
5393                }
5394
5395                if (dataPath.exists()) {
5396                    pkg.applicationInfo.dataDir = dataPath.getPath();
5397                } else {
5398                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5399                    pkg.applicationInfo.dataDir = null;
5400                }
5401            }
5402
5403            pkgSetting.uidError = uidError;
5404        }
5405
5406        final String path = scanFile.getPath();
5407        final String codePath = pkg.applicationInfo.getCodePath();
5408        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5409        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5410            setBundledAppAbisAndRoots(pkg, pkgSetting);
5411
5412            // If we haven't found any native libraries for the app, check if it has
5413            // renderscript code. We'll need to force the app to 32 bit if it has
5414            // renderscript bitcode.
5415            if (pkg.applicationInfo.primaryCpuAbi == null
5416                    && pkg.applicationInfo.secondaryCpuAbi == null
5417                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5418                NativeLibraryHelper.Handle handle = null;
5419                try {
5420                    handle = NativeLibraryHelper.Handle.create(scanFile);
5421                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5422                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5423                    }
5424                } catch (IOException ioe) {
5425                    Slog.w(TAG, "Error scanning system app : " + ioe);
5426                } finally {
5427                    IoUtils.closeQuietly(handle);
5428                }
5429            }
5430
5431            setNativeLibraryPaths(pkg);
5432        } else {
5433            // TODO: We can probably be smarter about this stuff. For installed apps,
5434            // we can calculate this information at install time once and for all. For
5435            // system apps, we can probably assume that this information doesn't change
5436            // after the first boot scan. As things stand, we do lots of unnecessary work.
5437
5438            // Give ourselves some initial paths; we'll come back for another
5439            // pass once we've determined ABI below.
5440            setNativeLibraryPaths(pkg);
5441
5442            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5443            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5444            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5445
5446            NativeLibraryHelper.Handle handle = null;
5447            try {
5448                handle = NativeLibraryHelper.Handle.create(scanFile);
5449                // TODO(multiArch): This can be null for apps that didn't go through the
5450                // usual installation process. We can calculate it again, like we
5451                // do during install time.
5452                //
5453                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5454                // unnecessary.
5455                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5456
5457                // Null out the abis so that they can be recalculated.
5458                pkg.applicationInfo.primaryCpuAbi = null;
5459                pkg.applicationInfo.secondaryCpuAbi = null;
5460                if (isMultiArch(pkg.applicationInfo)) {
5461                    // Warn if we've set an abiOverride for multi-lib packages..
5462                    // By definition, we need to copy both 32 and 64 bit libraries for
5463                    // such packages.
5464                    if (pkg.cpuAbiOverride != null
5465                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5466                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5467                    }
5468
5469                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5470                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5471                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5472                        if (isAsec) {
5473                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5474                        } else {
5475                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5476                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5477                                    useIsaSpecificSubdirs);
5478                        }
5479                    }
5480
5481                    maybeThrowExceptionForMultiArchCopy(
5482                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5483
5484                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5485                        if (isAsec) {
5486                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5487                        } else {
5488                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5489                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5490                                    useIsaSpecificSubdirs);
5491                        }
5492                    }
5493
5494                    maybeThrowExceptionForMultiArchCopy(
5495                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5496
5497                    if (abi64 >= 0) {
5498                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5499                    }
5500
5501                    if (abi32 >= 0) {
5502                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5503                        if (abi64 >= 0) {
5504                            pkg.applicationInfo.secondaryCpuAbi = abi;
5505                        } else {
5506                            pkg.applicationInfo.primaryCpuAbi = abi;
5507                        }
5508                    }
5509                } else {
5510                    String[] abiList = (cpuAbiOverride != null) ?
5511                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5512
5513                    // Enable gross and lame hacks for apps that are built with old
5514                    // SDK tools. We must scan their APKs for renderscript bitcode and
5515                    // not launch them if it's present. Don't bother checking on devices
5516                    // that don't have 64 bit support.
5517                    boolean needsRenderScriptOverride = false;
5518                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5519                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5520                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5521                        needsRenderScriptOverride = true;
5522                    }
5523
5524                    final int copyRet;
5525                    if (isAsec) {
5526                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5527                    } else {
5528                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5529                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5530                    }
5531
5532                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5533                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5534                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5535                    }
5536
5537                    if (copyRet >= 0) {
5538                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5539                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5540                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5541                    } else if (needsRenderScriptOverride) {
5542                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5543                    }
5544                }
5545            } catch (IOException ioe) {
5546                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5547            } finally {
5548                IoUtils.closeQuietly(handle);
5549            }
5550
5551            // Now that we've calculated the ABIs and determined if it's an internal app,
5552            // we will go ahead and populate the nativeLibraryPath.
5553            setNativeLibraryPaths(pkg);
5554
5555            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5556            final int[] userIds = sUserManager.getUserIds();
5557            synchronized (mInstallLock) {
5558                // Create a native library symlink only if we have native libraries
5559                // and if the native libraries are 32 bit libraries. We do not provide
5560                // this symlink for 64 bit libraries.
5561                if (pkg.applicationInfo.primaryCpuAbi != null &&
5562                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5563                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5564                    for (int userId : userIds) {
5565                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5566                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5567                                    "Failed linking native library dir (user=" + userId + ")");
5568                        }
5569                    }
5570                }
5571            }
5572        }
5573
5574        // This is a special case for the "system" package, where the ABI is
5575        // dictated by the zygote configuration (and init.rc). We should keep track
5576        // of this ABI so that we can deal with "normal" applications that run under
5577        // the same UID correctly.
5578        if (mPlatformPackage == pkg) {
5579            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5580                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5581        }
5582
5583        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5584        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5585        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5586        // Copy the derived override back to the parsed package, so that we can
5587        // update the package settings accordingly.
5588        pkg.cpuAbiOverride = cpuAbiOverride;
5589
5590        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5591                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5592                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5593
5594        // Push the derived path down into PackageSettings so we know what to
5595        // clean up at uninstall time.
5596        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5597
5598        if (DEBUG_ABI_SELECTION) {
5599            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5600                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5601                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5602        }
5603
5604        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5605            // We don't do this here during boot because we can do it all
5606            // at once after scanning all existing packages.
5607            //
5608            // We also do this *before* we perform dexopt on this package, so that
5609            // we can avoid redundant dexopts, and also to make sure we've got the
5610            // code and package path correct.
5611            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5612                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5613        }
5614
5615        if ((scanFlags & SCAN_NO_DEX) == 0) {
5616            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5617                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5618                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5619            }
5620        }
5621
5622        if (mFactoryTest && pkg.requestedPermissions.contains(
5623                android.Manifest.permission.FACTORY_TEST)) {
5624            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5625        }
5626
5627        ArrayList<PackageParser.Package> clientLibPkgs = null;
5628
5629        // writer
5630        synchronized (mPackages) {
5631            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5632                // Only system apps can add new shared libraries.
5633                if (pkg.libraryNames != null) {
5634                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5635                        String name = pkg.libraryNames.get(i);
5636                        boolean allowed = false;
5637                        if (isUpdatedSystemApp(pkg)) {
5638                            // New library entries can only be added through the
5639                            // system image.  This is important to get rid of a lot
5640                            // of nasty edge cases: for example if we allowed a non-
5641                            // system update of the app to add a library, then uninstalling
5642                            // the update would make the library go away, and assumptions
5643                            // we made such as through app install filtering would now
5644                            // have allowed apps on the device which aren't compatible
5645                            // with it.  Better to just have the restriction here, be
5646                            // conservative, and create many fewer cases that can negatively
5647                            // impact the user experience.
5648                            final PackageSetting sysPs = mSettings
5649                                    .getDisabledSystemPkgLPr(pkg.packageName);
5650                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5651                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5652                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5653                                        allowed = true;
5654                                        allowed = true;
5655                                        break;
5656                                    }
5657                                }
5658                            }
5659                        } else {
5660                            allowed = true;
5661                        }
5662                        if (allowed) {
5663                            if (!mSharedLibraries.containsKey(name)) {
5664                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5665                            } else if (!name.equals(pkg.packageName)) {
5666                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5667                                        + name + " already exists; skipping");
5668                            }
5669                        } else {
5670                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5671                                    + name + " that is not declared on system image; skipping");
5672                        }
5673                    }
5674                    if ((scanFlags&SCAN_BOOTING) == 0) {
5675                        // If we are not booting, we need to update any applications
5676                        // that are clients of our shared library.  If we are booting,
5677                        // this will all be done once the scan is complete.
5678                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5679                    }
5680                }
5681            }
5682        }
5683
5684        // We also need to dexopt any apps that are dependent on this library.  Note that
5685        // if these fail, we should abort the install since installing the library will
5686        // result in some apps being broken.
5687        if (clientLibPkgs != null) {
5688            if ((scanFlags & SCAN_NO_DEX) == 0) {
5689                for (int i = 0; i < clientLibPkgs.size(); i++) {
5690                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5691                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5692                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5693                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5694                                "scanPackageLI failed to dexopt clientLibPkgs");
5695                    }
5696                }
5697            }
5698        }
5699
5700        // Request the ActivityManager to kill the process(only for existing packages)
5701        // so that we do not end up in a confused state while the user is still using the older
5702        // version of the application while the new one gets installed.
5703        if ((scanFlags & SCAN_REPLACING) != 0) {
5704            killApplication(pkg.applicationInfo.packageName,
5705                        pkg.applicationInfo.uid, "update pkg");
5706        }
5707
5708        // Also need to kill any apps that are dependent on the library.
5709        if (clientLibPkgs != null) {
5710            for (int i=0; i<clientLibPkgs.size(); i++) {
5711                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5712                killApplication(clientPkg.applicationInfo.packageName,
5713                        clientPkg.applicationInfo.uid, "update lib");
5714            }
5715        }
5716
5717        // writer
5718        synchronized (mPackages) {
5719            // We don't expect installation to fail beyond this point
5720
5721            // Add the new setting to mSettings
5722            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5723            // Add the new setting to mPackages
5724            mPackages.put(pkg.applicationInfo.packageName, pkg);
5725            // Make sure we don't accidentally delete its data.
5726            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5727            while (iter.hasNext()) {
5728                PackageCleanItem item = iter.next();
5729                if (pkgName.equals(item.packageName)) {
5730                    iter.remove();
5731                }
5732            }
5733
5734            // Take care of first install / last update times.
5735            if (currentTime != 0) {
5736                if (pkgSetting.firstInstallTime == 0) {
5737                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5738                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5739                    pkgSetting.lastUpdateTime = currentTime;
5740                }
5741            } else if (pkgSetting.firstInstallTime == 0) {
5742                // We need *something*.  Take time time stamp of the file.
5743                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5744            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5745                if (scanFileTime != pkgSetting.timeStamp) {
5746                    // A package on the system image has changed; consider this
5747                    // to be an update.
5748                    pkgSetting.lastUpdateTime = scanFileTime;
5749                }
5750            }
5751
5752            // Add the package's KeySets to the global KeySetManagerService
5753            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5754            try {
5755                // Old KeySetData no longer valid.
5756                ksms.removeAppKeySetDataLPw(pkg.packageName);
5757                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5758                if (pkg.mKeySetMapping != null) {
5759                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5760                            pkg.mKeySetMapping.entrySet()) {
5761                        if (entry.getValue() != null) {
5762                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5763                                                          entry.getValue(), entry.getKey());
5764                        }
5765                    }
5766                    if (pkg.mUpgradeKeySets != null) {
5767                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5768                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5769                        }
5770                    }
5771                }
5772            } catch (NullPointerException e) {
5773                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5774            } catch (IllegalArgumentException e) {
5775                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5776            }
5777
5778            int N = pkg.providers.size();
5779            StringBuilder r = null;
5780            int i;
5781            for (i=0; i<N; i++) {
5782                PackageParser.Provider p = pkg.providers.get(i);
5783                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5784                        p.info.processName, pkg.applicationInfo.uid);
5785                mProviders.addProvider(p);
5786                p.syncable = p.info.isSyncable;
5787                if (p.info.authority != null) {
5788                    String names[] = p.info.authority.split(";");
5789                    p.info.authority = null;
5790                    for (int j = 0; j < names.length; j++) {
5791                        if (j == 1 && p.syncable) {
5792                            // We only want the first authority for a provider to possibly be
5793                            // syncable, so if we already added this provider using a different
5794                            // authority clear the syncable flag. We copy the provider before
5795                            // changing it because the mProviders object contains a reference
5796                            // to a provider that we don't want to change.
5797                            // Only do this for the second authority since the resulting provider
5798                            // object can be the same for all future authorities for this provider.
5799                            p = new PackageParser.Provider(p);
5800                            p.syncable = false;
5801                        }
5802                        if (!mProvidersByAuthority.containsKey(names[j])) {
5803                            mProvidersByAuthority.put(names[j], p);
5804                            if (p.info.authority == null) {
5805                                p.info.authority = names[j];
5806                            } else {
5807                                p.info.authority = p.info.authority + ";" + names[j];
5808                            }
5809                            if (DEBUG_PACKAGE_SCANNING) {
5810                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5811                                    Log.d(TAG, "Registered content provider: " + names[j]
5812                                            + ", className = " + p.info.name + ", isSyncable = "
5813                                            + p.info.isSyncable);
5814                            }
5815                        } else {
5816                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5817                            Slog.w(TAG, "Skipping provider name " + names[j] +
5818                                    " (in package " + pkg.applicationInfo.packageName +
5819                                    "): name already used by "
5820                                    + ((other != null && other.getComponentName() != null)
5821                                            ? other.getComponentName().getPackageName() : "?"));
5822                        }
5823                    }
5824                }
5825                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5826                    if (r == null) {
5827                        r = new StringBuilder(256);
5828                    } else {
5829                        r.append(' ');
5830                    }
5831                    r.append(p.info.name);
5832                }
5833            }
5834            if (r != null) {
5835                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5836            }
5837
5838            N = pkg.services.size();
5839            r = null;
5840            for (i=0; i<N; i++) {
5841                PackageParser.Service s = pkg.services.get(i);
5842                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5843                        s.info.processName, pkg.applicationInfo.uid);
5844                mServices.addService(s);
5845                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5846                    if (r == null) {
5847                        r = new StringBuilder(256);
5848                    } else {
5849                        r.append(' ');
5850                    }
5851                    r.append(s.info.name);
5852                }
5853            }
5854            if (r != null) {
5855                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5856            }
5857
5858            N = pkg.receivers.size();
5859            r = null;
5860            for (i=0; i<N; i++) {
5861                PackageParser.Activity a = pkg.receivers.get(i);
5862                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5863                        a.info.processName, pkg.applicationInfo.uid);
5864                mReceivers.addActivity(a, "receiver");
5865                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5866                    if (r == null) {
5867                        r = new StringBuilder(256);
5868                    } else {
5869                        r.append(' ');
5870                    }
5871                    r.append(a.info.name);
5872                }
5873            }
5874            if (r != null) {
5875                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5876            }
5877
5878            N = pkg.activities.size();
5879            r = null;
5880            for (i=0; i<N; i++) {
5881                PackageParser.Activity a = pkg.activities.get(i);
5882                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5883                        a.info.processName, pkg.applicationInfo.uid);
5884                mActivities.addActivity(a, "activity");
5885                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5886                    if (r == null) {
5887                        r = new StringBuilder(256);
5888                    } else {
5889                        r.append(' ');
5890                    }
5891                    r.append(a.info.name);
5892                }
5893            }
5894            if (r != null) {
5895                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5896            }
5897
5898            N = pkg.permissionGroups.size();
5899            r = null;
5900            for (i=0; i<N; i++) {
5901                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5902                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5903                if (cur == null) {
5904                    mPermissionGroups.put(pg.info.name, pg);
5905                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5906                        if (r == null) {
5907                            r = new StringBuilder(256);
5908                        } else {
5909                            r.append(' ');
5910                        }
5911                        r.append(pg.info.name);
5912                    }
5913                } else {
5914                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5915                            + pg.info.packageName + " ignored: original from "
5916                            + cur.info.packageName);
5917                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5918                        if (r == null) {
5919                            r = new StringBuilder(256);
5920                        } else {
5921                            r.append(' ');
5922                        }
5923                        r.append("DUP:");
5924                        r.append(pg.info.name);
5925                    }
5926                }
5927            }
5928            if (r != null) {
5929                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5930            }
5931
5932            N = pkg.permissions.size();
5933            r = null;
5934            for (i=0; i<N; i++) {
5935                PackageParser.Permission p = pkg.permissions.get(i);
5936                HashMap<String, BasePermission> permissionMap =
5937                        p.tree ? mSettings.mPermissionTrees
5938                        : mSettings.mPermissions;
5939                p.group = mPermissionGroups.get(p.info.group);
5940                if (p.info.group == null || p.group != null) {
5941                    BasePermission bp = permissionMap.get(p.info.name);
5942                    if (bp == null) {
5943                        bp = new BasePermission(p.info.name, p.info.packageName,
5944                                BasePermission.TYPE_NORMAL);
5945                        permissionMap.put(p.info.name, bp);
5946                    }
5947                    if (bp.perm == null) {
5948                        if (bp.sourcePackage != null
5949                                && !bp.sourcePackage.equals(p.info.packageName)) {
5950                            // If this is a permission that was formerly defined by a non-system
5951                            // app, but is now defined by a system app (following an upgrade),
5952                            // discard the previous declaration and consider the system's to be
5953                            // canonical.
5954                            if (isSystemApp(p.owner)) {
5955                                String msg = "New decl " + p.owner + " of permission  "
5956                                        + p.info.name + " is system";
5957                                reportSettingsProblem(Log.WARN, msg);
5958                                bp.sourcePackage = null;
5959                            }
5960                        }
5961                        if (bp.sourcePackage == null
5962                                || bp.sourcePackage.equals(p.info.packageName)) {
5963                            BasePermission tree = findPermissionTreeLP(p.info.name);
5964                            if (tree == null
5965                                    || tree.sourcePackage.equals(p.info.packageName)) {
5966                                bp.packageSetting = pkgSetting;
5967                                bp.perm = p;
5968                                bp.uid = pkg.applicationInfo.uid;
5969                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5970                                    if (r == null) {
5971                                        r = new StringBuilder(256);
5972                                    } else {
5973                                        r.append(' ');
5974                                    }
5975                                    r.append(p.info.name);
5976                                }
5977                            } else {
5978                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5979                                        + p.info.packageName + " ignored: base tree "
5980                                        + tree.name + " is from package "
5981                                        + tree.sourcePackage);
5982                            }
5983                        } else {
5984                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5985                                    + p.info.packageName + " ignored: original from "
5986                                    + bp.sourcePackage);
5987                        }
5988                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5989                        if (r == null) {
5990                            r = new StringBuilder(256);
5991                        } else {
5992                            r.append(' ');
5993                        }
5994                        r.append("DUP:");
5995                        r.append(p.info.name);
5996                    }
5997                    if (bp.perm == p) {
5998                        bp.protectionLevel = p.info.protectionLevel;
5999                    }
6000                } else {
6001                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6002                            + p.info.packageName + " ignored: no group "
6003                            + p.group);
6004                }
6005            }
6006            if (r != null) {
6007                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6008            }
6009
6010            N = pkg.instrumentation.size();
6011            r = null;
6012            for (i=0; i<N; i++) {
6013                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6014                a.info.packageName = pkg.applicationInfo.packageName;
6015                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6016                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6017                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6018                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6019                a.info.dataDir = pkg.applicationInfo.dataDir;
6020
6021                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6022                // need other information about the application, like the ABI and what not ?
6023                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6024                mInstrumentation.put(a.getComponentName(), a);
6025                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6026                    if (r == null) {
6027                        r = new StringBuilder(256);
6028                    } else {
6029                        r.append(' ');
6030                    }
6031                    r.append(a.info.name);
6032                }
6033            }
6034            if (r != null) {
6035                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6036            }
6037
6038            if (pkg.protectedBroadcasts != null) {
6039                N = pkg.protectedBroadcasts.size();
6040                for (i=0; i<N; i++) {
6041                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6042                }
6043            }
6044
6045            pkgSetting.setTimeStamp(scanFileTime);
6046
6047            // Create idmap files for pairs of (packages, overlay packages).
6048            // Note: "android", ie framework-res.apk, is handled by native layers.
6049            if (pkg.mOverlayTarget != null) {
6050                // This is an overlay package.
6051                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6052                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6053                        mOverlays.put(pkg.mOverlayTarget,
6054                                new HashMap<String, PackageParser.Package>());
6055                    }
6056                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6057                    map.put(pkg.packageName, pkg);
6058                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6059                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6060                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6061                                "scanPackageLI failed to createIdmap");
6062                    }
6063                }
6064            } else if (mOverlays.containsKey(pkg.packageName) &&
6065                    !pkg.packageName.equals("android")) {
6066                // This is a regular package, with one or more known overlay packages.
6067                createIdmapsForPackageLI(pkg);
6068            }
6069        }
6070
6071        return pkg;
6072    }
6073
6074    /**
6075     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6076     * i.e, so that all packages can be run inside a single process if required.
6077     *
6078     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6079     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6080     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6081     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6082     * updating a package that belongs to a shared user.
6083     *
6084     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6085     * adds unnecessary complexity.
6086     */
6087    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6088            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6089        String requiredInstructionSet = null;
6090        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6091            requiredInstructionSet = VMRuntime.getInstructionSet(
6092                     scannedPackage.applicationInfo.primaryCpuAbi);
6093        }
6094
6095        PackageSetting requirer = null;
6096        for (PackageSetting ps : packagesForUser) {
6097            // If packagesForUser contains scannedPackage, we skip it. This will happen
6098            // when scannedPackage is an update of an existing package. Without this check,
6099            // we will never be able to change the ABI of any package belonging to a shared
6100            // user, even if it's compatible with other packages.
6101            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6102                if (ps.primaryCpuAbiString == null) {
6103                    continue;
6104                }
6105
6106                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6107                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6108                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6109                    // this but there's not much we can do.
6110                    String errorMessage = "Instruction set mismatch, "
6111                            + ((requirer == null) ? "[caller]" : requirer)
6112                            + " requires " + requiredInstructionSet + " whereas " + ps
6113                            + " requires " + instructionSet;
6114                    Slog.w(TAG, errorMessage);
6115                }
6116
6117                if (requiredInstructionSet == null) {
6118                    requiredInstructionSet = instructionSet;
6119                    requirer = ps;
6120                }
6121            }
6122        }
6123
6124        if (requiredInstructionSet != null) {
6125            String adjustedAbi;
6126            if (requirer != null) {
6127                // requirer != null implies that either scannedPackage was null or that scannedPackage
6128                // did not require an ABI, in which case we have to adjust scannedPackage to match
6129                // the ABI of the set (which is the same as requirer's ABI)
6130                adjustedAbi = requirer.primaryCpuAbiString;
6131                if (scannedPackage != null) {
6132                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6133                }
6134            } else {
6135                // requirer == null implies that we're updating all ABIs in the set to
6136                // match scannedPackage.
6137                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6138            }
6139
6140            for (PackageSetting ps : packagesForUser) {
6141                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6142                    if (ps.primaryCpuAbiString != null) {
6143                        continue;
6144                    }
6145
6146                    ps.primaryCpuAbiString = adjustedAbi;
6147                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6148                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6149                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6150
6151                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6152                                deferDexOpt, true) == DEX_OPT_FAILED) {
6153                            ps.primaryCpuAbiString = null;
6154                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6155                            return;
6156                        } else {
6157                            mInstaller.rmdex(ps.codePathString,
6158                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6159                        }
6160                    }
6161                }
6162            }
6163        }
6164    }
6165
6166    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6167        synchronized (mPackages) {
6168            mResolverReplaced = true;
6169            // Set up information for custom user intent resolution activity.
6170            mResolveActivity.applicationInfo = pkg.applicationInfo;
6171            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6172            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6173            mResolveActivity.processName = null;
6174            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6175            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6176                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6177            mResolveActivity.theme = 0;
6178            mResolveActivity.exported = true;
6179            mResolveActivity.enabled = true;
6180            mResolveInfo.activityInfo = mResolveActivity;
6181            mResolveInfo.priority = 0;
6182            mResolveInfo.preferredOrder = 0;
6183            mResolveInfo.match = 0;
6184            mResolveComponentName = mCustomResolverComponentName;
6185            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6186                    mResolveComponentName);
6187        }
6188    }
6189
6190    private static String calculateBundledApkRoot(final String codePathString) {
6191        final File codePath = new File(codePathString);
6192        final File codeRoot;
6193        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6194            codeRoot = Environment.getRootDirectory();
6195        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6196            codeRoot = Environment.getOemDirectory();
6197        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6198            codeRoot = Environment.getVendorDirectory();
6199        } else {
6200            // Unrecognized code path; take its top real segment as the apk root:
6201            // e.g. /something/app/blah.apk => /something
6202            try {
6203                File f = codePath.getCanonicalFile();
6204                File parent = f.getParentFile();    // non-null because codePath is a file
6205                File tmp;
6206                while ((tmp = parent.getParentFile()) != null) {
6207                    f = parent;
6208                    parent = tmp;
6209                }
6210                codeRoot = f;
6211                Slog.w(TAG, "Unrecognized code path "
6212                        + codePath + " - using " + codeRoot);
6213            } catch (IOException e) {
6214                // Can't canonicalize the code path -- shenanigans?
6215                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6216                return Environment.getRootDirectory().getPath();
6217            }
6218        }
6219        return codeRoot.getPath();
6220    }
6221
6222    /**
6223     * Derive and set the location of native libraries for the given package,
6224     * which varies depending on where and how the package was installed.
6225     */
6226    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6227        final ApplicationInfo info = pkg.applicationInfo;
6228        final String codePath = pkg.codePath;
6229        final File codeFile = new File(codePath);
6230        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6231        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6232
6233        info.nativeLibraryRootDir = null;
6234        info.nativeLibraryRootRequiresIsa = false;
6235        info.nativeLibraryDir = null;
6236        info.secondaryNativeLibraryDir = null;
6237
6238        if (isApkFile(codeFile)) {
6239            // Monolithic install
6240            if (bundledApp) {
6241                // If "/system/lib64/apkname" exists, assume that is the per-package
6242                // native library directory to use; otherwise use "/system/lib/apkname".
6243                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6244                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6245                        getPrimaryInstructionSet(info));
6246
6247                // This is a bundled system app so choose the path based on the ABI.
6248                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6249                // is just the default path.
6250                final String apkName = deriveCodePathName(codePath);
6251                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6252                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6253                        apkName).getAbsolutePath();
6254
6255                if (info.secondaryCpuAbi != null) {
6256                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6257                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6258                            secondaryLibDir, apkName).getAbsolutePath();
6259                }
6260            } else if (asecApp) {
6261                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6262                        .getAbsolutePath();
6263            } else {
6264                final String apkName = deriveCodePathName(codePath);
6265                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6266                        .getAbsolutePath();
6267            }
6268
6269            info.nativeLibraryRootRequiresIsa = false;
6270            info.nativeLibraryDir = info.nativeLibraryRootDir;
6271        } else {
6272            // Cluster install
6273            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6274            info.nativeLibraryRootRequiresIsa = true;
6275
6276            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6277                    getPrimaryInstructionSet(info)).getAbsolutePath();
6278
6279            if (info.secondaryCpuAbi != null) {
6280                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6281                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6282            }
6283        }
6284    }
6285
6286    /**
6287     * Calculate the abis and roots for a bundled app. These can uniquely
6288     * be determined from the contents of the system partition, i.e whether
6289     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6290     * of this information, and instead assume that the system was built
6291     * sensibly.
6292     */
6293    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6294                                           PackageSetting pkgSetting) {
6295        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6296
6297        // If "/system/lib64/apkname" exists, assume that is the per-package
6298        // native library directory to use; otherwise use "/system/lib/apkname".
6299        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6300        setBundledAppAbi(pkg, apkRoot, apkName);
6301        // pkgSetting might be null during rescan following uninstall of updates
6302        // to a bundled app, so accommodate that possibility.  The settings in
6303        // that case will be established later from the parsed package.
6304        //
6305        // If the settings aren't null, sync them up with what we've just derived.
6306        // note that apkRoot isn't stored in the package settings.
6307        if (pkgSetting != null) {
6308            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6309            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6310        }
6311    }
6312
6313    /**
6314     * Deduces the ABI of a bundled app and sets the relevant fields on the
6315     * parsed pkg object.
6316     *
6317     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6318     *        under which system libraries are installed.
6319     * @param apkName the name of the installed package.
6320     */
6321    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6322        final File codeFile = new File(pkg.codePath);
6323
6324        final boolean has64BitLibs;
6325        final boolean has32BitLibs;
6326        if (isApkFile(codeFile)) {
6327            // Monolithic install
6328            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6329            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6330        } else {
6331            // Cluster install
6332            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6333            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6334                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6335                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6336                has64BitLibs = (new File(rootDir, isa)).exists();
6337            } else {
6338                has64BitLibs = false;
6339            }
6340            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6341                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6342                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6343                has32BitLibs = (new File(rootDir, isa)).exists();
6344            } else {
6345                has32BitLibs = false;
6346            }
6347        }
6348
6349        if (has64BitLibs && !has32BitLibs) {
6350            // The package has 64 bit libs, but not 32 bit libs. Its primary
6351            // ABI should be 64 bit. We can safely assume here that the bundled
6352            // native libraries correspond to the most preferred ABI in the list.
6353
6354            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6355            pkg.applicationInfo.secondaryCpuAbi = null;
6356        } else if (has32BitLibs && !has64BitLibs) {
6357            // The package has 32 bit libs but not 64 bit libs. Its primary
6358            // ABI should be 32 bit.
6359
6360            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6361            pkg.applicationInfo.secondaryCpuAbi = null;
6362        } else if (has32BitLibs && has64BitLibs) {
6363            // The application has both 64 and 32 bit bundled libraries. We check
6364            // here that the app declares multiArch support, and warn if it doesn't.
6365            //
6366            // We will be lenient here and record both ABIs. The primary will be the
6367            // ABI that's higher on the list, i.e, a device that's configured to prefer
6368            // 64 bit apps will see a 64 bit primary ABI,
6369
6370            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6371                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6372            }
6373
6374            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6375                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6376                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6377            } else {
6378                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6379                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6380            }
6381        } else {
6382            pkg.applicationInfo.primaryCpuAbi = null;
6383            pkg.applicationInfo.secondaryCpuAbi = null;
6384        }
6385    }
6386
6387    private void killApplication(String pkgName, int appId, String reason) {
6388        // Request the ActivityManager to kill the process(only for existing packages)
6389        // so that we do not end up in a confused state while the user is still using the older
6390        // version of the application while the new one gets installed.
6391        IActivityManager am = ActivityManagerNative.getDefault();
6392        if (am != null) {
6393            try {
6394                am.killApplicationWithAppId(pkgName, appId, reason);
6395            } catch (RemoteException e) {
6396            }
6397        }
6398    }
6399
6400    void removePackageLI(PackageSetting ps, boolean chatty) {
6401        if (DEBUG_INSTALL) {
6402            if (chatty)
6403                Log.d(TAG, "Removing package " + ps.name);
6404        }
6405
6406        // writer
6407        synchronized (mPackages) {
6408            mPackages.remove(ps.name);
6409            final PackageParser.Package pkg = ps.pkg;
6410            if (pkg != null) {
6411                cleanPackageDataStructuresLILPw(pkg, chatty);
6412            }
6413        }
6414    }
6415
6416    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6417        if (DEBUG_INSTALL) {
6418            if (chatty)
6419                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6420        }
6421
6422        // writer
6423        synchronized (mPackages) {
6424            mPackages.remove(pkg.applicationInfo.packageName);
6425            cleanPackageDataStructuresLILPw(pkg, chatty);
6426        }
6427    }
6428
6429    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6430        int N = pkg.providers.size();
6431        StringBuilder r = null;
6432        int i;
6433        for (i=0; i<N; i++) {
6434            PackageParser.Provider p = pkg.providers.get(i);
6435            mProviders.removeProvider(p);
6436            if (p.info.authority == null) {
6437
6438                /* There was another ContentProvider with this authority when
6439                 * this app was installed so this authority is null,
6440                 * Ignore it as we don't have to unregister the provider.
6441                 */
6442                continue;
6443            }
6444            String names[] = p.info.authority.split(";");
6445            for (int j = 0; j < names.length; j++) {
6446                if (mProvidersByAuthority.get(names[j]) == p) {
6447                    mProvidersByAuthority.remove(names[j]);
6448                    if (DEBUG_REMOVE) {
6449                        if (chatty)
6450                            Log.d(TAG, "Unregistered content provider: " + names[j]
6451                                    + ", className = " + p.info.name + ", isSyncable = "
6452                                    + p.info.isSyncable);
6453                    }
6454                }
6455            }
6456            if (DEBUG_REMOVE && chatty) {
6457                if (r == null) {
6458                    r = new StringBuilder(256);
6459                } else {
6460                    r.append(' ');
6461                }
6462                r.append(p.info.name);
6463            }
6464        }
6465        if (r != null) {
6466            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6467        }
6468
6469        N = pkg.services.size();
6470        r = null;
6471        for (i=0; i<N; i++) {
6472            PackageParser.Service s = pkg.services.get(i);
6473            mServices.removeService(s);
6474            if (chatty) {
6475                if (r == null) {
6476                    r = new StringBuilder(256);
6477                } else {
6478                    r.append(' ');
6479                }
6480                r.append(s.info.name);
6481            }
6482        }
6483        if (r != null) {
6484            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6485        }
6486
6487        N = pkg.receivers.size();
6488        r = null;
6489        for (i=0; i<N; i++) {
6490            PackageParser.Activity a = pkg.receivers.get(i);
6491            mReceivers.removeActivity(a, "receiver");
6492            if (DEBUG_REMOVE && chatty) {
6493                if (r == null) {
6494                    r = new StringBuilder(256);
6495                } else {
6496                    r.append(' ');
6497                }
6498                r.append(a.info.name);
6499            }
6500        }
6501        if (r != null) {
6502            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6503        }
6504
6505        N = pkg.activities.size();
6506        r = null;
6507        for (i=0; i<N; i++) {
6508            PackageParser.Activity a = pkg.activities.get(i);
6509            mActivities.removeActivity(a, "activity");
6510            if (DEBUG_REMOVE && chatty) {
6511                if (r == null) {
6512                    r = new StringBuilder(256);
6513                } else {
6514                    r.append(' ');
6515                }
6516                r.append(a.info.name);
6517            }
6518        }
6519        if (r != null) {
6520            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6521        }
6522
6523        N = pkg.permissions.size();
6524        r = null;
6525        for (i=0; i<N; i++) {
6526            PackageParser.Permission p = pkg.permissions.get(i);
6527            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6528            if (bp == null) {
6529                bp = mSettings.mPermissionTrees.get(p.info.name);
6530            }
6531            if (bp != null && bp.perm == p) {
6532                bp.perm = null;
6533                if (DEBUG_REMOVE && chatty) {
6534                    if (r == null) {
6535                        r = new StringBuilder(256);
6536                    } else {
6537                        r.append(' ');
6538                    }
6539                    r.append(p.info.name);
6540                }
6541            }
6542            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6543                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6544                if (appOpPerms != null) {
6545                    appOpPerms.remove(pkg.packageName);
6546                }
6547            }
6548        }
6549        if (r != null) {
6550            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6551        }
6552
6553        N = pkg.requestedPermissions.size();
6554        r = null;
6555        for (i=0; i<N; i++) {
6556            String perm = pkg.requestedPermissions.get(i);
6557            BasePermission bp = mSettings.mPermissions.get(perm);
6558            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6559                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6560                if (appOpPerms != null) {
6561                    appOpPerms.remove(pkg.packageName);
6562                    if (appOpPerms.isEmpty()) {
6563                        mAppOpPermissionPackages.remove(perm);
6564                    }
6565                }
6566            }
6567        }
6568        if (r != null) {
6569            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6570        }
6571
6572        N = pkg.instrumentation.size();
6573        r = null;
6574        for (i=0; i<N; i++) {
6575            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6576            mInstrumentation.remove(a.getComponentName());
6577            if (DEBUG_REMOVE && chatty) {
6578                if (r == null) {
6579                    r = new StringBuilder(256);
6580                } else {
6581                    r.append(' ');
6582                }
6583                r.append(a.info.name);
6584            }
6585        }
6586        if (r != null) {
6587            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6588        }
6589
6590        r = null;
6591        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6592            // Only system apps can hold shared libraries.
6593            if (pkg.libraryNames != null) {
6594                for (i=0; i<pkg.libraryNames.size(); i++) {
6595                    String name = pkg.libraryNames.get(i);
6596                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6597                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6598                        mSharedLibraries.remove(name);
6599                        if (DEBUG_REMOVE && chatty) {
6600                            if (r == null) {
6601                                r = new StringBuilder(256);
6602                            } else {
6603                                r.append(' ');
6604                            }
6605                            r.append(name);
6606                        }
6607                    }
6608                }
6609            }
6610        }
6611        if (r != null) {
6612            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6613        }
6614    }
6615
6616    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6617        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6618            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6619                return true;
6620            }
6621        }
6622        return false;
6623    }
6624
6625    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6626    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6627    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6628
6629    private void updatePermissionsLPw(String changingPkg,
6630            PackageParser.Package pkgInfo, int flags) {
6631        // Make sure there are no dangling permission trees.
6632        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6633        while (it.hasNext()) {
6634            final BasePermission bp = it.next();
6635            if (bp.packageSetting == null) {
6636                // We may not yet have parsed the package, so just see if
6637                // we still know about its settings.
6638                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6639            }
6640            if (bp.packageSetting == null) {
6641                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6642                        + " from package " + bp.sourcePackage);
6643                it.remove();
6644            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6645                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6646                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6647                            + " from package " + bp.sourcePackage);
6648                    flags |= UPDATE_PERMISSIONS_ALL;
6649                    it.remove();
6650                }
6651            }
6652        }
6653
6654        // Make sure all dynamic permissions have been assigned to a package,
6655        // and make sure there are no dangling permissions.
6656        it = mSettings.mPermissions.values().iterator();
6657        while (it.hasNext()) {
6658            final BasePermission bp = it.next();
6659            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6660                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6661                        + bp.name + " pkg=" + bp.sourcePackage
6662                        + " info=" + bp.pendingInfo);
6663                if (bp.packageSetting == null && bp.pendingInfo != null) {
6664                    final BasePermission tree = findPermissionTreeLP(bp.name);
6665                    if (tree != null && tree.perm != null) {
6666                        bp.packageSetting = tree.packageSetting;
6667                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6668                                new PermissionInfo(bp.pendingInfo));
6669                        bp.perm.info.packageName = tree.perm.info.packageName;
6670                        bp.perm.info.name = bp.name;
6671                        bp.uid = tree.uid;
6672                    }
6673                }
6674            }
6675            if (bp.packageSetting == null) {
6676                // We may not yet have parsed the package, so just see if
6677                // we still know about its settings.
6678                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6679            }
6680            if (bp.packageSetting == null) {
6681                Slog.w(TAG, "Removing dangling permission: " + bp.name
6682                        + " from package " + bp.sourcePackage);
6683                it.remove();
6684            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6685                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6686                    Slog.i(TAG, "Removing old permission: " + bp.name
6687                            + " from package " + bp.sourcePackage);
6688                    flags |= UPDATE_PERMISSIONS_ALL;
6689                    it.remove();
6690                }
6691            }
6692        }
6693
6694        // Now update the permissions for all packages, in particular
6695        // replace the granted permissions of the system packages.
6696        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6697            for (PackageParser.Package pkg : mPackages.values()) {
6698                if (pkg != pkgInfo) {
6699                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6700                }
6701            }
6702        }
6703
6704        if (pkgInfo != null) {
6705            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6706        }
6707    }
6708
6709    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6710        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6711        if (ps == null) {
6712            return;
6713        }
6714        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6715        HashSet<String> origPermissions = gp.grantedPermissions;
6716        boolean changedPermission = false;
6717
6718        if (replace) {
6719            ps.permissionsFixed = false;
6720            if (gp == ps) {
6721                origPermissions = new HashSet<String>(gp.grantedPermissions);
6722                gp.grantedPermissions.clear();
6723                gp.gids = mGlobalGids;
6724            }
6725        }
6726
6727        if (gp.gids == null) {
6728            gp.gids = mGlobalGids;
6729        }
6730
6731        final int N = pkg.requestedPermissions.size();
6732        for (int i=0; i<N; i++) {
6733            final String name = pkg.requestedPermissions.get(i);
6734            final boolean required = pkg.requestedPermissionsRequired.get(i);
6735            final BasePermission bp = mSettings.mPermissions.get(name);
6736            if (DEBUG_INSTALL) {
6737                if (gp != ps) {
6738                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6739                }
6740            }
6741
6742            if (bp == null || bp.packageSetting == null) {
6743                Slog.w(TAG, "Unknown permission " + name
6744                        + " in package " + pkg.packageName);
6745                continue;
6746            }
6747
6748            final String perm = bp.name;
6749            boolean allowed;
6750            boolean allowedSig = false;
6751            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6752                // Keep track of app op permissions.
6753                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6754                if (pkgs == null) {
6755                    pkgs = new ArraySet<>();
6756                    mAppOpPermissionPackages.put(bp.name, pkgs);
6757                }
6758                pkgs.add(pkg.packageName);
6759            }
6760            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6761            if (level == PermissionInfo.PROTECTION_NORMAL
6762                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6763                // We grant a normal or dangerous permission if any of the following
6764                // are true:
6765                // 1) The permission is required
6766                // 2) The permission is optional, but was granted in the past
6767                // 3) The permission is optional, but was requested by an
6768                //    app in /system (not /data)
6769                //
6770                // Otherwise, reject the permission.
6771                allowed = (required || origPermissions.contains(perm)
6772                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6773            } else if (bp.packageSetting == null) {
6774                // This permission is invalid; skip it.
6775                allowed = false;
6776            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6777                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6778                if (allowed) {
6779                    allowedSig = true;
6780                }
6781            } else {
6782                allowed = false;
6783            }
6784            if (DEBUG_INSTALL) {
6785                if (gp != ps) {
6786                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6787                }
6788            }
6789            if (allowed) {
6790                if (!isSystemApp(ps) && ps.permissionsFixed) {
6791                    // If this is an existing, non-system package, then
6792                    // we can't add any new permissions to it.
6793                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6794                        // Except...  if this is a permission that was added
6795                        // to the platform (note: need to only do this when
6796                        // updating the platform).
6797                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6798                    }
6799                }
6800                if (allowed) {
6801                    if (!gp.grantedPermissions.contains(perm)) {
6802                        changedPermission = true;
6803                        gp.grantedPermissions.add(perm);
6804                        gp.gids = appendInts(gp.gids, bp.gids);
6805                    } else if (!ps.haveGids) {
6806                        gp.gids = appendInts(gp.gids, bp.gids);
6807                    }
6808                } else {
6809                    Slog.w(TAG, "Not granting permission " + perm
6810                            + " to package " + pkg.packageName
6811                            + " because it was previously installed without");
6812                }
6813            } else {
6814                if (gp.grantedPermissions.remove(perm)) {
6815                    changedPermission = true;
6816                    gp.gids = removeInts(gp.gids, bp.gids);
6817                    Slog.i(TAG, "Un-granting permission " + perm
6818                            + " from package " + pkg.packageName
6819                            + " (protectionLevel=" + bp.protectionLevel
6820                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6821                            + ")");
6822                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6823                    // Don't print warning for app op permissions, since it is fine for them
6824                    // not to be granted, there is a UI for the user to decide.
6825                    Slog.w(TAG, "Not granting permission " + perm
6826                            + " to package " + pkg.packageName
6827                            + " (protectionLevel=" + bp.protectionLevel
6828                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6829                            + ")");
6830                }
6831            }
6832        }
6833
6834        if ((changedPermission || replace) && !ps.permissionsFixed &&
6835                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6836            // This is the first that we have heard about this package, so the
6837            // permissions we have now selected are fixed until explicitly
6838            // changed.
6839            ps.permissionsFixed = true;
6840        }
6841        ps.haveGids = true;
6842    }
6843
6844    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6845        boolean allowed = false;
6846        final int NP = PackageParser.NEW_PERMISSIONS.length;
6847        for (int ip=0; ip<NP; ip++) {
6848            final PackageParser.NewPermissionInfo npi
6849                    = PackageParser.NEW_PERMISSIONS[ip];
6850            if (npi.name.equals(perm)
6851                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6852                allowed = true;
6853                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6854                        + pkg.packageName);
6855                break;
6856            }
6857        }
6858        return allowed;
6859    }
6860
6861    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6862                                          BasePermission bp, HashSet<String> origPermissions) {
6863        boolean allowed;
6864        allowed = (compareSignatures(
6865                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6866                        == PackageManager.SIGNATURE_MATCH)
6867                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6868                        == PackageManager.SIGNATURE_MATCH);
6869        if (!allowed && (bp.protectionLevel
6870                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6871            if (isSystemApp(pkg)) {
6872                // For updated system applications, a system permission
6873                // is granted only if it had been defined by the original application.
6874                if (isUpdatedSystemApp(pkg)) {
6875                    final PackageSetting sysPs = mSettings
6876                            .getDisabledSystemPkgLPr(pkg.packageName);
6877                    final GrantedPermissions origGp = sysPs.sharedUser != null
6878                            ? sysPs.sharedUser : sysPs;
6879
6880                    if (origGp.grantedPermissions.contains(perm)) {
6881                        // If the original was granted this permission, we take
6882                        // that grant decision as read and propagate it to the
6883                        // update.
6884                        allowed = true;
6885                    } else {
6886                        // The system apk may have been updated with an older
6887                        // version of the one on the data partition, but which
6888                        // granted a new system permission that it didn't have
6889                        // before.  In this case we do want to allow the app to
6890                        // now get the new permission if the ancestral apk is
6891                        // privileged to get it.
6892                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6893                            for (int j=0;
6894                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6895                                if (perm.equals(
6896                                        sysPs.pkg.requestedPermissions.get(j))) {
6897                                    allowed = true;
6898                                    break;
6899                                }
6900                            }
6901                        }
6902                    }
6903                } else {
6904                    allowed = isPrivilegedApp(pkg);
6905                }
6906            }
6907        }
6908        if (!allowed && (bp.protectionLevel
6909                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6910            // For development permissions, a development permission
6911            // is granted only if it was already granted.
6912            allowed = origPermissions.contains(perm);
6913        }
6914        return allowed;
6915    }
6916
6917    final class ActivityIntentResolver
6918            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6919        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6920                boolean defaultOnly, int userId) {
6921            if (!sUserManager.exists(userId)) return null;
6922            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6923            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6924        }
6925
6926        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6927                int userId) {
6928            if (!sUserManager.exists(userId)) return null;
6929            mFlags = flags;
6930            return super.queryIntent(intent, resolvedType,
6931                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6932        }
6933
6934        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6935                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6936            if (!sUserManager.exists(userId)) return null;
6937            if (packageActivities == null) {
6938                return null;
6939            }
6940            mFlags = flags;
6941            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6942            final int N = packageActivities.size();
6943            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6944                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6945
6946            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6947            for (int i = 0; i < N; ++i) {
6948                intentFilters = packageActivities.get(i).intents;
6949                if (intentFilters != null && intentFilters.size() > 0) {
6950                    PackageParser.ActivityIntentInfo[] array =
6951                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6952                    intentFilters.toArray(array);
6953                    listCut.add(array);
6954                }
6955            }
6956            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6957        }
6958
6959        public final void addActivity(PackageParser.Activity a, String type) {
6960            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6961            mActivities.put(a.getComponentName(), a);
6962            if (DEBUG_SHOW_INFO)
6963                Log.v(
6964                TAG, "  " + type + " " +
6965                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6966            if (DEBUG_SHOW_INFO)
6967                Log.v(TAG, "    Class=" + a.info.name);
6968            final int NI = a.intents.size();
6969            for (int j=0; j<NI; j++) {
6970                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6971                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6972                    intent.setPriority(0);
6973                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6974                            + a.className + " with priority > 0, forcing to 0");
6975                }
6976                if (DEBUG_SHOW_INFO) {
6977                    Log.v(TAG, "    IntentFilter:");
6978                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6979                }
6980                if (!intent.debugCheck()) {
6981                    Log.w(TAG, "==> For Activity " + a.info.name);
6982                }
6983                addFilter(intent);
6984            }
6985        }
6986
6987        public final void removeActivity(PackageParser.Activity a, String type) {
6988            mActivities.remove(a.getComponentName());
6989            if (DEBUG_SHOW_INFO) {
6990                Log.v(TAG, "  " + type + " "
6991                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6992                                : a.info.name) + ":");
6993                Log.v(TAG, "    Class=" + a.info.name);
6994            }
6995            final int NI = a.intents.size();
6996            for (int j=0; j<NI; j++) {
6997                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6998                if (DEBUG_SHOW_INFO) {
6999                    Log.v(TAG, "    IntentFilter:");
7000                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7001                }
7002                removeFilter(intent);
7003            }
7004        }
7005
7006        @Override
7007        protected boolean allowFilterResult(
7008                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7009            ActivityInfo filterAi = filter.activity.info;
7010            for (int i=dest.size()-1; i>=0; i--) {
7011                ActivityInfo destAi = dest.get(i).activityInfo;
7012                if (destAi.name == filterAi.name
7013                        && destAi.packageName == filterAi.packageName) {
7014                    return false;
7015                }
7016            }
7017            return true;
7018        }
7019
7020        @Override
7021        protected ActivityIntentInfo[] newArray(int size) {
7022            return new ActivityIntentInfo[size];
7023        }
7024
7025        @Override
7026        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7027            if (!sUserManager.exists(userId)) return true;
7028            PackageParser.Package p = filter.activity.owner;
7029            if (p != null) {
7030                PackageSetting ps = (PackageSetting)p.mExtras;
7031                if (ps != null) {
7032                    // System apps are never considered stopped for purposes of
7033                    // filtering, because there may be no way for the user to
7034                    // actually re-launch them.
7035                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7036                            && ps.getStopped(userId);
7037                }
7038            }
7039            return false;
7040        }
7041
7042        @Override
7043        protected boolean isPackageForFilter(String packageName,
7044                PackageParser.ActivityIntentInfo info) {
7045            return packageName.equals(info.activity.owner.packageName);
7046        }
7047
7048        @Override
7049        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7050                int match, int userId) {
7051            if (!sUserManager.exists(userId)) return null;
7052            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7053                return null;
7054            }
7055            final PackageParser.Activity activity = info.activity;
7056            if (mSafeMode && (activity.info.applicationInfo.flags
7057                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7058                return null;
7059            }
7060            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7061            if (ps == null) {
7062                return null;
7063            }
7064            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7065                    ps.readUserState(userId), userId);
7066            if (ai == null) {
7067                return null;
7068            }
7069            final ResolveInfo res = new ResolveInfo();
7070            res.activityInfo = ai;
7071            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7072                res.filter = info;
7073            }
7074            res.priority = info.getPriority();
7075            res.preferredOrder = activity.owner.mPreferredOrder;
7076            //System.out.println("Result: " + res.activityInfo.className +
7077            //                   " = " + res.priority);
7078            res.match = match;
7079            res.isDefault = info.hasDefault;
7080            res.labelRes = info.labelRes;
7081            res.nonLocalizedLabel = info.nonLocalizedLabel;
7082            if (userNeedsBadging(userId)) {
7083                res.noResourceId = true;
7084            } else {
7085                res.icon = info.icon;
7086            }
7087            res.system = isSystemApp(res.activityInfo.applicationInfo);
7088            return res;
7089        }
7090
7091        @Override
7092        protected void sortResults(List<ResolveInfo> results) {
7093            Collections.sort(results, mResolvePrioritySorter);
7094        }
7095
7096        @Override
7097        protected void dumpFilter(PrintWriter out, String prefix,
7098                PackageParser.ActivityIntentInfo filter) {
7099            out.print(prefix); out.print(
7100                    Integer.toHexString(System.identityHashCode(filter.activity)));
7101                    out.print(' ');
7102                    filter.activity.printComponentShortName(out);
7103                    out.print(" filter ");
7104                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7105        }
7106
7107//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7108//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7109//            final List<ResolveInfo> retList = Lists.newArrayList();
7110//            while (i.hasNext()) {
7111//                final ResolveInfo resolveInfo = i.next();
7112//                if (isEnabledLP(resolveInfo.activityInfo)) {
7113//                    retList.add(resolveInfo);
7114//                }
7115//            }
7116//            return retList;
7117//        }
7118
7119        // Keys are String (activity class name), values are Activity.
7120        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7121                = new HashMap<ComponentName, PackageParser.Activity>();
7122        private int mFlags;
7123    }
7124
7125    private final class ServiceIntentResolver
7126            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7127        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7128                boolean defaultOnly, int userId) {
7129            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7130            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7131        }
7132
7133        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7134                int userId) {
7135            if (!sUserManager.exists(userId)) return null;
7136            mFlags = flags;
7137            return super.queryIntent(intent, resolvedType,
7138                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7139        }
7140
7141        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7142                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7143            if (!sUserManager.exists(userId)) return null;
7144            if (packageServices == null) {
7145                return null;
7146            }
7147            mFlags = flags;
7148            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7149            final int N = packageServices.size();
7150            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7151                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7152
7153            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7154            for (int i = 0; i < N; ++i) {
7155                intentFilters = packageServices.get(i).intents;
7156                if (intentFilters != null && intentFilters.size() > 0) {
7157                    PackageParser.ServiceIntentInfo[] array =
7158                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7159                    intentFilters.toArray(array);
7160                    listCut.add(array);
7161                }
7162            }
7163            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7164        }
7165
7166        public final void addService(PackageParser.Service s) {
7167            mServices.put(s.getComponentName(), s);
7168            if (DEBUG_SHOW_INFO) {
7169                Log.v(TAG, "  "
7170                        + (s.info.nonLocalizedLabel != null
7171                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7172                Log.v(TAG, "    Class=" + s.info.name);
7173            }
7174            final int NI = s.intents.size();
7175            int j;
7176            for (j=0; j<NI; j++) {
7177                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7178                if (DEBUG_SHOW_INFO) {
7179                    Log.v(TAG, "    IntentFilter:");
7180                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7181                }
7182                if (!intent.debugCheck()) {
7183                    Log.w(TAG, "==> For Service " + s.info.name);
7184                }
7185                addFilter(intent);
7186            }
7187        }
7188
7189        public final void removeService(PackageParser.Service s) {
7190            mServices.remove(s.getComponentName());
7191            if (DEBUG_SHOW_INFO) {
7192                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7193                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7194                Log.v(TAG, "    Class=" + s.info.name);
7195            }
7196            final int NI = s.intents.size();
7197            int j;
7198            for (j=0; j<NI; j++) {
7199                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7200                if (DEBUG_SHOW_INFO) {
7201                    Log.v(TAG, "    IntentFilter:");
7202                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7203                }
7204                removeFilter(intent);
7205            }
7206        }
7207
7208        @Override
7209        protected boolean allowFilterResult(
7210                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7211            ServiceInfo filterSi = filter.service.info;
7212            for (int i=dest.size()-1; i>=0; i--) {
7213                ServiceInfo destAi = dest.get(i).serviceInfo;
7214                if (destAi.name == filterSi.name
7215                        && destAi.packageName == filterSi.packageName) {
7216                    return false;
7217                }
7218            }
7219            return true;
7220        }
7221
7222        @Override
7223        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7224            return new PackageParser.ServiceIntentInfo[size];
7225        }
7226
7227        @Override
7228        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7229            if (!sUserManager.exists(userId)) return true;
7230            PackageParser.Package p = filter.service.owner;
7231            if (p != null) {
7232                PackageSetting ps = (PackageSetting)p.mExtras;
7233                if (ps != null) {
7234                    // System apps are never considered stopped for purposes of
7235                    // filtering, because there may be no way for the user to
7236                    // actually re-launch them.
7237                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7238                            && ps.getStopped(userId);
7239                }
7240            }
7241            return false;
7242        }
7243
7244        @Override
7245        protected boolean isPackageForFilter(String packageName,
7246                PackageParser.ServiceIntentInfo info) {
7247            return packageName.equals(info.service.owner.packageName);
7248        }
7249
7250        @Override
7251        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7252                int match, int userId) {
7253            if (!sUserManager.exists(userId)) return null;
7254            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7255            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7256                return null;
7257            }
7258            final PackageParser.Service service = info.service;
7259            if (mSafeMode && (service.info.applicationInfo.flags
7260                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7261                return null;
7262            }
7263            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7264            if (ps == null) {
7265                return null;
7266            }
7267            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7268                    ps.readUserState(userId), userId);
7269            if (si == null) {
7270                return null;
7271            }
7272            final ResolveInfo res = new ResolveInfo();
7273            res.serviceInfo = si;
7274            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7275                res.filter = filter;
7276            }
7277            res.priority = info.getPriority();
7278            res.preferredOrder = service.owner.mPreferredOrder;
7279            //System.out.println("Result: " + res.activityInfo.className +
7280            //                   " = " + res.priority);
7281            res.match = match;
7282            res.isDefault = info.hasDefault;
7283            res.labelRes = info.labelRes;
7284            res.nonLocalizedLabel = info.nonLocalizedLabel;
7285            res.icon = info.icon;
7286            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7287            return res;
7288        }
7289
7290        @Override
7291        protected void sortResults(List<ResolveInfo> results) {
7292            Collections.sort(results, mResolvePrioritySorter);
7293        }
7294
7295        @Override
7296        protected void dumpFilter(PrintWriter out, String prefix,
7297                PackageParser.ServiceIntentInfo filter) {
7298            out.print(prefix); out.print(
7299                    Integer.toHexString(System.identityHashCode(filter.service)));
7300                    out.print(' ');
7301                    filter.service.printComponentShortName(out);
7302                    out.print(" filter ");
7303                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7304        }
7305
7306//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7307//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7308//            final List<ResolveInfo> retList = Lists.newArrayList();
7309//            while (i.hasNext()) {
7310//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7311//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7312//                    retList.add(resolveInfo);
7313//                }
7314//            }
7315//            return retList;
7316//        }
7317
7318        // Keys are String (activity class name), values are Activity.
7319        private final HashMap<ComponentName, PackageParser.Service> mServices
7320                = new HashMap<ComponentName, PackageParser.Service>();
7321        private int mFlags;
7322    };
7323
7324    private final class ProviderIntentResolver
7325            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7326        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7327                boolean defaultOnly, int userId) {
7328            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7329            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7330        }
7331
7332        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7333                int userId) {
7334            if (!sUserManager.exists(userId))
7335                return null;
7336            mFlags = flags;
7337            return super.queryIntent(intent, resolvedType,
7338                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7339        }
7340
7341        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7342                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7343            if (!sUserManager.exists(userId))
7344                return null;
7345            if (packageProviders == null) {
7346                return null;
7347            }
7348            mFlags = flags;
7349            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7350            final int N = packageProviders.size();
7351            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7352                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7353
7354            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7355            for (int i = 0; i < N; ++i) {
7356                intentFilters = packageProviders.get(i).intents;
7357                if (intentFilters != null && intentFilters.size() > 0) {
7358                    PackageParser.ProviderIntentInfo[] array =
7359                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7360                    intentFilters.toArray(array);
7361                    listCut.add(array);
7362                }
7363            }
7364            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7365        }
7366
7367        public final void addProvider(PackageParser.Provider p) {
7368            if (mProviders.containsKey(p.getComponentName())) {
7369                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7370                return;
7371            }
7372
7373            mProviders.put(p.getComponentName(), p);
7374            if (DEBUG_SHOW_INFO) {
7375                Log.v(TAG, "  "
7376                        + (p.info.nonLocalizedLabel != null
7377                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7378                Log.v(TAG, "    Class=" + p.info.name);
7379            }
7380            final int NI = p.intents.size();
7381            int j;
7382            for (j = 0; j < NI; j++) {
7383                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7384                if (DEBUG_SHOW_INFO) {
7385                    Log.v(TAG, "    IntentFilter:");
7386                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7387                }
7388                if (!intent.debugCheck()) {
7389                    Log.w(TAG, "==> For Provider " + p.info.name);
7390                }
7391                addFilter(intent);
7392            }
7393        }
7394
7395        public final void removeProvider(PackageParser.Provider p) {
7396            mProviders.remove(p.getComponentName());
7397            if (DEBUG_SHOW_INFO) {
7398                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7399                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7400                Log.v(TAG, "    Class=" + p.info.name);
7401            }
7402            final int NI = p.intents.size();
7403            int j;
7404            for (j = 0; j < NI; j++) {
7405                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7406                if (DEBUG_SHOW_INFO) {
7407                    Log.v(TAG, "    IntentFilter:");
7408                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7409                }
7410                removeFilter(intent);
7411            }
7412        }
7413
7414        @Override
7415        protected boolean allowFilterResult(
7416                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7417            ProviderInfo filterPi = filter.provider.info;
7418            for (int i = dest.size() - 1; i >= 0; i--) {
7419                ProviderInfo destPi = dest.get(i).providerInfo;
7420                if (destPi.name == filterPi.name
7421                        && destPi.packageName == filterPi.packageName) {
7422                    return false;
7423                }
7424            }
7425            return true;
7426        }
7427
7428        @Override
7429        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7430            return new PackageParser.ProviderIntentInfo[size];
7431        }
7432
7433        @Override
7434        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7435            if (!sUserManager.exists(userId))
7436                return true;
7437            PackageParser.Package p = filter.provider.owner;
7438            if (p != null) {
7439                PackageSetting ps = (PackageSetting) p.mExtras;
7440                if (ps != null) {
7441                    // System apps are never considered stopped for purposes of
7442                    // filtering, because there may be no way for the user to
7443                    // actually re-launch them.
7444                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7445                            && ps.getStopped(userId);
7446                }
7447            }
7448            return false;
7449        }
7450
7451        @Override
7452        protected boolean isPackageForFilter(String packageName,
7453                PackageParser.ProviderIntentInfo info) {
7454            return packageName.equals(info.provider.owner.packageName);
7455        }
7456
7457        @Override
7458        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7459                int match, int userId) {
7460            if (!sUserManager.exists(userId))
7461                return null;
7462            final PackageParser.ProviderIntentInfo info = filter;
7463            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7464                return null;
7465            }
7466            final PackageParser.Provider provider = info.provider;
7467            if (mSafeMode && (provider.info.applicationInfo.flags
7468                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7469                return null;
7470            }
7471            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7472            if (ps == null) {
7473                return null;
7474            }
7475            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7476                    ps.readUserState(userId), userId);
7477            if (pi == null) {
7478                return null;
7479            }
7480            final ResolveInfo res = new ResolveInfo();
7481            res.providerInfo = pi;
7482            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7483                res.filter = filter;
7484            }
7485            res.priority = info.getPriority();
7486            res.preferredOrder = provider.owner.mPreferredOrder;
7487            res.match = match;
7488            res.isDefault = info.hasDefault;
7489            res.labelRes = info.labelRes;
7490            res.nonLocalizedLabel = info.nonLocalizedLabel;
7491            res.icon = info.icon;
7492            res.system = isSystemApp(res.providerInfo.applicationInfo);
7493            return res;
7494        }
7495
7496        @Override
7497        protected void sortResults(List<ResolveInfo> results) {
7498            Collections.sort(results, mResolvePrioritySorter);
7499        }
7500
7501        @Override
7502        protected void dumpFilter(PrintWriter out, String prefix,
7503                PackageParser.ProviderIntentInfo filter) {
7504            out.print(prefix);
7505            out.print(
7506                    Integer.toHexString(System.identityHashCode(filter.provider)));
7507            out.print(' ');
7508            filter.provider.printComponentShortName(out);
7509            out.print(" filter ");
7510            out.println(Integer.toHexString(System.identityHashCode(filter)));
7511        }
7512
7513        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7514                = new HashMap<ComponentName, PackageParser.Provider>();
7515        private int mFlags;
7516    };
7517
7518    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7519            new Comparator<ResolveInfo>() {
7520        public int compare(ResolveInfo r1, ResolveInfo r2) {
7521            int v1 = r1.priority;
7522            int v2 = r2.priority;
7523            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7524            if (v1 != v2) {
7525                return (v1 > v2) ? -1 : 1;
7526            }
7527            v1 = r1.preferredOrder;
7528            v2 = r2.preferredOrder;
7529            if (v1 != v2) {
7530                return (v1 > v2) ? -1 : 1;
7531            }
7532            if (r1.isDefault != r2.isDefault) {
7533                return r1.isDefault ? -1 : 1;
7534            }
7535            v1 = r1.match;
7536            v2 = r2.match;
7537            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7538            if (v1 != v2) {
7539                return (v1 > v2) ? -1 : 1;
7540            }
7541            if (r1.system != r2.system) {
7542                return r1.system ? -1 : 1;
7543            }
7544            return 0;
7545        }
7546    };
7547
7548    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7549            new Comparator<ProviderInfo>() {
7550        public int compare(ProviderInfo p1, ProviderInfo p2) {
7551            final int v1 = p1.initOrder;
7552            final int v2 = p2.initOrder;
7553            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7554        }
7555    };
7556
7557    static final void sendPackageBroadcast(String action, String pkg,
7558            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7559            int[] userIds) {
7560        IActivityManager am = ActivityManagerNative.getDefault();
7561        if (am != null) {
7562            try {
7563                if (userIds == null) {
7564                    userIds = am.getRunningUserIds();
7565                }
7566                for (int id : userIds) {
7567                    final Intent intent = new Intent(action,
7568                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7569                    if (extras != null) {
7570                        intent.putExtras(extras);
7571                    }
7572                    if (targetPkg != null) {
7573                        intent.setPackage(targetPkg);
7574                    }
7575                    // Modify the UID when posting to other users
7576                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7577                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7578                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7579                        intent.putExtra(Intent.EXTRA_UID, uid);
7580                    }
7581                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7582                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7583                    if (DEBUG_BROADCASTS) {
7584                        RuntimeException here = new RuntimeException("here");
7585                        here.fillInStackTrace();
7586                        Slog.d(TAG, "Sending to user " + id + ": "
7587                                + intent.toShortString(false, true, false, false)
7588                                + " " + intent.getExtras(), here);
7589                    }
7590                    am.broadcastIntent(null, intent, null, finishedReceiver,
7591                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7592                            finishedReceiver != null, false, id);
7593                }
7594            } catch (RemoteException ex) {
7595            }
7596        }
7597    }
7598
7599    /**
7600     * Check if the external storage media is available. This is true if there
7601     * is a mounted external storage medium or if the external storage is
7602     * emulated.
7603     */
7604    private boolean isExternalMediaAvailable() {
7605        return mMediaMounted || Environment.isExternalStorageEmulated();
7606    }
7607
7608    @Override
7609    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7610        // writer
7611        synchronized (mPackages) {
7612            if (!isExternalMediaAvailable()) {
7613                // If the external storage is no longer mounted at this point,
7614                // the caller may not have been able to delete all of this
7615                // packages files and can not delete any more.  Bail.
7616                return null;
7617            }
7618            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7619            if (lastPackage != null) {
7620                pkgs.remove(lastPackage);
7621            }
7622            if (pkgs.size() > 0) {
7623                return pkgs.get(0);
7624            }
7625        }
7626        return null;
7627    }
7628
7629    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7630        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7631                userId, andCode ? 1 : 0, packageName);
7632        if (mSystemReady) {
7633            msg.sendToTarget();
7634        } else {
7635            if (mPostSystemReadyMessages == null) {
7636                mPostSystemReadyMessages = new ArrayList<>();
7637            }
7638            mPostSystemReadyMessages.add(msg);
7639        }
7640    }
7641
7642    void startCleaningPackages() {
7643        // reader
7644        synchronized (mPackages) {
7645            if (!isExternalMediaAvailable()) {
7646                return;
7647            }
7648            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7649                return;
7650            }
7651        }
7652        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7653        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7654        IActivityManager am = ActivityManagerNative.getDefault();
7655        if (am != null) {
7656            try {
7657                am.startService(null, intent, null, UserHandle.USER_OWNER);
7658            } catch (RemoteException e) {
7659            }
7660        }
7661    }
7662
7663    @Override
7664    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7665            int installFlags, String installerPackageName, VerificationParams verificationParams,
7666            String packageAbiOverride) {
7667        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7668                packageAbiOverride, UserHandle.getCallingUserId());
7669    }
7670
7671    @Override
7672    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7673            int installFlags, String installerPackageName, VerificationParams verificationParams,
7674            String packageAbiOverride, int userId) {
7675        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7676
7677        final int callingUid = Binder.getCallingUid();
7678        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7679
7680        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7681            try {
7682                if (observer != null) {
7683                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7684                }
7685            } catch (RemoteException re) {
7686            }
7687            return;
7688        }
7689
7690        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7691            installFlags |= PackageManager.INSTALL_FROM_ADB;
7692
7693        } else {
7694            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7695            // about installerPackageName.
7696
7697            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7698            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7699        }
7700
7701        UserHandle user;
7702        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7703            user = UserHandle.ALL;
7704        } else {
7705            user = new UserHandle(userId);
7706        }
7707
7708        verificationParams.setInstallerUid(callingUid);
7709
7710        final File originFile = new File(originPath);
7711        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7712
7713        final Message msg = mHandler.obtainMessage(INIT_COPY);
7714        msg.obj = new InstallParams(origin, observer, installFlags,
7715                installerPackageName, verificationParams, user, packageAbiOverride);
7716        mHandler.sendMessage(msg);
7717    }
7718
7719    void installStage(String packageName, File stagedDir, String stagedCid,
7720            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7721            String installerPackageName, int installerUid, UserHandle user) {
7722        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7723                params.referrerUri, installerUid, null);
7724
7725        final OriginInfo origin;
7726        if (stagedDir != null) {
7727            origin = OriginInfo.fromStagedFile(stagedDir);
7728        } else {
7729            origin = OriginInfo.fromStagedContainer(stagedCid);
7730        }
7731
7732        final Message msg = mHandler.obtainMessage(INIT_COPY);
7733        msg.obj = new InstallParams(origin, observer, params.installFlags,
7734                installerPackageName, verifParams, user, params.abiOverride);
7735        mHandler.sendMessage(msg);
7736    }
7737
7738    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7739        Bundle extras = new Bundle(1);
7740        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7741
7742        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7743                packageName, extras, null, null, new int[] {userId});
7744        try {
7745            IActivityManager am = ActivityManagerNative.getDefault();
7746            final boolean isSystem =
7747                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7748            if (isSystem && am.isUserRunning(userId, false)) {
7749                // The just-installed/enabled app is bundled on the system, so presumed
7750                // to be able to run automatically without needing an explicit launch.
7751                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7752                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7753                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7754                        .setPackage(packageName);
7755                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7756                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7757            }
7758        } catch (RemoteException e) {
7759            // shouldn't happen
7760            Slog.w(TAG, "Unable to bootstrap installed package", e);
7761        }
7762    }
7763
7764    @Override
7765    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7766            int userId) {
7767        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7768        PackageSetting pkgSetting;
7769        final int uid = Binder.getCallingUid();
7770        enforceCrossUserPermission(uid, userId, true, true,
7771                "setApplicationHiddenSetting for user " + userId);
7772
7773        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7774            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7775            return false;
7776        }
7777
7778        long callingId = Binder.clearCallingIdentity();
7779        try {
7780            boolean sendAdded = false;
7781            boolean sendRemoved = false;
7782            // writer
7783            synchronized (mPackages) {
7784                pkgSetting = mSettings.mPackages.get(packageName);
7785                if (pkgSetting == null) {
7786                    return false;
7787                }
7788                if (pkgSetting.getHidden(userId) != hidden) {
7789                    pkgSetting.setHidden(hidden, userId);
7790                    mSettings.writePackageRestrictionsLPr(userId);
7791                    if (hidden) {
7792                        sendRemoved = true;
7793                    } else {
7794                        sendAdded = true;
7795                    }
7796                }
7797            }
7798            if (sendAdded) {
7799                sendPackageAddedForUser(packageName, pkgSetting, userId);
7800                return true;
7801            }
7802            if (sendRemoved) {
7803                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7804                        "hiding pkg");
7805                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7806            }
7807        } finally {
7808            Binder.restoreCallingIdentity(callingId);
7809        }
7810        return false;
7811    }
7812
7813    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7814            int userId) {
7815        final PackageRemovedInfo info = new PackageRemovedInfo();
7816        info.removedPackage = packageName;
7817        info.removedUsers = new int[] {userId};
7818        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7819        info.sendBroadcast(false, false, false);
7820    }
7821
7822    /**
7823     * Returns true if application is not found or there was an error. Otherwise it returns
7824     * the hidden state of the package for the given user.
7825     */
7826    @Override
7827    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7828        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7829        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7830                false, "getApplicationHidden for user " + userId);
7831        PackageSetting pkgSetting;
7832        long callingId = Binder.clearCallingIdentity();
7833        try {
7834            // writer
7835            synchronized (mPackages) {
7836                pkgSetting = mSettings.mPackages.get(packageName);
7837                if (pkgSetting == null) {
7838                    return true;
7839                }
7840                return pkgSetting.getHidden(userId);
7841            }
7842        } finally {
7843            Binder.restoreCallingIdentity(callingId);
7844        }
7845    }
7846
7847    /**
7848     * @hide
7849     */
7850    @Override
7851    public int installExistingPackageAsUser(String packageName, int userId) {
7852        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7853                null);
7854        PackageSetting pkgSetting;
7855        final int uid = Binder.getCallingUid();
7856        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7857                + userId);
7858        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7859            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7860        }
7861
7862        long callingId = Binder.clearCallingIdentity();
7863        try {
7864            boolean sendAdded = false;
7865            Bundle extras = new Bundle(1);
7866
7867            // writer
7868            synchronized (mPackages) {
7869                pkgSetting = mSettings.mPackages.get(packageName);
7870                if (pkgSetting == null) {
7871                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7872                }
7873                if (!pkgSetting.getInstalled(userId)) {
7874                    pkgSetting.setInstalled(true, userId);
7875                    pkgSetting.setHidden(false, userId);
7876                    mSettings.writePackageRestrictionsLPr(userId);
7877                    sendAdded = true;
7878                }
7879            }
7880
7881            if (sendAdded) {
7882                sendPackageAddedForUser(packageName, pkgSetting, userId);
7883            }
7884        } finally {
7885            Binder.restoreCallingIdentity(callingId);
7886        }
7887
7888        return PackageManager.INSTALL_SUCCEEDED;
7889    }
7890
7891    boolean isUserRestricted(int userId, String restrictionKey) {
7892        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7893        if (restrictions.getBoolean(restrictionKey, false)) {
7894            Log.w(TAG, "User is restricted: " + restrictionKey);
7895            return true;
7896        }
7897        return false;
7898    }
7899
7900    @Override
7901    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7902        mContext.enforceCallingOrSelfPermission(
7903                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7904                "Only package verification agents can verify applications");
7905
7906        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7907        final PackageVerificationResponse response = new PackageVerificationResponse(
7908                verificationCode, Binder.getCallingUid());
7909        msg.arg1 = id;
7910        msg.obj = response;
7911        mHandler.sendMessage(msg);
7912    }
7913
7914    @Override
7915    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7916            long millisecondsToDelay) {
7917        mContext.enforceCallingOrSelfPermission(
7918                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7919                "Only package verification agents can extend verification timeouts");
7920
7921        final PackageVerificationState state = mPendingVerification.get(id);
7922        final PackageVerificationResponse response = new PackageVerificationResponse(
7923                verificationCodeAtTimeout, Binder.getCallingUid());
7924
7925        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7926            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7927        }
7928        if (millisecondsToDelay < 0) {
7929            millisecondsToDelay = 0;
7930        }
7931        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7932                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7933            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7934        }
7935
7936        if ((state != null) && !state.timeoutExtended()) {
7937            state.extendTimeout();
7938
7939            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7940            msg.arg1 = id;
7941            msg.obj = response;
7942            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7943        }
7944    }
7945
7946    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7947            int verificationCode, UserHandle user) {
7948        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7949        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7950        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7951        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7952        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7953
7954        mContext.sendBroadcastAsUser(intent, user,
7955                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7956    }
7957
7958    private ComponentName matchComponentForVerifier(String packageName,
7959            List<ResolveInfo> receivers) {
7960        ActivityInfo targetReceiver = null;
7961
7962        final int NR = receivers.size();
7963        for (int i = 0; i < NR; i++) {
7964            final ResolveInfo info = receivers.get(i);
7965            if (info.activityInfo == null) {
7966                continue;
7967            }
7968
7969            if (packageName.equals(info.activityInfo.packageName)) {
7970                targetReceiver = info.activityInfo;
7971                break;
7972            }
7973        }
7974
7975        if (targetReceiver == null) {
7976            return null;
7977        }
7978
7979        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7980    }
7981
7982    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7983            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7984        if (pkgInfo.verifiers.length == 0) {
7985            return null;
7986        }
7987
7988        final int N = pkgInfo.verifiers.length;
7989        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7990        for (int i = 0; i < N; i++) {
7991            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7992
7993            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7994                    receivers);
7995            if (comp == null) {
7996                continue;
7997            }
7998
7999            final int verifierUid = getUidForVerifier(verifierInfo);
8000            if (verifierUid == -1) {
8001                continue;
8002            }
8003
8004            if (DEBUG_VERIFY) {
8005                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8006                        + " with the correct signature");
8007            }
8008            sufficientVerifiers.add(comp);
8009            verificationState.addSufficientVerifier(verifierUid);
8010        }
8011
8012        return sufficientVerifiers;
8013    }
8014
8015    private int getUidForVerifier(VerifierInfo verifierInfo) {
8016        synchronized (mPackages) {
8017            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8018            if (pkg == null) {
8019                return -1;
8020            } else if (pkg.mSignatures.length != 1) {
8021                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8022                        + " has more than one signature; ignoring");
8023                return -1;
8024            }
8025
8026            /*
8027             * If the public key of the package's signature does not match
8028             * our expected public key, then this is a different package and
8029             * we should skip.
8030             */
8031
8032            final byte[] expectedPublicKey;
8033            try {
8034                final Signature verifierSig = pkg.mSignatures[0];
8035                final PublicKey publicKey = verifierSig.getPublicKey();
8036                expectedPublicKey = publicKey.getEncoded();
8037            } catch (CertificateException e) {
8038                return -1;
8039            }
8040
8041            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8042
8043            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8044                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8045                        + " does not have the expected public key; ignoring");
8046                return -1;
8047            }
8048
8049            return pkg.applicationInfo.uid;
8050        }
8051    }
8052
8053    @Override
8054    public void finishPackageInstall(int token) {
8055        enforceSystemOrRoot("Only the system is allowed to finish installs");
8056
8057        if (DEBUG_INSTALL) {
8058            Slog.v(TAG, "BM finishing package install for " + token);
8059        }
8060
8061        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8062        mHandler.sendMessage(msg);
8063    }
8064
8065    /**
8066     * Get the verification agent timeout.
8067     *
8068     * @return verification timeout in milliseconds
8069     */
8070    private long getVerificationTimeout() {
8071        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8072                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8073                DEFAULT_VERIFICATION_TIMEOUT);
8074    }
8075
8076    /**
8077     * Get the default verification agent response code.
8078     *
8079     * @return default verification response code
8080     */
8081    private int getDefaultVerificationResponse() {
8082        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8083                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8084                DEFAULT_VERIFICATION_RESPONSE);
8085    }
8086
8087    /**
8088     * Check whether or not package verification has been enabled.
8089     *
8090     * @return true if verification should be performed
8091     */
8092    private boolean isVerificationEnabled(int userId, int installFlags) {
8093        if (!DEFAULT_VERIFY_ENABLE) {
8094            return false;
8095        }
8096
8097        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8098
8099        // Check if installing from ADB
8100        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8101            // Do not run verification in a test harness environment
8102            if (ActivityManager.isRunningInTestHarness()) {
8103                return false;
8104            }
8105            if (ensureVerifyAppsEnabled) {
8106                return true;
8107            }
8108            // Check if the developer does not want package verification for ADB installs
8109            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8110                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8111                return false;
8112            }
8113        }
8114
8115        if (ensureVerifyAppsEnabled) {
8116            return true;
8117        }
8118
8119        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8120                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8121    }
8122
8123    /**
8124     * Get the "allow unknown sources" setting.
8125     *
8126     * @return the current "allow unknown sources" setting
8127     */
8128    private int getUnknownSourcesSettings() {
8129        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8130                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8131                -1);
8132    }
8133
8134    @Override
8135    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8136        final int uid = Binder.getCallingUid();
8137        // writer
8138        synchronized (mPackages) {
8139            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8140            if (targetPackageSetting == null) {
8141                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8142            }
8143
8144            PackageSetting installerPackageSetting;
8145            if (installerPackageName != null) {
8146                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8147                if (installerPackageSetting == null) {
8148                    throw new IllegalArgumentException("Unknown installer package: "
8149                            + installerPackageName);
8150                }
8151            } else {
8152                installerPackageSetting = null;
8153            }
8154
8155            Signature[] callerSignature;
8156            Object obj = mSettings.getUserIdLPr(uid);
8157            if (obj != null) {
8158                if (obj instanceof SharedUserSetting) {
8159                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8160                } else if (obj instanceof PackageSetting) {
8161                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8162                } else {
8163                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8164                }
8165            } else {
8166                throw new SecurityException("Unknown calling uid " + uid);
8167            }
8168
8169            // Verify: can't set installerPackageName to a package that is
8170            // not signed with the same cert as the caller.
8171            if (installerPackageSetting != null) {
8172                if (compareSignatures(callerSignature,
8173                        installerPackageSetting.signatures.mSignatures)
8174                        != PackageManager.SIGNATURE_MATCH) {
8175                    throw new SecurityException(
8176                            "Caller does not have same cert as new installer package "
8177                            + installerPackageName);
8178                }
8179            }
8180
8181            // Verify: if target already has an installer package, it must
8182            // be signed with the same cert as the caller.
8183            if (targetPackageSetting.installerPackageName != null) {
8184                PackageSetting setting = mSettings.mPackages.get(
8185                        targetPackageSetting.installerPackageName);
8186                // If the currently set package isn't valid, then it's always
8187                // okay to change it.
8188                if (setting != null) {
8189                    if (compareSignatures(callerSignature,
8190                            setting.signatures.mSignatures)
8191                            != PackageManager.SIGNATURE_MATCH) {
8192                        throw new SecurityException(
8193                                "Caller does not have same cert as old installer package "
8194                                + targetPackageSetting.installerPackageName);
8195                    }
8196                }
8197            }
8198
8199            // Okay!
8200            targetPackageSetting.installerPackageName = installerPackageName;
8201            scheduleWriteSettingsLocked();
8202        }
8203    }
8204
8205    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8206        // Queue up an async operation since the package installation may take a little while.
8207        mHandler.post(new Runnable() {
8208            public void run() {
8209                mHandler.removeCallbacks(this);
8210                 // Result object to be returned
8211                PackageInstalledInfo res = new PackageInstalledInfo();
8212                res.returnCode = currentStatus;
8213                res.uid = -1;
8214                res.pkg = null;
8215                res.removedInfo = new PackageRemovedInfo();
8216                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8217                    args.doPreInstall(res.returnCode);
8218                    synchronized (mInstallLock) {
8219                        installPackageLI(args, res);
8220                    }
8221                    args.doPostInstall(res.returnCode, res.uid);
8222                }
8223
8224                // A restore should be performed at this point if (a) the install
8225                // succeeded, (b) the operation is not an update, and (c) the new
8226                // package has not opted out of backup participation.
8227                final boolean update = res.removedInfo.removedPackage != null;
8228                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8229                boolean doRestore = !update
8230                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8231
8232                // Set up the post-install work request bookkeeping.  This will be used
8233                // and cleaned up by the post-install event handling regardless of whether
8234                // there's a restore pass performed.  Token values are >= 1.
8235                int token;
8236                if (mNextInstallToken < 0) mNextInstallToken = 1;
8237                token = mNextInstallToken++;
8238
8239                PostInstallData data = new PostInstallData(args, res);
8240                mRunningInstalls.put(token, data);
8241                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8242
8243                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8244                    // Pass responsibility to the Backup Manager.  It will perform a
8245                    // restore if appropriate, then pass responsibility back to the
8246                    // Package Manager to run the post-install observer callbacks
8247                    // and broadcasts.
8248                    IBackupManager bm = IBackupManager.Stub.asInterface(
8249                            ServiceManager.getService(Context.BACKUP_SERVICE));
8250                    if (bm != null) {
8251                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8252                                + " to BM for possible restore");
8253                        try {
8254                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8255                        } catch (RemoteException e) {
8256                            // can't happen; the backup manager is local
8257                        } catch (Exception e) {
8258                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8259                            doRestore = false;
8260                        }
8261                    } else {
8262                        Slog.e(TAG, "Backup Manager not found!");
8263                        doRestore = false;
8264                    }
8265                }
8266
8267                if (!doRestore) {
8268                    // No restore possible, or the Backup Manager was mysteriously not
8269                    // available -- just fire the post-install work request directly.
8270                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8271                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8272                    mHandler.sendMessage(msg);
8273                }
8274            }
8275        });
8276    }
8277
8278    private abstract class HandlerParams {
8279        private static final int MAX_RETRIES = 4;
8280
8281        /**
8282         * Number of times startCopy() has been attempted and had a non-fatal
8283         * error.
8284         */
8285        private int mRetries = 0;
8286
8287        /** User handle for the user requesting the information or installation. */
8288        private final UserHandle mUser;
8289
8290        HandlerParams(UserHandle user) {
8291            mUser = user;
8292        }
8293
8294        UserHandle getUser() {
8295            return mUser;
8296        }
8297
8298        final boolean startCopy() {
8299            boolean res;
8300            try {
8301                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8302
8303                if (++mRetries > MAX_RETRIES) {
8304                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8305                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8306                    handleServiceError();
8307                    return false;
8308                } else {
8309                    handleStartCopy();
8310                    res = true;
8311                }
8312            } catch (RemoteException e) {
8313                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8314                mHandler.sendEmptyMessage(MCS_RECONNECT);
8315                res = false;
8316            }
8317            handleReturnCode();
8318            return res;
8319        }
8320
8321        final void serviceError() {
8322            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8323            handleServiceError();
8324            handleReturnCode();
8325        }
8326
8327        abstract void handleStartCopy() throws RemoteException;
8328        abstract void handleServiceError();
8329        abstract void handleReturnCode();
8330    }
8331
8332    class MeasureParams extends HandlerParams {
8333        private final PackageStats mStats;
8334        private boolean mSuccess;
8335
8336        private final IPackageStatsObserver mObserver;
8337
8338        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8339            super(new UserHandle(stats.userHandle));
8340            mObserver = observer;
8341            mStats = stats;
8342        }
8343
8344        @Override
8345        public String toString() {
8346            return "MeasureParams{"
8347                + Integer.toHexString(System.identityHashCode(this))
8348                + " " + mStats.packageName + "}";
8349        }
8350
8351        @Override
8352        void handleStartCopy() throws RemoteException {
8353            synchronized (mInstallLock) {
8354                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8355            }
8356
8357            if (mSuccess) {
8358                final boolean mounted;
8359                if (Environment.isExternalStorageEmulated()) {
8360                    mounted = true;
8361                } else {
8362                    final String status = Environment.getExternalStorageState();
8363                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8364                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8365                }
8366
8367                if (mounted) {
8368                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8369
8370                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8371                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8372
8373                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8374                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8375
8376                    // Always subtract cache size, since it's a subdirectory
8377                    mStats.externalDataSize -= mStats.externalCacheSize;
8378
8379                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8380                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8381
8382                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8383                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8384                }
8385            }
8386        }
8387
8388        @Override
8389        void handleReturnCode() {
8390            if (mObserver != null) {
8391                try {
8392                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8393                } catch (RemoteException e) {
8394                    Slog.i(TAG, "Observer no longer exists.");
8395                }
8396            }
8397        }
8398
8399        @Override
8400        void handleServiceError() {
8401            Slog.e(TAG, "Could not measure application " + mStats.packageName
8402                            + " external storage");
8403        }
8404    }
8405
8406    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8407            throws RemoteException {
8408        long result = 0;
8409        for (File path : paths) {
8410            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8411        }
8412        return result;
8413    }
8414
8415    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8416        for (File path : paths) {
8417            try {
8418                mcs.clearDirectory(path.getAbsolutePath());
8419            } catch (RemoteException e) {
8420            }
8421        }
8422    }
8423
8424    static class OriginInfo {
8425        /**
8426         * Location where install is coming from, before it has been
8427         * copied/renamed into place. This could be a single monolithic APK
8428         * file, or a cluster directory. This location may be untrusted.
8429         */
8430        final File file;
8431        final String cid;
8432
8433        /**
8434         * Flag indicating that {@link #file} or {@link #cid} has already been
8435         * staged, meaning downstream users don't need to defensively copy the
8436         * contents.
8437         */
8438        final boolean staged;
8439
8440        /**
8441         * Flag indicating that {@link #file} or {@link #cid} is an already
8442         * installed app that is being moved.
8443         */
8444        final boolean existing;
8445
8446        final String resolvedPath;
8447        final File resolvedFile;
8448
8449        static OriginInfo fromNothing() {
8450            return new OriginInfo(null, null, false, false);
8451        }
8452
8453        static OriginInfo fromUntrustedFile(File file) {
8454            return new OriginInfo(file, null, false, false);
8455        }
8456
8457        static OriginInfo fromExistingFile(File file) {
8458            return new OriginInfo(file, null, false, true);
8459        }
8460
8461        static OriginInfo fromStagedFile(File file) {
8462            return new OriginInfo(file, null, true, false);
8463        }
8464
8465        static OriginInfo fromStagedContainer(String cid) {
8466            return new OriginInfo(null, cid, true, false);
8467        }
8468
8469        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8470            this.file = file;
8471            this.cid = cid;
8472            this.staged = staged;
8473            this.existing = existing;
8474
8475            if (cid != null) {
8476                resolvedPath = PackageHelper.getSdDir(cid);
8477                resolvedFile = new File(resolvedPath);
8478            } else if (file != null) {
8479                resolvedPath = file.getAbsolutePath();
8480                resolvedFile = file;
8481            } else {
8482                resolvedPath = null;
8483                resolvedFile = null;
8484            }
8485        }
8486    }
8487
8488    class InstallParams extends HandlerParams {
8489        final OriginInfo origin;
8490        final IPackageInstallObserver2 observer;
8491        int installFlags;
8492        final String installerPackageName;
8493        final VerificationParams verificationParams;
8494        private InstallArgs mArgs;
8495        private int mRet;
8496        final String packageAbiOverride;
8497
8498        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8499                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8500                String packageAbiOverride) {
8501            super(user);
8502            this.origin = origin;
8503            this.observer = observer;
8504            this.installFlags = installFlags;
8505            this.installerPackageName = installerPackageName;
8506            this.verificationParams = verificationParams;
8507            this.packageAbiOverride = packageAbiOverride;
8508        }
8509
8510        @Override
8511        public String toString() {
8512            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8513                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8514        }
8515
8516        public ManifestDigest getManifestDigest() {
8517            if (verificationParams == null) {
8518                return null;
8519            }
8520            return verificationParams.getManifestDigest();
8521        }
8522
8523        private int installLocationPolicy(PackageInfoLite pkgLite) {
8524            String packageName = pkgLite.packageName;
8525            int installLocation = pkgLite.installLocation;
8526            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8527            // reader
8528            synchronized (mPackages) {
8529                PackageParser.Package pkg = mPackages.get(packageName);
8530                if (pkg != null) {
8531                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8532                        // Check for downgrading.
8533                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8534                            if (pkgLite.versionCode < pkg.mVersionCode) {
8535                                Slog.w(TAG, "Can't install update of " + packageName
8536                                        + " update version " + pkgLite.versionCode
8537                                        + " is older than installed version "
8538                                        + pkg.mVersionCode);
8539                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8540                            }
8541                        }
8542                        // Check for updated system application.
8543                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8544                            if (onSd) {
8545                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8546                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8547                            }
8548                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8549                        } else {
8550                            if (onSd) {
8551                                // Install flag overrides everything.
8552                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8553                            }
8554                            // If current upgrade specifies particular preference
8555                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8556                                // Application explicitly specified internal.
8557                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8558                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8559                                // App explictly prefers external. Let policy decide
8560                            } else {
8561                                // Prefer previous location
8562                                if (isExternal(pkg)) {
8563                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8564                                }
8565                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8566                            }
8567                        }
8568                    } else {
8569                        // Invalid install. Return error code
8570                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8571                    }
8572                }
8573            }
8574            // All the special cases have been taken care of.
8575            // Return result based on recommended install location.
8576            if (onSd) {
8577                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8578            }
8579            return pkgLite.recommendedInstallLocation;
8580        }
8581
8582        /*
8583         * Invoke remote method to get package information and install
8584         * location values. Override install location based on default
8585         * policy if needed and then create install arguments based
8586         * on the install location.
8587         */
8588        public void handleStartCopy() throws RemoteException {
8589            int ret = PackageManager.INSTALL_SUCCEEDED;
8590
8591            // If we're already staged, we've firmly committed to an install location
8592            if (origin.staged) {
8593                if (origin.file != null) {
8594                    installFlags |= PackageManager.INSTALL_INTERNAL;
8595                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8596                } else if (origin.cid != null) {
8597                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8598                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8599                } else {
8600                    throw new IllegalStateException("Invalid stage location");
8601                }
8602            }
8603
8604            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8605            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8606
8607            PackageInfoLite pkgLite = null;
8608
8609            if (onInt && onSd) {
8610                // Check if both bits are set.
8611                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8612                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8613            } else {
8614                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8615                        packageAbiOverride);
8616
8617                /*
8618                 * If we have too little free space, try to free cache
8619                 * before giving up.
8620                 */
8621                if (!origin.staged && pkgLite.recommendedInstallLocation
8622                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8623                    // TODO: focus freeing disk space on the target device
8624                    final StorageManager storage = StorageManager.from(mContext);
8625                    final long lowThreshold = storage.getStorageLowBytes(
8626                            Environment.getDataDirectory());
8627
8628                    final long sizeBytes = mContainerService.calculateInstalledSize(
8629                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8630
8631                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8632                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8633                                installFlags, packageAbiOverride);
8634                    }
8635
8636                    /*
8637                     * The cache free must have deleted the file we
8638                     * downloaded to install.
8639                     *
8640                     * TODO: fix the "freeCache" call to not delete
8641                     *       the file we care about.
8642                     */
8643                    if (pkgLite.recommendedInstallLocation
8644                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8645                        pkgLite.recommendedInstallLocation
8646                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8647                    }
8648                }
8649            }
8650
8651            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8652                int loc = pkgLite.recommendedInstallLocation;
8653                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8654                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8655                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8656                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8657                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8658                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8659                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8660                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8661                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8662                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8663                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8664                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8665                } else {
8666                    // Override with defaults if needed.
8667                    loc = installLocationPolicy(pkgLite);
8668                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8669                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8670                    } else if (!onSd && !onInt) {
8671                        // Override install location with flags
8672                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8673                            // Set the flag to install on external media.
8674                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8675                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8676                        } else {
8677                            // Make sure the flag for installing on external
8678                            // media is unset
8679                            installFlags |= PackageManager.INSTALL_INTERNAL;
8680                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8681                        }
8682                    }
8683                }
8684            }
8685
8686            final InstallArgs args = createInstallArgs(this);
8687            mArgs = args;
8688
8689            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8690                 /*
8691                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8692                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8693                 */
8694                int userIdentifier = getUser().getIdentifier();
8695                if (userIdentifier == UserHandle.USER_ALL
8696                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8697                    userIdentifier = UserHandle.USER_OWNER;
8698                }
8699
8700                /*
8701                 * Determine if we have any installed package verifiers. If we
8702                 * do, then we'll defer to them to verify the packages.
8703                 */
8704                final int requiredUid = mRequiredVerifierPackage == null ? -1
8705                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8706                if (!origin.existing && requiredUid != -1
8707                        && isVerificationEnabled(userIdentifier, installFlags)) {
8708                    final Intent verification = new Intent(
8709                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8710                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8711                            PACKAGE_MIME_TYPE);
8712                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8713
8714                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8715                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8716                            0 /* TODO: Which userId? */);
8717
8718                    if (DEBUG_VERIFY) {
8719                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8720                                + verification.toString() + " with " + pkgLite.verifiers.length
8721                                + " optional verifiers");
8722                    }
8723
8724                    final int verificationId = mPendingVerificationToken++;
8725
8726                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8727
8728                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8729                            installerPackageName);
8730
8731                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8732                            installFlags);
8733
8734                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8735                            pkgLite.packageName);
8736
8737                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8738                            pkgLite.versionCode);
8739
8740                    if (verificationParams != null) {
8741                        if (verificationParams.getVerificationURI() != null) {
8742                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8743                                 verificationParams.getVerificationURI());
8744                        }
8745                        if (verificationParams.getOriginatingURI() != null) {
8746                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8747                                  verificationParams.getOriginatingURI());
8748                        }
8749                        if (verificationParams.getReferrer() != null) {
8750                            verification.putExtra(Intent.EXTRA_REFERRER,
8751                                  verificationParams.getReferrer());
8752                        }
8753                        if (verificationParams.getOriginatingUid() >= 0) {
8754                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8755                                  verificationParams.getOriginatingUid());
8756                        }
8757                        if (verificationParams.getInstallerUid() >= 0) {
8758                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8759                                  verificationParams.getInstallerUid());
8760                        }
8761                    }
8762
8763                    final PackageVerificationState verificationState = new PackageVerificationState(
8764                            requiredUid, args);
8765
8766                    mPendingVerification.append(verificationId, verificationState);
8767
8768                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8769                            receivers, verificationState);
8770
8771                    /*
8772                     * If any sufficient verifiers were listed in the package
8773                     * manifest, attempt to ask them.
8774                     */
8775                    if (sufficientVerifiers != null) {
8776                        final int N = sufficientVerifiers.size();
8777                        if (N == 0) {
8778                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8779                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8780                        } else {
8781                            for (int i = 0; i < N; i++) {
8782                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8783
8784                                final Intent sufficientIntent = new Intent(verification);
8785                                sufficientIntent.setComponent(verifierComponent);
8786
8787                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8788                            }
8789                        }
8790                    }
8791
8792                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8793                            mRequiredVerifierPackage, receivers);
8794                    if (ret == PackageManager.INSTALL_SUCCEEDED
8795                            && mRequiredVerifierPackage != null) {
8796                        /*
8797                         * Send the intent to the required verification agent,
8798                         * but only start the verification timeout after the
8799                         * target BroadcastReceivers have run.
8800                         */
8801                        verification.setComponent(requiredVerifierComponent);
8802                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8803                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8804                                new BroadcastReceiver() {
8805                                    @Override
8806                                    public void onReceive(Context context, Intent intent) {
8807                                        final Message msg = mHandler
8808                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8809                                        msg.arg1 = verificationId;
8810                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8811                                    }
8812                                }, null, 0, null, null);
8813
8814                        /*
8815                         * We don't want the copy to proceed until verification
8816                         * succeeds, so null out this field.
8817                         */
8818                        mArgs = null;
8819                    }
8820                } else {
8821                    /*
8822                     * No package verification is enabled, so immediately start
8823                     * the remote call to initiate copy using temporary file.
8824                     */
8825                    ret = args.copyApk(mContainerService, true);
8826                }
8827            }
8828
8829            mRet = ret;
8830        }
8831
8832        @Override
8833        void handleReturnCode() {
8834            // If mArgs is null, then MCS couldn't be reached. When it
8835            // reconnects, it will try again to install. At that point, this
8836            // will succeed.
8837            if (mArgs != null) {
8838                processPendingInstall(mArgs, mRet);
8839            }
8840        }
8841
8842        @Override
8843        void handleServiceError() {
8844            mArgs = createInstallArgs(this);
8845            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8846        }
8847
8848        public boolean isForwardLocked() {
8849            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8850        }
8851    }
8852
8853    /**
8854     * Used during creation of InstallArgs
8855     *
8856     * @param installFlags package installation flags
8857     * @return true if should be installed on external storage
8858     */
8859    private static boolean installOnSd(int installFlags) {
8860        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8861            return false;
8862        }
8863        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8864            return true;
8865        }
8866        return false;
8867    }
8868
8869    /**
8870     * Used during creation of InstallArgs
8871     *
8872     * @param installFlags package installation flags
8873     * @return true if should be installed as forward locked
8874     */
8875    private static boolean installForwardLocked(int installFlags) {
8876        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8877    }
8878
8879    private InstallArgs createInstallArgs(InstallParams params) {
8880        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8881            return new AsecInstallArgs(params);
8882        } else {
8883            return new FileInstallArgs(params);
8884        }
8885    }
8886
8887    /**
8888     * Create args that describe an existing installed package. Typically used
8889     * when cleaning up old installs, or used as a move source.
8890     */
8891    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8892            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8893        final boolean isInAsec;
8894        if (installOnSd(installFlags)) {
8895            /* Apps on SD card are always in ASEC containers. */
8896            isInAsec = true;
8897        } else if (installForwardLocked(installFlags)
8898                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8899            /*
8900             * Forward-locked apps are only in ASEC containers if they're the
8901             * new style
8902             */
8903            isInAsec = true;
8904        } else {
8905            isInAsec = false;
8906        }
8907
8908        if (isInAsec) {
8909            return new AsecInstallArgs(codePath, instructionSets,
8910                    installOnSd(installFlags), installForwardLocked(installFlags));
8911        } else {
8912            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8913                    instructionSets);
8914        }
8915    }
8916
8917    static abstract class InstallArgs {
8918        /** @see InstallParams#origin */
8919        final OriginInfo origin;
8920
8921        final IPackageInstallObserver2 observer;
8922        // Always refers to PackageManager flags only
8923        final int installFlags;
8924        final String installerPackageName;
8925        final ManifestDigest manifestDigest;
8926        final UserHandle user;
8927        final String abiOverride;
8928
8929        // The list of instruction sets supported by this app. This is currently
8930        // only used during the rmdex() phase to clean up resources. We can get rid of this
8931        // if we move dex files under the common app path.
8932        /* nullable */ String[] instructionSets;
8933
8934        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8935                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8936                String[] instructionSets, String abiOverride) {
8937            this.origin = origin;
8938            this.installFlags = installFlags;
8939            this.observer = observer;
8940            this.installerPackageName = installerPackageName;
8941            this.manifestDigest = manifestDigest;
8942            this.user = user;
8943            this.instructionSets = instructionSets;
8944            this.abiOverride = abiOverride;
8945        }
8946
8947        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8948        abstract int doPreInstall(int status);
8949
8950        /**
8951         * Rename package into final resting place. All paths on the given
8952         * scanned package should be updated to reflect the rename.
8953         */
8954        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8955        abstract int doPostInstall(int status, int uid);
8956
8957        /** @see PackageSettingBase#codePathString */
8958        abstract String getCodePath();
8959        /** @see PackageSettingBase#resourcePathString */
8960        abstract String getResourcePath();
8961        abstract String getLegacyNativeLibraryPath();
8962
8963        // Need installer lock especially for dex file removal.
8964        abstract void cleanUpResourcesLI();
8965        abstract boolean doPostDeleteLI(boolean delete);
8966        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8967
8968        /**
8969         * Called before the source arguments are copied. This is used mostly
8970         * for MoveParams when it needs to read the source file to put it in the
8971         * destination.
8972         */
8973        int doPreCopy() {
8974            return PackageManager.INSTALL_SUCCEEDED;
8975        }
8976
8977        /**
8978         * Called after the source arguments are copied. This is used mostly for
8979         * MoveParams when it needs to read the source file to put it in the
8980         * destination.
8981         *
8982         * @return
8983         */
8984        int doPostCopy(int uid) {
8985            return PackageManager.INSTALL_SUCCEEDED;
8986        }
8987
8988        protected boolean isFwdLocked() {
8989            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8990        }
8991
8992        protected boolean isExternal() {
8993            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8994        }
8995
8996        UserHandle getUser() {
8997            return user;
8998        }
8999    }
9000
9001    /**
9002     * Logic to handle installation of non-ASEC applications, including copying
9003     * and renaming logic.
9004     */
9005    class FileInstallArgs extends InstallArgs {
9006        private File codeFile;
9007        private File resourceFile;
9008        private File legacyNativeLibraryPath;
9009
9010        // Example topology:
9011        // /data/app/com.example/base.apk
9012        // /data/app/com.example/split_foo.apk
9013        // /data/app/com.example/lib/arm/libfoo.so
9014        // /data/app/com.example/lib/arm64/libfoo.so
9015        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9016
9017        /** New install */
9018        FileInstallArgs(InstallParams params) {
9019            super(params.origin, params.observer, params.installFlags,
9020                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9021                    null /* instruction sets */, params.packageAbiOverride);
9022            if (isFwdLocked()) {
9023                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9024            }
9025        }
9026
9027        /** Existing install */
9028        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9029                String[] instructionSets) {
9030            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9031            this.codeFile = (codePath != null) ? new File(codePath) : null;
9032            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9033            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9034                    new File(legacyNativeLibraryPath) : null;
9035        }
9036
9037        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9038            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9039                    isFwdLocked(), abiOverride);
9040
9041            final StorageManager storage = StorageManager.from(mContext);
9042            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9043        }
9044
9045        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9046            if (origin.staged) {
9047                Slog.d(TAG, origin.file + " already staged; skipping copy");
9048                codeFile = origin.file;
9049                resourceFile = origin.file;
9050                return PackageManager.INSTALL_SUCCEEDED;
9051            }
9052
9053            try {
9054                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9055                codeFile = tempDir;
9056                resourceFile = tempDir;
9057            } catch (IOException e) {
9058                Slog.w(TAG, "Failed to create copy file: " + e);
9059                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9060            }
9061
9062            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9063                @Override
9064                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9065                    if (!FileUtils.isValidExtFilename(name)) {
9066                        throw new IllegalArgumentException("Invalid filename: " + name);
9067                    }
9068                    try {
9069                        final File file = new File(codeFile, name);
9070                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9071                                O_RDWR | O_CREAT, 0644);
9072                        Os.chmod(file.getAbsolutePath(), 0644);
9073                        return new ParcelFileDescriptor(fd);
9074                    } catch (ErrnoException e) {
9075                        throw new RemoteException("Failed to open: " + e.getMessage());
9076                    }
9077                }
9078            };
9079
9080            int ret = PackageManager.INSTALL_SUCCEEDED;
9081            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9082            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9083                Slog.e(TAG, "Failed to copy package");
9084                return ret;
9085            }
9086
9087            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9088            NativeLibraryHelper.Handle handle = null;
9089            try {
9090                handle = NativeLibraryHelper.Handle.create(codeFile);
9091                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9092                        abiOverride);
9093            } catch (IOException e) {
9094                Slog.e(TAG, "Copying native libraries failed", e);
9095                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9096            } finally {
9097                IoUtils.closeQuietly(handle);
9098            }
9099
9100            return ret;
9101        }
9102
9103        int doPreInstall(int status) {
9104            if (status != PackageManager.INSTALL_SUCCEEDED) {
9105                cleanUp();
9106            }
9107            return status;
9108        }
9109
9110        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9111            if (status != PackageManager.INSTALL_SUCCEEDED) {
9112                cleanUp();
9113                return false;
9114            } else {
9115                final File beforeCodeFile = codeFile;
9116                final File afterCodeFile = getNextCodePath(pkg.packageName);
9117
9118                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9119                try {
9120                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9121                } catch (ErrnoException e) {
9122                    Slog.d(TAG, "Failed to rename", e);
9123                    return false;
9124                }
9125
9126                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9127                    Slog.d(TAG, "Failed to restorecon");
9128                    return false;
9129                }
9130
9131                // Reflect the rename internally
9132                codeFile = afterCodeFile;
9133                resourceFile = afterCodeFile;
9134
9135                // Reflect the rename in scanned details
9136                pkg.codePath = afterCodeFile.getAbsolutePath();
9137                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9138                        pkg.baseCodePath);
9139                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9140                        pkg.splitCodePaths);
9141
9142                // Reflect the rename in app info
9143                pkg.applicationInfo.setCodePath(pkg.codePath);
9144                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9145                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9146                pkg.applicationInfo.setResourcePath(pkg.codePath);
9147                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9148                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9149
9150                return true;
9151            }
9152        }
9153
9154        int doPostInstall(int status, int uid) {
9155            if (status != PackageManager.INSTALL_SUCCEEDED) {
9156                cleanUp();
9157            }
9158            return status;
9159        }
9160
9161        @Override
9162        String getCodePath() {
9163            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9164        }
9165
9166        @Override
9167        String getResourcePath() {
9168            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9169        }
9170
9171        @Override
9172        String getLegacyNativeLibraryPath() {
9173            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9174        }
9175
9176        private boolean cleanUp() {
9177            if (codeFile == null || !codeFile.exists()) {
9178                return false;
9179            }
9180
9181            if (codeFile.isDirectory()) {
9182                FileUtils.deleteContents(codeFile);
9183            }
9184            codeFile.delete();
9185
9186            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9187                resourceFile.delete();
9188            }
9189
9190            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9191                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9192                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9193                }
9194                legacyNativeLibraryPath.delete();
9195            }
9196
9197            return true;
9198        }
9199
9200        void cleanUpResourcesLI() {
9201            // Try enumerating all code paths before deleting
9202            List<String> allCodePaths = Collections.EMPTY_LIST;
9203            if (codeFile != null && codeFile.exists()) {
9204                try {
9205                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9206                    allCodePaths = pkg.getAllCodePaths();
9207                } catch (PackageParserException e) {
9208                    // Ignored; we tried our best
9209                }
9210            }
9211
9212            cleanUp();
9213
9214            if (!allCodePaths.isEmpty()) {
9215                if (instructionSets == null) {
9216                    throw new IllegalStateException("instructionSet == null");
9217                }
9218                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9219                for (String codePath : allCodePaths) {
9220                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9221                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9222                        if (retCode < 0) {
9223                            Slog.w(TAG, "Couldn't remove dex file for package: "
9224                                    + " at location " + codePath + ", retcode=" + retCode);
9225                            // we don't consider this to be a failure of the core package deletion
9226                        }
9227                    }
9228                }
9229            }
9230        }
9231
9232        boolean doPostDeleteLI(boolean delete) {
9233            // XXX err, shouldn't we respect the delete flag?
9234            cleanUpResourcesLI();
9235            return true;
9236        }
9237    }
9238
9239    private boolean isAsecExternal(String cid) {
9240        final String asecPath = PackageHelper.getSdFilesystem(cid);
9241        return !asecPath.startsWith(mAsecInternalPath);
9242    }
9243
9244    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9245            PackageManagerException {
9246        if (copyRet < 0) {
9247            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9248                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9249                throw new PackageManagerException(copyRet, message);
9250            }
9251        }
9252    }
9253
9254    /**
9255     * Extract the MountService "container ID" from the full code path of an
9256     * .apk.
9257     */
9258    static String cidFromCodePath(String fullCodePath) {
9259        int eidx = fullCodePath.lastIndexOf("/");
9260        String subStr1 = fullCodePath.substring(0, eidx);
9261        int sidx = subStr1.lastIndexOf("/");
9262        return subStr1.substring(sidx+1, eidx);
9263    }
9264
9265    /**
9266     * Logic to handle installation of ASEC applications, including copying and
9267     * renaming logic.
9268     */
9269    class AsecInstallArgs extends InstallArgs {
9270        static final String RES_FILE_NAME = "pkg.apk";
9271        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9272
9273        String cid;
9274        String packagePath;
9275        String resourcePath;
9276        String legacyNativeLibraryDir;
9277
9278        /** New install */
9279        AsecInstallArgs(InstallParams params) {
9280            super(params.origin, params.observer, params.installFlags,
9281                    params.installerPackageName, params.getManifestDigest(),
9282                    params.getUser(), null /* instruction sets */,
9283                    params.packageAbiOverride);
9284        }
9285
9286        /** Existing install */
9287        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9288                        boolean isExternal, boolean isForwardLocked) {
9289            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9290                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9291                    instructionSets, null);
9292            // Hackily pretend we're still looking at a full code path
9293            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9294                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9295            }
9296
9297            // Extract cid from fullCodePath
9298            int eidx = fullCodePath.lastIndexOf("/");
9299            String subStr1 = fullCodePath.substring(0, eidx);
9300            int sidx = subStr1.lastIndexOf("/");
9301            cid = subStr1.substring(sidx+1, eidx);
9302            setMountPath(subStr1);
9303        }
9304
9305        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9306            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9307                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9308                    instructionSets, null);
9309            this.cid = cid;
9310            setMountPath(PackageHelper.getSdDir(cid));
9311        }
9312
9313        void createCopyFile() {
9314            cid = mInstallerService.allocateExternalStageCidLegacy();
9315        }
9316
9317        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9318            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9319                    abiOverride);
9320
9321            final File target;
9322            if (isExternal()) {
9323                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9324            } else {
9325                target = Environment.getDataDirectory();
9326            }
9327
9328            final StorageManager storage = StorageManager.from(mContext);
9329            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9330        }
9331
9332        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9333            if (origin.staged) {
9334                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9335                cid = origin.cid;
9336                setMountPath(PackageHelper.getSdDir(cid));
9337                return PackageManager.INSTALL_SUCCEEDED;
9338            }
9339
9340            if (temp) {
9341                createCopyFile();
9342            } else {
9343                /*
9344                 * Pre-emptively destroy the container since it's destroyed if
9345                 * copying fails due to it existing anyway.
9346                 */
9347                PackageHelper.destroySdDir(cid);
9348            }
9349
9350            final String newMountPath = imcs.copyPackageToContainer(
9351                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9352                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9353
9354            if (newMountPath != null) {
9355                setMountPath(newMountPath);
9356                return PackageManager.INSTALL_SUCCEEDED;
9357            } else {
9358                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9359            }
9360        }
9361
9362        @Override
9363        String getCodePath() {
9364            return packagePath;
9365        }
9366
9367        @Override
9368        String getResourcePath() {
9369            return resourcePath;
9370        }
9371
9372        @Override
9373        String getLegacyNativeLibraryPath() {
9374            return legacyNativeLibraryDir;
9375        }
9376
9377        int doPreInstall(int status) {
9378            if (status != PackageManager.INSTALL_SUCCEEDED) {
9379                // Destroy container
9380                PackageHelper.destroySdDir(cid);
9381            } else {
9382                boolean mounted = PackageHelper.isContainerMounted(cid);
9383                if (!mounted) {
9384                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9385                            Process.SYSTEM_UID);
9386                    if (newMountPath != null) {
9387                        setMountPath(newMountPath);
9388                    } else {
9389                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9390                    }
9391                }
9392            }
9393            return status;
9394        }
9395
9396        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9397            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9398            String newMountPath = null;
9399            if (PackageHelper.isContainerMounted(cid)) {
9400                // Unmount the container
9401                if (!PackageHelper.unMountSdDir(cid)) {
9402                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9403                    return false;
9404                }
9405            }
9406            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9407                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9408                        " which might be stale. Will try to clean up.");
9409                // Clean up the stale container and proceed to recreate.
9410                if (!PackageHelper.destroySdDir(newCacheId)) {
9411                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9412                    return false;
9413                }
9414                // Successfully cleaned up stale container. Try to rename again.
9415                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9416                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9417                            + " inspite of cleaning it up.");
9418                    return false;
9419                }
9420            }
9421            if (!PackageHelper.isContainerMounted(newCacheId)) {
9422                Slog.w(TAG, "Mounting container " + newCacheId);
9423                newMountPath = PackageHelper.mountSdDir(newCacheId,
9424                        getEncryptKey(), Process.SYSTEM_UID);
9425            } else {
9426                newMountPath = PackageHelper.getSdDir(newCacheId);
9427            }
9428            if (newMountPath == null) {
9429                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9430                return false;
9431            }
9432            Log.i(TAG, "Succesfully renamed " + cid +
9433                    " to " + newCacheId +
9434                    " at new path: " + newMountPath);
9435            cid = newCacheId;
9436
9437            final File beforeCodeFile = new File(packagePath);
9438            setMountPath(newMountPath);
9439            final File afterCodeFile = new File(packagePath);
9440
9441            // Reflect the rename in scanned details
9442            pkg.codePath = afterCodeFile.getAbsolutePath();
9443            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9444                    pkg.baseCodePath);
9445            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9446                    pkg.splitCodePaths);
9447
9448            // Reflect the rename in app info
9449            pkg.applicationInfo.setCodePath(pkg.codePath);
9450            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9451            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9452            pkg.applicationInfo.setResourcePath(pkg.codePath);
9453            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9454            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9455
9456            return true;
9457        }
9458
9459        private void setMountPath(String mountPath) {
9460            final File mountFile = new File(mountPath);
9461
9462            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9463            if (monolithicFile.exists()) {
9464                packagePath = monolithicFile.getAbsolutePath();
9465                if (isFwdLocked()) {
9466                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9467                } else {
9468                    resourcePath = packagePath;
9469                }
9470            } else {
9471                packagePath = mountFile.getAbsolutePath();
9472                resourcePath = packagePath;
9473            }
9474
9475            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9476        }
9477
9478        int doPostInstall(int status, int uid) {
9479            if (status != PackageManager.INSTALL_SUCCEEDED) {
9480                cleanUp();
9481            } else {
9482                final int groupOwner;
9483                final String protectedFile;
9484                if (isFwdLocked()) {
9485                    groupOwner = UserHandle.getSharedAppGid(uid);
9486                    protectedFile = RES_FILE_NAME;
9487                } else {
9488                    groupOwner = -1;
9489                    protectedFile = null;
9490                }
9491
9492                if (uid < Process.FIRST_APPLICATION_UID
9493                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9494                    Slog.e(TAG, "Failed to finalize " + cid);
9495                    PackageHelper.destroySdDir(cid);
9496                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9497                }
9498
9499                boolean mounted = PackageHelper.isContainerMounted(cid);
9500                if (!mounted) {
9501                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9502                }
9503            }
9504            return status;
9505        }
9506
9507        private void cleanUp() {
9508            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9509
9510            // Destroy secure container
9511            PackageHelper.destroySdDir(cid);
9512        }
9513
9514        private List<String> getAllCodePaths() {
9515            final File codeFile = new File(getCodePath());
9516            if (codeFile != null && codeFile.exists()) {
9517                try {
9518                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9519                    return pkg.getAllCodePaths();
9520                } catch (PackageParserException e) {
9521                    // Ignored; we tried our best
9522                }
9523            }
9524            return Collections.EMPTY_LIST;
9525        }
9526
9527        void cleanUpResourcesLI() {
9528            // Enumerate all code paths before deleting
9529            cleanUpResourcesLI(getAllCodePaths());
9530        }
9531
9532        private void cleanUpResourcesLI(List<String> allCodePaths) {
9533            cleanUp();
9534
9535            if (!allCodePaths.isEmpty()) {
9536                if (instructionSets == null) {
9537                    throw new IllegalStateException("instructionSet == null");
9538                }
9539                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9540                for (String codePath : allCodePaths) {
9541                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9542                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9543                        if (retCode < 0) {
9544                            Slog.w(TAG, "Couldn't remove dex file for package: "
9545                                    + " at location " + codePath + ", retcode=" + retCode);
9546                            // we don't consider this to be a failure of the core package deletion
9547                        }
9548                    }
9549                }
9550            }
9551        }
9552
9553        boolean matchContainer(String app) {
9554            if (cid.startsWith(app)) {
9555                return true;
9556            }
9557            return false;
9558        }
9559
9560        String getPackageName() {
9561            return getAsecPackageName(cid);
9562        }
9563
9564        boolean doPostDeleteLI(boolean delete) {
9565            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9566            final List<String> allCodePaths = getAllCodePaths();
9567            boolean mounted = PackageHelper.isContainerMounted(cid);
9568            if (mounted) {
9569                // Unmount first
9570                if (PackageHelper.unMountSdDir(cid)) {
9571                    mounted = false;
9572                }
9573            }
9574            if (!mounted && delete) {
9575                cleanUpResourcesLI(allCodePaths);
9576            }
9577            return !mounted;
9578        }
9579
9580        @Override
9581        int doPreCopy() {
9582            if (isFwdLocked()) {
9583                if (!PackageHelper.fixSdPermissions(cid,
9584                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9585                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9586                }
9587            }
9588
9589            return PackageManager.INSTALL_SUCCEEDED;
9590        }
9591
9592        @Override
9593        int doPostCopy(int uid) {
9594            if (isFwdLocked()) {
9595                if (uid < Process.FIRST_APPLICATION_UID
9596                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9597                                RES_FILE_NAME)) {
9598                    Slog.e(TAG, "Failed to finalize " + cid);
9599                    PackageHelper.destroySdDir(cid);
9600                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9601                }
9602            }
9603
9604            return PackageManager.INSTALL_SUCCEEDED;
9605        }
9606    }
9607
9608    static String getAsecPackageName(String packageCid) {
9609        int idx = packageCid.lastIndexOf("-");
9610        if (idx == -1) {
9611            return packageCid;
9612        }
9613        return packageCid.substring(0, idx);
9614    }
9615
9616    // Utility method used to create code paths based on package name and available index.
9617    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9618        String idxStr = "";
9619        int idx = 1;
9620        // Fall back to default value of idx=1 if prefix is not
9621        // part of oldCodePath
9622        if (oldCodePath != null) {
9623            String subStr = oldCodePath;
9624            // Drop the suffix right away
9625            if (suffix != null && subStr.endsWith(suffix)) {
9626                subStr = subStr.substring(0, subStr.length() - suffix.length());
9627            }
9628            // If oldCodePath already contains prefix find out the
9629            // ending index to either increment or decrement.
9630            int sidx = subStr.lastIndexOf(prefix);
9631            if (sidx != -1) {
9632                subStr = subStr.substring(sidx + prefix.length());
9633                if (subStr != null) {
9634                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9635                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9636                    }
9637                    try {
9638                        idx = Integer.parseInt(subStr);
9639                        if (idx <= 1) {
9640                            idx++;
9641                        } else {
9642                            idx--;
9643                        }
9644                    } catch(NumberFormatException e) {
9645                    }
9646                }
9647            }
9648        }
9649        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9650        return prefix + idxStr;
9651    }
9652
9653    private File getNextCodePath(String packageName) {
9654        int suffix = 1;
9655        File result;
9656        do {
9657            result = new File(mAppInstallDir, packageName + "-" + suffix);
9658            suffix++;
9659        } while (result.exists());
9660        return result;
9661    }
9662
9663    // Utility method used to ignore ADD/REMOVE events
9664    // by directory observer.
9665    private static boolean ignoreCodePath(String fullPathStr) {
9666        String apkName = deriveCodePathName(fullPathStr);
9667        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9668        if (idx != -1 && ((idx+1) < apkName.length())) {
9669            // Make sure the package ends with a numeral
9670            String version = apkName.substring(idx+1);
9671            try {
9672                Integer.parseInt(version);
9673                return true;
9674            } catch (NumberFormatException e) {}
9675        }
9676        return false;
9677    }
9678
9679    // Utility method that returns the relative package path with respect
9680    // to the installation directory. Like say for /data/data/com.test-1.apk
9681    // string com.test-1 is returned.
9682    static String deriveCodePathName(String codePath) {
9683        if (codePath == null) {
9684            return null;
9685        }
9686        final File codeFile = new File(codePath);
9687        final String name = codeFile.getName();
9688        if (codeFile.isDirectory()) {
9689            return name;
9690        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9691            final int lastDot = name.lastIndexOf('.');
9692            return name.substring(0, lastDot);
9693        } else {
9694            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9695            return null;
9696        }
9697    }
9698
9699    class PackageInstalledInfo {
9700        String name;
9701        int uid;
9702        // The set of users that originally had this package installed.
9703        int[] origUsers;
9704        // The set of users that now have this package installed.
9705        int[] newUsers;
9706        PackageParser.Package pkg;
9707        int returnCode;
9708        String returnMsg;
9709        PackageRemovedInfo removedInfo;
9710
9711        public void setError(int code, String msg) {
9712            returnCode = code;
9713            returnMsg = msg;
9714            Slog.w(TAG, msg);
9715        }
9716
9717        public void setError(String msg, PackageParserException e) {
9718            returnCode = e.error;
9719            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9720            Slog.w(TAG, msg, e);
9721        }
9722
9723        public void setError(String msg, PackageManagerException e) {
9724            returnCode = e.error;
9725            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9726            Slog.w(TAG, msg, e);
9727        }
9728
9729        // In some error cases we want to convey more info back to the observer
9730        String origPackage;
9731        String origPermission;
9732    }
9733
9734    /*
9735     * Install a non-existing package.
9736     */
9737    private void installNewPackageLI(PackageParser.Package pkg,
9738            int parseFlags, int scanFlags, UserHandle user,
9739            String installerPackageName, PackageInstalledInfo res) {
9740        // Remember this for later, in case we need to rollback this install
9741        String pkgName = pkg.packageName;
9742
9743        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9744        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9745        synchronized(mPackages) {
9746            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9747                // A package with the same name is already installed, though
9748                // it has been renamed to an older name.  The package we
9749                // are trying to install should be installed as an update to
9750                // the existing one, but that has not been requested, so bail.
9751                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9752                        + " without first uninstalling package running as "
9753                        + mSettings.mRenamedPackages.get(pkgName));
9754                return;
9755            }
9756            if (mPackages.containsKey(pkgName)) {
9757                // Don't allow installation over an existing package with the same name.
9758                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9759                        + " without first uninstalling.");
9760                return;
9761            }
9762        }
9763
9764        try {
9765            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9766                    System.currentTimeMillis(), user);
9767
9768            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9769            // delete the partially installed application. the data directory will have to be
9770            // restored if it was already existing
9771            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9772                // remove package from internal structures.  Note that we want deletePackageX to
9773                // delete the package data and cache directories that it created in
9774                // scanPackageLocked, unless those directories existed before we even tried to
9775                // install.
9776                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9777                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9778                                res.removedInfo, true);
9779            }
9780
9781        } catch (PackageManagerException e) {
9782            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9783        }
9784    }
9785
9786    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9787        // Upgrade keysets are being used.  Determine if new package has a superset of the
9788        // required keys.
9789        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9790        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9791        for (int i = 0; i < upgradeKeySets.length; i++) {
9792            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9793            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9794                return true;
9795            }
9796        }
9797        return false;
9798    }
9799
9800    private void replacePackageLI(PackageParser.Package pkg,
9801            int parseFlags, int scanFlags, UserHandle user,
9802            String installerPackageName, PackageInstalledInfo res) {
9803        PackageParser.Package oldPackage;
9804        String pkgName = pkg.packageName;
9805        int[] allUsers;
9806        boolean[] perUserInstalled;
9807
9808        // First find the old package info and check signatures
9809        synchronized(mPackages) {
9810            oldPackage = mPackages.get(pkgName);
9811            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9812            PackageSetting ps = mSettings.mPackages.get(pkgName);
9813            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9814                // default to original signature matching
9815                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9816                    != PackageManager.SIGNATURE_MATCH) {
9817                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9818                            "New package has a different signature: " + pkgName);
9819                    return;
9820                }
9821            } else {
9822                if(!checkUpgradeKeySetLP(ps, pkg)) {
9823                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9824                            "New package not signed by keys specified by upgrade-keysets: "
9825                            + pkgName);
9826                    return;
9827                }
9828            }
9829
9830            // In case of rollback, remember per-user/profile install state
9831            allUsers = sUserManager.getUserIds();
9832            perUserInstalled = new boolean[allUsers.length];
9833            for (int i = 0; i < allUsers.length; i++) {
9834                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9835            }
9836        }
9837
9838        boolean sysPkg = (isSystemApp(oldPackage));
9839        if (sysPkg) {
9840            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9841                    user, allUsers, perUserInstalled, installerPackageName, res);
9842        } else {
9843            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9844                    user, allUsers, perUserInstalled, installerPackageName, res);
9845        }
9846    }
9847
9848    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9849            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9850            int[] allUsers, boolean[] perUserInstalled,
9851            String installerPackageName, PackageInstalledInfo res) {
9852        String pkgName = deletedPackage.packageName;
9853        boolean deletedPkg = true;
9854        boolean updatedSettings = false;
9855
9856        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9857                + deletedPackage);
9858        long origUpdateTime;
9859        if (pkg.mExtras != null) {
9860            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9861        } else {
9862            origUpdateTime = 0;
9863        }
9864
9865        // First delete the existing package while retaining the data directory
9866        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9867                res.removedInfo, true)) {
9868            // If the existing package wasn't successfully deleted
9869            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9870            deletedPkg = false;
9871        } else {
9872            // Successfully deleted the old package; proceed with replace.
9873
9874            // If deleted package lived in a container, give users a chance to
9875            // relinquish resources before killing.
9876            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9877                if (DEBUG_INSTALL) {
9878                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9879                }
9880                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9881                final ArrayList<String> pkgList = new ArrayList<String>(1);
9882                pkgList.add(deletedPackage.applicationInfo.packageName);
9883                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9884            }
9885
9886            deleteCodeCacheDirsLI(pkgName);
9887            try {
9888                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9889                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9890                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9891                updatedSettings = true;
9892            } catch (PackageManagerException e) {
9893                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9894            }
9895        }
9896
9897        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9898            // remove package from internal structures.  Note that we want deletePackageX to
9899            // delete the package data and cache directories that it created in
9900            // scanPackageLocked, unless those directories existed before we even tried to
9901            // install.
9902            if(updatedSettings) {
9903                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9904                deletePackageLI(
9905                        pkgName, null, true, allUsers, perUserInstalled,
9906                        PackageManager.DELETE_KEEP_DATA,
9907                                res.removedInfo, true);
9908            }
9909            // Since we failed to install the new package we need to restore the old
9910            // package that we deleted.
9911            if (deletedPkg) {
9912                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9913                File restoreFile = new File(deletedPackage.codePath);
9914                // Parse old package
9915                boolean oldOnSd = isExternal(deletedPackage);
9916                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9917                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9918                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9919                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9920                try {
9921                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9922                } catch (PackageManagerException e) {
9923                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9924                            + e.getMessage());
9925                    return;
9926                }
9927                // Restore of old package succeeded. Update permissions.
9928                // writer
9929                synchronized (mPackages) {
9930                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9931                            UPDATE_PERMISSIONS_ALL);
9932                    // can downgrade to reader
9933                    mSettings.writeLPr();
9934                }
9935                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9936            }
9937        }
9938    }
9939
9940    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9941            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9942            int[] allUsers, boolean[] perUserInstalled,
9943            String installerPackageName, PackageInstalledInfo res) {
9944        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9945                + ", old=" + deletedPackage);
9946        boolean updatedSettings = false;
9947        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9948        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9949            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9950        }
9951        String packageName = deletedPackage.packageName;
9952        if (packageName == null) {
9953            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9954                    "Attempt to delete null packageName.");
9955            return;
9956        }
9957        PackageParser.Package oldPkg;
9958        PackageSetting oldPkgSetting;
9959        // reader
9960        synchronized (mPackages) {
9961            oldPkg = mPackages.get(packageName);
9962            oldPkgSetting = mSettings.mPackages.get(packageName);
9963            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9964                    (oldPkgSetting == null)) {
9965                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9966                        "Couldn't find package:" + packageName + " information");
9967                return;
9968            }
9969        }
9970
9971        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9972
9973        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9974        res.removedInfo.removedPackage = packageName;
9975        // Remove existing system package
9976        removePackageLI(oldPkgSetting, true);
9977        // writer
9978        synchronized (mPackages) {
9979            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9980                // We didn't need to disable the .apk as a current system package,
9981                // which means we are replacing another update that is already
9982                // installed.  We need to make sure to delete the older one's .apk.
9983                res.removedInfo.args = createInstallArgsForExisting(0,
9984                        deletedPackage.applicationInfo.getCodePath(),
9985                        deletedPackage.applicationInfo.getResourcePath(),
9986                        deletedPackage.applicationInfo.nativeLibraryRootDir,
9987                        getAppDexInstructionSets(deletedPackage.applicationInfo));
9988            } else {
9989                res.removedInfo.args = null;
9990            }
9991        }
9992
9993        // Successfully disabled the old package. Now proceed with re-installation
9994        deleteCodeCacheDirsLI(packageName);
9995
9996        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9997        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9998
9999        PackageParser.Package newPackage = null;
10000        try {
10001            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10002            if (newPackage.mExtras != null) {
10003                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10004                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10005                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10006
10007                // is the update attempting to change shared user? that isn't going to work...
10008                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10009                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10010                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10011                            + " to " + newPkgSetting.sharedUser);
10012                    updatedSettings = true;
10013                }
10014            }
10015
10016            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10017                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10018                updatedSettings = true;
10019            }
10020
10021        } catch (PackageManagerException e) {
10022            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10023        }
10024
10025        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10026            // Re installation failed. Restore old information
10027            // Remove new pkg information
10028            if (newPackage != null) {
10029                removeInstalledPackageLI(newPackage, true);
10030            }
10031            // Add back the old system package
10032            try {
10033                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10034            } catch (PackageManagerException e) {
10035                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10036            }
10037            // Restore the old system information in Settings
10038            synchronized(mPackages) {
10039                if (updatedSettings) {
10040                    mSettings.enableSystemPackageLPw(packageName);
10041                    mSettings.setInstallerPackageName(packageName,
10042                            oldPkgSetting.installerPackageName);
10043                }
10044                mSettings.writeLPr();
10045            }
10046        }
10047    }
10048
10049    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10050            int[] allUsers, boolean[] perUserInstalled,
10051            PackageInstalledInfo res) {
10052        String pkgName = newPackage.packageName;
10053        synchronized (mPackages) {
10054            //write settings. the installStatus will be incomplete at this stage.
10055            //note that the new package setting would have already been
10056            //added to mPackages. It hasn't been persisted yet.
10057            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10058            mSettings.writeLPr();
10059        }
10060
10061        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10062
10063        synchronized (mPackages) {
10064            updatePermissionsLPw(newPackage.packageName, newPackage,
10065                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10066                            ? UPDATE_PERMISSIONS_ALL : 0));
10067            // For system-bundled packages, we assume that installing an upgraded version
10068            // of the package implies that the user actually wants to run that new code,
10069            // so we enable the package.
10070            if (isSystemApp(newPackage)) {
10071                // NB: implicit assumption that system package upgrades apply to all users
10072                if (DEBUG_INSTALL) {
10073                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10074                }
10075                PackageSetting ps = mSettings.mPackages.get(pkgName);
10076                if (ps != null) {
10077                    if (res.origUsers != null) {
10078                        for (int userHandle : res.origUsers) {
10079                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10080                                    userHandle, installerPackageName);
10081                        }
10082                    }
10083                    // Also convey the prior install/uninstall state
10084                    if (allUsers != null && perUserInstalled != null) {
10085                        for (int i = 0; i < allUsers.length; i++) {
10086                            if (DEBUG_INSTALL) {
10087                                Slog.d(TAG, "    user " + allUsers[i]
10088                                        + " => " + perUserInstalled[i]);
10089                            }
10090                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10091                        }
10092                        // these install state changes will be persisted in the
10093                        // upcoming call to mSettings.writeLPr().
10094                    }
10095                }
10096            }
10097            res.name = pkgName;
10098            res.uid = newPackage.applicationInfo.uid;
10099            res.pkg = newPackage;
10100            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10101            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10102            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10103            //to update install status
10104            mSettings.writeLPr();
10105        }
10106    }
10107
10108    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10109        final int installFlags = args.installFlags;
10110        String installerPackageName = args.installerPackageName;
10111        File tmpPackageFile = new File(args.getCodePath());
10112        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10113        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10114        boolean replace = false;
10115        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10116        // Result object to be returned
10117        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10118
10119        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10120        // Retrieve PackageSettings and parse package
10121        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10122                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10123                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10124        PackageParser pp = new PackageParser();
10125        pp.setSeparateProcesses(mSeparateProcesses);
10126        pp.setDisplayMetrics(mMetrics);
10127
10128        final PackageParser.Package pkg;
10129        try {
10130            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10131        } catch (PackageParserException e) {
10132            res.setError("Failed parse during installPackageLI", e);
10133            return;
10134        }
10135
10136        // Mark that we have an install time CPU ABI override.
10137        pkg.cpuAbiOverride = args.abiOverride;
10138
10139        String pkgName = res.name = pkg.packageName;
10140        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10141            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10142                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10143                return;
10144            }
10145        }
10146
10147        try {
10148            pp.collectCertificates(pkg, parseFlags);
10149            pp.collectManifestDigest(pkg);
10150        } catch (PackageParserException e) {
10151            res.setError("Failed collect during installPackageLI", e);
10152            return;
10153        }
10154
10155        /* If the installer passed in a manifest digest, compare it now. */
10156        if (args.manifestDigest != null) {
10157            if (DEBUG_INSTALL) {
10158                final String parsedManifest = pkg.manifestDigest == null ? "null"
10159                        : pkg.manifestDigest.toString();
10160                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10161                        + parsedManifest);
10162            }
10163
10164            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10165                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10166                return;
10167            }
10168        } else if (DEBUG_INSTALL) {
10169            final String parsedManifest = pkg.manifestDigest == null
10170                    ? "null" : pkg.manifestDigest.toString();
10171            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10172        }
10173
10174        // Get rid of all references to package scan path via parser.
10175        pp = null;
10176        String oldCodePath = null;
10177        boolean systemApp = false;
10178        synchronized (mPackages) {
10179            // Check whether the newly-scanned package wants to define an already-defined perm
10180            int N = pkg.permissions.size();
10181            for (int i = N-1; i >= 0; i--) {
10182                PackageParser.Permission perm = pkg.permissions.get(i);
10183                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10184                if (bp != null) {
10185                    // If the defining package is signed with our cert, it's okay.  This
10186                    // also includes the "updating the same package" case, of course.
10187                    // "updating same package" could also involve key-rotation.
10188                    final boolean sigsOk;
10189                    if (!bp.sourcePackage.equals(pkg.packageName)
10190                            || !(bp.packageSetting instanceof PackageSetting)
10191                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10192                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10193                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10194                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10195                    } else {
10196                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10197                    }
10198                    if (!sigsOk) {
10199                        // If the owning package is the system itself, we log but allow
10200                        // install to proceed; we fail the install on all other permission
10201                        // redefinitions.
10202                        if (!bp.sourcePackage.equals("android")) {
10203                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10204                                    + pkg.packageName + " attempting to redeclare permission "
10205                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10206                            res.origPermission = perm.info.name;
10207                            res.origPackage = bp.sourcePackage;
10208                            return;
10209                        } else {
10210                            Slog.w(TAG, "Package " + pkg.packageName
10211                                    + " attempting to redeclare system permission "
10212                                    + perm.info.name + "; ignoring new declaration");
10213                            pkg.permissions.remove(i);
10214                        }
10215                    }
10216                }
10217            }
10218
10219            // Check if installing already existing package
10220            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10221                String oldName = mSettings.mRenamedPackages.get(pkgName);
10222                if (pkg.mOriginalPackages != null
10223                        && pkg.mOriginalPackages.contains(oldName)
10224                        && mPackages.containsKey(oldName)) {
10225                    // This package is derived from an original package,
10226                    // and this device has been updating from that original
10227                    // name.  We must continue using the original name, so
10228                    // rename the new package here.
10229                    pkg.setPackageName(oldName);
10230                    pkgName = pkg.packageName;
10231                    replace = true;
10232                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10233                            + oldName + " pkgName=" + pkgName);
10234                } else if (mPackages.containsKey(pkgName)) {
10235                    // This package, under its official name, already exists
10236                    // on the device; we should replace it.
10237                    replace = true;
10238                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10239                }
10240            }
10241            PackageSetting ps = mSettings.mPackages.get(pkgName);
10242            if (ps != null) {
10243                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10244                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10245                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10246                    systemApp = (ps.pkg.applicationInfo.flags &
10247                            ApplicationInfo.FLAG_SYSTEM) != 0;
10248                }
10249                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10250            }
10251        }
10252
10253        if (systemApp && onSd) {
10254            // Disable updates to system apps on sdcard
10255            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10256                    "Cannot install updates to system apps on sdcard");
10257            return;
10258        }
10259
10260        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10261            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10262            return;
10263        }
10264
10265        if (replace) {
10266            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10267                    installerPackageName, res);
10268        } else {
10269            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10270                    args.user, installerPackageName, res);
10271        }
10272        synchronized (mPackages) {
10273            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10274            if (ps != null) {
10275                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10276            }
10277        }
10278    }
10279
10280    private static boolean isForwardLocked(PackageParser.Package pkg) {
10281        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10282    }
10283
10284    private static boolean isForwardLocked(ApplicationInfo info) {
10285        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10286    }
10287
10288    private boolean isForwardLocked(PackageSetting ps) {
10289        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10290    }
10291
10292    private static boolean isMultiArch(PackageSetting ps) {
10293        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10294    }
10295
10296    private static boolean isMultiArch(ApplicationInfo info) {
10297        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10298    }
10299
10300    private static boolean isExternal(PackageParser.Package pkg) {
10301        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10302    }
10303
10304    private static boolean isExternal(PackageSetting ps) {
10305        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10306    }
10307
10308    private static boolean isExternal(ApplicationInfo info) {
10309        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10310    }
10311
10312    private static boolean isSystemApp(PackageParser.Package pkg) {
10313        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10314    }
10315
10316    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10317        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10318    }
10319
10320    private static boolean isSystemApp(ApplicationInfo info) {
10321        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10322    }
10323
10324    private static boolean isSystemApp(PackageSetting ps) {
10325        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10326    }
10327
10328    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10329        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10330    }
10331
10332    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10333        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10334    }
10335
10336    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10337        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10338    }
10339
10340    private int packageFlagsToInstallFlags(PackageSetting ps) {
10341        int installFlags = 0;
10342        if (isExternal(ps)) {
10343            installFlags |= PackageManager.INSTALL_EXTERNAL;
10344        }
10345        if (isForwardLocked(ps)) {
10346            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10347        }
10348        return installFlags;
10349    }
10350
10351    private void deleteTempPackageFiles() {
10352        final FilenameFilter filter = new FilenameFilter() {
10353            public boolean accept(File dir, String name) {
10354                return name.startsWith("vmdl") && name.endsWith(".tmp");
10355            }
10356        };
10357        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10358            file.delete();
10359        }
10360    }
10361
10362    @Override
10363    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10364            int flags) {
10365        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10366                flags);
10367    }
10368
10369    @Override
10370    public void deletePackage(final String packageName,
10371            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10372        mContext.enforceCallingOrSelfPermission(
10373                android.Manifest.permission.DELETE_PACKAGES, null);
10374        final int uid = Binder.getCallingUid();
10375        if (UserHandle.getUserId(uid) != userId) {
10376            mContext.enforceCallingPermission(
10377                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10378                    "deletePackage for user " + userId);
10379        }
10380        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10381            try {
10382                observer.onPackageDeleted(packageName,
10383                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10384            } catch (RemoteException re) {
10385            }
10386            return;
10387        }
10388
10389        boolean uninstallBlocked = false;
10390        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10391            int[] users = sUserManager.getUserIds();
10392            for (int i = 0; i < users.length; ++i) {
10393                if (getBlockUninstallForUser(packageName, users[i])) {
10394                    uninstallBlocked = true;
10395                    break;
10396                }
10397            }
10398        } else {
10399            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10400        }
10401        if (uninstallBlocked) {
10402            try {
10403                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10404                        null);
10405            } catch (RemoteException re) {
10406            }
10407            return;
10408        }
10409
10410        if (DEBUG_REMOVE) {
10411            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10412        }
10413        // Queue up an async operation since the package deletion may take a little while.
10414        mHandler.post(new Runnable() {
10415            public void run() {
10416                mHandler.removeCallbacks(this);
10417                final int returnCode = deletePackageX(packageName, userId, flags);
10418                if (observer != null) {
10419                    try {
10420                        observer.onPackageDeleted(packageName, returnCode, null);
10421                    } catch (RemoteException e) {
10422                        Log.i(TAG, "Observer no longer exists.");
10423                    } //end catch
10424                } //end if
10425            } //end run
10426        });
10427    }
10428
10429    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10430        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10431                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10432        try {
10433            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10434                    || dpm.isDeviceOwner(packageName))) {
10435                return true;
10436            }
10437        } catch (RemoteException e) {
10438        }
10439        return false;
10440    }
10441
10442    /**
10443     *  This method is an internal method that could be get invoked either
10444     *  to delete an installed package or to clean up a failed installation.
10445     *  After deleting an installed package, a broadcast is sent to notify any
10446     *  listeners that the package has been installed. For cleaning up a failed
10447     *  installation, the broadcast is not necessary since the package's
10448     *  installation wouldn't have sent the initial broadcast either
10449     *  The key steps in deleting a package are
10450     *  deleting the package information in internal structures like mPackages,
10451     *  deleting the packages base directories through installd
10452     *  updating mSettings to reflect current status
10453     *  persisting settings for later use
10454     *  sending a broadcast if necessary
10455     */
10456    private int deletePackageX(String packageName, int userId, int flags) {
10457        final PackageRemovedInfo info = new PackageRemovedInfo();
10458        final boolean res;
10459
10460        if (isPackageDeviceAdmin(packageName, userId)) {
10461            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10462            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10463        }
10464
10465        boolean removedForAllUsers = false;
10466        boolean systemUpdate = false;
10467
10468        // for the uninstall-updates case and restricted profiles, remember the per-
10469        // userhandle installed state
10470        int[] allUsers;
10471        boolean[] perUserInstalled;
10472        synchronized (mPackages) {
10473            PackageSetting ps = mSettings.mPackages.get(packageName);
10474            allUsers = sUserManager.getUserIds();
10475            perUserInstalled = new boolean[allUsers.length];
10476            for (int i = 0; i < allUsers.length; i++) {
10477                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10478            }
10479        }
10480
10481        synchronized (mInstallLock) {
10482            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10483            res = deletePackageLI(packageName,
10484                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10485                            ? UserHandle.ALL : new UserHandle(userId),
10486                    true, allUsers, perUserInstalled,
10487                    flags | REMOVE_CHATTY, info, true);
10488            systemUpdate = info.isRemovedPackageSystemUpdate;
10489            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10490                removedForAllUsers = true;
10491            }
10492            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10493                    + " removedForAllUsers=" + removedForAllUsers);
10494        }
10495
10496        if (res) {
10497            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10498
10499            // If the removed package was a system update, the old system package
10500            // was re-enabled; we need to broadcast this information
10501            if (systemUpdate) {
10502                Bundle extras = new Bundle(1);
10503                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10504                        ? info.removedAppId : info.uid);
10505                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10506
10507                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10508                        extras, null, null, null);
10509                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10510                        extras, null, null, null);
10511                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10512                        null, packageName, null, null);
10513            }
10514        }
10515        // Force a gc here.
10516        Runtime.getRuntime().gc();
10517        // Delete the resources here after sending the broadcast to let
10518        // other processes clean up before deleting resources.
10519        if (info.args != null) {
10520            synchronized (mInstallLock) {
10521                info.args.doPostDeleteLI(true);
10522            }
10523        }
10524
10525        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10526    }
10527
10528    static class PackageRemovedInfo {
10529        String removedPackage;
10530        int uid = -1;
10531        int removedAppId = -1;
10532        int[] removedUsers = null;
10533        boolean isRemovedPackageSystemUpdate = false;
10534        // Clean up resources deleted packages.
10535        InstallArgs args = null;
10536
10537        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10538            Bundle extras = new Bundle(1);
10539            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10540            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10541            if (replacing) {
10542                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10543            }
10544            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10545            if (removedPackage != null) {
10546                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10547                        extras, null, null, removedUsers);
10548                if (fullRemove && !replacing) {
10549                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10550                            extras, null, null, removedUsers);
10551                }
10552            }
10553            if (removedAppId >= 0) {
10554                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10555                        removedUsers);
10556            }
10557        }
10558    }
10559
10560    /*
10561     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10562     * flag is not set, the data directory is removed as well.
10563     * make sure this flag is set for partially installed apps. If not its meaningless to
10564     * delete a partially installed application.
10565     */
10566    private void removePackageDataLI(PackageSetting ps,
10567            int[] allUserHandles, boolean[] perUserInstalled,
10568            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10569        String packageName = ps.name;
10570        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10571        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10572        // Retrieve object to delete permissions for shared user later on
10573        final PackageSetting deletedPs;
10574        // reader
10575        synchronized (mPackages) {
10576            deletedPs = mSettings.mPackages.get(packageName);
10577            if (outInfo != null) {
10578                outInfo.removedPackage = packageName;
10579                outInfo.removedUsers = deletedPs != null
10580                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10581                        : null;
10582            }
10583        }
10584        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10585            removeDataDirsLI(packageName);
10586            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10587        }
10588        // writer
10589        synchronized (mPackages) {
10590            if (deletedPs != null) {
10591                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10592                    if (outInfo != null) {
10593                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10594                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10595                    }
10596                    if (deletedPs != null) {
10597                        updatePermissionsLPw(deletedPs.name, null, 0);
10598                        if (deletedPs.sharedUser != null) {
10599                            // remove permissions associated with package
10600                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10601                        }
10602                    }
10603                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10604                }
10605                // make sure to preserve per-user disabled state if this removal was just
10606                // a downgrade of a system app to the factory package
10607                if (allUserHandles != null && perUserInstalled != null) {
10608                    if (DEBUG_REMOVE) {
10609                        Slog.d(TAG, "Propagating install state across downgrade");
10610                    }
10611                    for (int i = 0; i < allUserHandles.length; i++) {
10612                        if (DEBUG_REMOVE) {
10613                            Slog.d(TAG, "    user " + allUserHandles[i]
10614                                    + " => " + perUserInstalled[i]);
10615                        }
10616                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10617                    }
10618                }
10619            }
10620            // can downgrade to reader
10621            if (writeSettings) {
10622                // Save settings now
10623                mSettings.writeLPr();
10624            }
10625        }
10626        if (outInfo != null) {
10627            // A user ID was deleted here. Go through all users and remove it
10628            // from KeyStore.
10629            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10630        }
10631    }
10632
10633    static boolean locationIsPrivileged(File path) {
10634        try {
10635            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10636                    .getCanonicalPath();
10637            return path.getCanonicalPath().startsWith(privilegedAppDir);
10638        } catch (IOException e) {
10639            Slog.e(TAG, "Unable to access code path " + path);
10640        }
10641        return false;
10642    }
10643
10644    /*
10645     * Tries to delete system package.
10646     */
10647    private boolean deleteSystemPackageLI(PackageSetting newPs,
10648            int[] allUserHandles, boolean[] perUserInstalled,
10649            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10650        final boolean applyUserRestrictions
10651                = (allUserHandles != null) && (perUserInstalled != null);
10652        PackageSetting disabledPs = null;
10653        // Confirm if the system package has been updated
10654        // An updated system app can be deleted. This will also have to restore
10655        // the system pkg from system partition
10656        // reader
10657        synchronized (mPackages) {
10658            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10659        }
10660        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10661                + " disabledPs=" + disabledPs);
10662        if (disabledPs == null) {
10663            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10664            return false;
10665        } else if (DEBUG_REMOVE) {
10666            Slog.d(TAG, "Deleting system pkg from data partition");
10667        }
10668        if (DEBUG_REMOVE) {
10669            if (applyUserRestrictions) {
10670                Slog.d(TAG, "Remembering install states:");
10671                for (int i = 0; i < allUserHandles.length; i++) {
10672                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10673                }
10674            }
10675        }
10676        // Delete the updated package
10677        outInfo.isRemovedPackageSystemUpdate = true;
10678        if (disabledPs.versionCode < newPs.versionCode) {
10679            // Delete data for downgrades
10680            flags &= ~PackageManager.DELETE_KEEP_DATA;
10681        } else {
10682            // Preserve data by setting flag
10683            flags |= PackageManager.DELETE_KEEP_DATA;
10684        }
10685        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10686                allUserHandles, perUserInstalled, outInfo, writeSettings);
10687        if (!ret) {
10688            return false;
10689        }
10690        // writer
10691        synchronized (mPackages) {
10692            // Reinstate the old system package
10693            mSettings.enableSystemPackageLPw(newPs.name);
10694            // Remove any native libraries from the upgraded package.
10695            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10696        }
10697        // Install the system package
10698        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10699        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10700        if (locationIsPrivileged(disabledPs.codePath)) {
10701            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10702        }
10703
10704        final PackageParser.Package newPkg;
10705        try {
10706            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10707        } catch (PackageManagerException e) {
10708            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10709            return false;
10710        }
10711
10712        // writer
10713        synchronized (mPackages) {
10714            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10715            updatePermissionsLPw(newPkg.packageName, newPkg,
10716                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10717            if (applyUserRestrictions) {
10718                if (DEBUG_REMOVE) {
10719                    Slog.d(TAG, "Propagating install state across reinstall");
10720                }
10721                for (int i = 0; i < allUserHandles.length; i++) {
10722                    if (DEBUG_REMOVE) {
10723                        Slog.d(TAG, "    user " + allUserHandles[i]
10724                                + " => " + perUserInstalled[i]);
10725                    }
10726                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10727                }
10728                // Regardless of writeSettings we need to ensure that this restriction
10729                // state propagation is persisted
10730                mSettings.writeAllUsersPackageRestrictionsLPr();
10731            }
10732            // can downgrade to reader here
10733            if (writeSettings) {
10734                mSettings.writeLPr();
10735            }
10736        }
10737        return true;
10738    }
10739
10740    private boolean deleteInstalledPackageLI(PackageSetting ps,
10741            boolean deleteCodeAndResources, int flags,
10742            int[] allUserHandles, boolean[] perUserInstalled,
10743            PackageRemovedInfo outInfo, boolean writeSettings) {
10744        if (outInfo != null) {
10745            outInfo.uid = ps.appId;
10746        }
10747
10748        // Delete package data from internal structures and also remove data if flag is set
10749        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10750
10751        // Delete application code and resources
10752        if (deleteCodeAndResources && (outInfo != null)) {
10753            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10754                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10755                    getAppDexInstructionSets(ps));
10756            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10757        }
10758        return true;
10759    }
10760
10761    @Override
10762    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10763            int userId) {
10764        mContext.enforceCallingOrSelfPermission(
10765                android.Manifest.permission.DELETE_PACKAGES, null);
10766        synchronized (mPackages) {
10767            PackageSetting ps = mSettings.mPackages.get(packageName);
10768            if (ps == null) {
10769                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10770                return false;
10771            }
10772            if (!ps.getInstalled(userId)) {
10773                // Can't block uninstall for an app that is not installed or enabled.
10774                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10775                return false;
10776            }
10777            ps.setBlockUninstall(blockUninstall, userId);
10778            mSettings.writePackageRestrictionsLPr(userId);
10779        }
10780        return true;
10781    }
10782
10783    @Override
10784    public boolean getBlockUninstallForUser(String packageName, int userId) {
10785        synchronized (mPackages) {
10786            PackageSetting ps = mSettings.mPackages.get(packageName);
10787            if (ps == null) {
10788                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10789                return false;
10790            }
10791            return ps.getBlockUninstall(userId);
10792        }
10793    }
10794
10795    /*
10796     * This method handles package deletion in general
10797     */
10798    private boolean deletePackageLI(String packageName, UserHandle user,
10799            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10800            int flags, PackageRemovedInfo outInfo,
10801            boolean writeSettings) {
10802        if (packageName == null) {
10803            Slog.w(TAG, "Attempt to delete null packageName.");
10804            return false;
10805        }
10806        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10807        PackageSetting ps;
10808        boolean dataOnly = false;
10809        int removeUser = -1;
10810        int appId = -1;
10811        synchronized (mPackages) {
10812            ps = mSettings.mPackages.get(packageName);
10813            if (ps == null) {
10814                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10815                return false;
10816            }
10817            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10818                    && user.getIdentifier() != UserHandle.USER_ALL) {
10819                // The caller is asking that the package only be deleted for a single
10820                // user.  To do this, we just mark its uninstalled state and delete
10821                // its data.  If this is a system app, we only allow this to happen if
10822                // they have set the special DELETE_SYSTEM_APP which requests different
10823                // semantics than normal for uninstalling system apps.
10824                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10825                ps.setUserState(user.getIdentifier(),
10826                        COMPONENT_ENABLED_STATE_DEFAULT,
10827                        false, //installed
10828                        true,  //stopped
10829                        true,  //notLaunched
10830                        false, //hidden
10831                        null, null, null,
10832                        false // blockUninstall
10833                        );
10834                if (!isSystemApp(ps)) {
10835                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10836                        // Other user still have this package installed, so all
10837                        // we need to do is clear this user's data and save that
10838                        // it is uninstalled.
10839                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10840                        removeUser = user.getIdentifier();
10841                        appId = ps.appId;
10842                        mSettings.writePackageRestrictionsLPr(removeUser);
10843                    } else {
10844                        // We need to set it back to 'installed' so the uninstall
10845                        // broadcasts will be sent correctly.
10846                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10847                        ps.setInstalled(true, user.getIdentifier());
10848                    }
10849                } else {
10850                    // This is a system app, so we assume that the
10851                    // other users still have this package installed, so all
10852                    // we need to do is clear this user's data and save that
10853                    // it is uninstalled.
10854                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10855                    removeUser = user.getIdentifier();
10856                    appId = ps.appId;
10857                    mSettings.writePackageRestrictionsLPr(removeUser);
10858                }
10859            }
10860        }
10861
10862        if (removeUser >= 0) {
10863            // From above, we determined that we are deleting this only
10864            // for a single user.  Continue the work here.
10865            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10866            if (outInfo != null) {
10867                outInfo.removedPackage = packageName;
10868                outInfo.removedAppId = appId;
10869                outInfo.removedUsers = new int[] {removeUser};
10870            }
10871            mInstaller.clearUserData(packageName, removeUser);
10872            removeKeystoreDataIfNeeded(removeUser, appId);
10873            schedulePackageCleaning(packageName, removeUser, false);
10874            return true;
10875        }
10876
10877        if (dataOnly) {
10878            // Delete application data first
10879            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10880            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10881            return true;
10882        }
10883
10884        boolean ret = false;
10885        if (isSystemApp(ps)) {
10886            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10887            // When an updated system application is deleted we delete the existing resources as well and
10888            // fall back to existing code in system partition
10889            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10890                    flags, outInfo, writeSettings);
10891        } else {
10892            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10893            // Kill application pre-emptively especially for apps on sd.
10894            killApplication(packageName, ps.appId, "uninstall pkg");
10895            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10896                    allUserHandles, perUserInstalled,
10897                    outInfo, writeSettings);
10898        }
10899
10900        return ret;
10901    }
10902
10903    private final class ClearStorageConnection implements ServiceConnection {
10904        IMediaContainerService mContainerService;
10905
10906        @Override
10907        public void onServiceConnected(ComponentName name, IBinder service) {
10908            synchronized (this) {
10909                mContainerService = IMediaContainerService.Stub.asInterface(service);
10910                notifyAll();
10911            }
10912        }
10913
10914        @Override
10915        public void onServiceDisconnected(ComponentName name) {
10916        }
10917    }
10918
10919    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10920        final boolean mounted;
10921        if (Environment.isExternalStorageEmulated()) {
10922            mounted = true;
10923        } else {
10924            final String status = Environment.getExternalStorageState();
10925
10926            mounted = status.equals(Environment.MEDIA_MOUNTED)
10927                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10928        }
10929
10930        if (!mounted) {
10931            return;
10932        }
10933
10934        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10935        int[] users;
10936        if (userId == UserHandle.USER_ALL) {
10937            users = sUserManager.getUserIds();
10938        } else {
10939            users = new int[] { userId };
10940        }
10941        final ClearStorageConnection conn = new ClearStorageConnection();
10942        if (mContext.bindServiceAsUser(
10943                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10944            try {
10945                for (int curUser : users) {
10946                    long timeout = SystemClock.uptimeMillis() + 5000;
10947                    synchronized (conn) {
10948                        long now = SystemClock.uptimeMillis();
10949                        while (conn.mContainerService == null && now < timeout) {
10950                            try {
10951                                conn.wait(timeout - now);
10952                            } catch (InterruptedException e) {
10953                            }
10954                        }
10955                    }
10956                    if (conn.mContainerService == null) {
10957                        return;
10958                    }
10959
10960                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10961                    clearDirectory(conn.mContainerService,
10962                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10963                    if (allData) {
10964                        clearDirectory(conn.mContainerService,
10965                                userEnv.buildExternalStorageAppDataDirs(packageName));
10966                        clearDirectory(conn.mContainerService,
10967                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10968                    }
10969                }
10970            } finally {
10971                mContext.unbindService(conn);
10972            }
10973        }
10974    }
10975
10976    @Override
10977    public void clearApplicationUserData(final String packageName,
10978            final IPackageDataObserver observer, final int userId) {
10979        mContext.enforceCallingOrSelfPermission(
10980                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10981        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
10982        // Queue up an async operation since the package deletion may take a little while.
10983        mHandler.post(new Runnable() {
10984            public void run() {
10985                mHandler.removeCallbacks(this);
10986                final boolean succeeded;
10987                synchronized (mInstallLock) {
10988                    succeeded = clearApplicationUserDataLI(packageName, userId);
10989                }
10990                clearExternalStorageDataSync(packageName, userId, true);
10991                if (succeeded) {
10992                    // invoke DeviceStorageMonitor's update method to clear any notifications
10993                    DeviceStorageMonitorInternal
10994                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10995                    if (dsm != null) {
10996                        dsm.checkMemory();
10997                    }
10998                }
10999                if(observer != null) {
11000                    try {
11001                        observer.onRemoveCompleted(packageName, succeeded);
11002                    } catch (RemoteException e) {
11003                        Log.i(TAG, "Observer no longer exists.");
11004                    }
11005                } //end if observer
11006            } //end run
11007        });
11008    }
11009
11010    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11011        if (packageName == null) {
11012            Slog.w(TAG, "Attempt to delete null packageName.");
11013            return false;
11014        }
11015
11016        // Try finding details about the requested package
11017        PackageParser.Package pkg;
11018        synchronized (mPackages) {
11019            pkg = mPackages.get(packageName);
11020            if (pkg == null) {
11021                final PackageSetting ps = mSettings.mPackages.get(packageName);
11022                if (ps != null) {
11023                    pkg = ps.pkg;
11024                }
11025            }
11026        }
11027
11028        if (pkg == null) {
11029            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11030        }
11031
11032        // Always delete data directories for package, even if we found no other
11033        // record of app. This helps users recover from UID mismatches without
11034        // resorting to a full data wipe.
11035        int retCode = mInstaller.clearUserData(packageName, userId);
11036        if (retCode < 0) {
11037            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11038            return false;
11039        }
11040
11041        if (pkg == null) {
11042            return false;
11043        }
11044
11045        if (pkg != null && pkg.applicationInfo != null) {
11046            final int appId = pkg.applicationInfo.uid;
11047            removeKeystoreDataIfNeeded(userId, appId);
11048        }
11049
11050        // Create a native library symlink only if we have native libraries
11051        // and if the native libraries are 32 bit libraries. We do not provide
11052        // this symlink for 64 bit libraries.
11053        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11054                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11055            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11056            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11057                Slog.w(TAG, "Failed linking native library dir");
11058                return false;
11059            }
11060        }
11061
11062        return true;
11063    }
11064
11065    /**
11066     * Remove entries from the keystore daemon. Will only remove it if the
11067     * {@code appId} is valid.
11068     */
11069    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11070        if (appId < 0) {
11071            return;
11072        }
11073
11074        final KeyStore keyStore = KeyStore.getInstance();
11075        if (keyStore != null) {
11076            if (userId == UserHandle.USER_ALL) {
11077                for (final int individual : sUserManager.getUserIds()) {
11078                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11079                }
11080            } else {
11081                keyStore.clearUid(UserHandle.getUid(userId, appId));
11082            }
11083        } else {
11084            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11085        }
11086    }
11087
11088    @Override
11089    public void deleteApplicationCacheFiles(final String packageName,
11090            final IPackageDataObserver observer) {
11091        mContext.enforceCallingOrSelfPermission(
11092                android.Manifest.permission.DELETE_CACHE_FILES, null);
11093        // Queue up an async operation since the package deletion may take a little while.
11094        final int userId = UserHandle.getCallingUserId();
11095        mHandler.post(new Runnable() {
11096            public void run() {
11097                mHandler.removeCallbacks(this);
11098                final boolean succeded;
11099                synchronized (mInstallLock) {
11100                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11101                }
11102                clearExternalStorageDataSync(packageName, userId, false);
11103                if(observer != null) {
11104                    try {
11105                        observer.onRemoveCompleted(packageName, succeded);
11106                    } catch (RemoteException e) {
11107                        Log.i(TAG, "Observer no longer exists.");
11108                    }
11109                } //end if observer
11110            } //end run
11111        });
11112    }
11113
11114    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11115        if (packageName == null) {
11116            Slog.w(TAG, "Attempt to delete null packageName.");
11117            return false;
11118        }
11119        PackageParser.Package p;
11120        synchronized (mPackages) {
11121            p = mPackages.get(packageName);
11122        }
11123        if (p == null) {
11124            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11125            return false;
11126        }
11127        final ApplicationInfo applicationInfo = p.applicationInfo;
11128        if (applicationInfo == null) {
11129            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11130            return false;
11131        }
11132        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11133        if (retCode < 0) {
11134            Slog.w(TAG, "Couldn't remove cache files for package: "
11135                       + packageName + " u" + userId);
11136            return false;
11137        }
11138        return true;
11139    }
11140
11141    @Override
11142    public void getPackageSizeInfo(final String packageName, int userHandle,
11143            final IPackageStatsObserver observer) {
11144        mContext.enforceCallingOrSelfPermission(
11145                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11146        if (packageName == null) {
11147            throw new IllegalArgumentException("Attempt to get size of null packageName");
11148        }
11149
11150        PackageStats stats = new PackageStats(packageName, userHandle);
11151
11152        /*
11153         * Queue up an async operation since the package measurement may take a
11154         * little while.
11155         */
11156        Message msg = mHandler.obtainMessage(INIT_COPY);
11157        msg.obj = new MeasureParams(stats, observer);
11158        mHandler.sendMessage(msg);
11159    }
11160
11161    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11162            PackageStats pStats) {
11163        if (packageName == null) {
11164            Slog.w(TAG, "Attempt to get size of null packageName.");
11165            return false;
11166        }
11167        PackageParser.Package p;
11168        boolean dataOnly = false;
11169        String libDirRoot = null;
11170        String asecPath = null;
11171        PackageSetting ps = null;
11172        synchronized (mPackages) {
11173            p = mPackages.get(packageName);
11174            ps = mSettings.mPackages.get(packageName);
11175            if(p == null) {
11176                dataOnly = true;
11177                if((ps == null) || (ps.pkg == null)) {
11178                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11179                    return false;
11180                }
11181                p = ps.pkg;
11182            }
11183            if (ps != null) {
11184                libDirRoot = ps.legacyNativeLibraryPathString;
11185            }
11186            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11187                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11188                if (secureContainerId != null) {
11189                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11190                }
11191            }
11192        }
11193        String publicSrcDir = null;
11194        if(!dataOnly) {
11195            final ApplicationInfo applicationInfo = p.applicationInfo;
11196            if (applicationInfo == null) {
11197                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11198                return false;
11199            }
11200            if (isForwardLocked(p)) {
11201                publicSrcDir = applicationInfo.getBaseResourcePath();
11202            }
11203        }
11204        // TODO: extend to measure size of split APKs
11205        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11206        // not just the first level.
11207        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11208        // just the primary.
11209        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11210        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11211                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11212        if (res < 0) {
11213            return false;
11214        }
11215
11216        // Fix-up for forward-locked applications in ASEC containers.
11217        if (!isExternal(p)) {
11218            pStats.codeSize += pStats.externalCodeSize;
11219            pStats.externalCodeSize = 0L;
11220        }
11221
11222        return true;
11223    }
11224
11225
11226    @Override
11227    public void addPackageToPreferred(String packageName) {
11228        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11229    }
11230
11231    @Override
11232    public void removePackageFromPreferred(String packageName) {
11233        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11234    }
11235
11236    @Override
11237    public List<PackageInfo> getPreferredPackages(int flags) {
11238        return new ArrayList<PackageInfo>();
11239    }
11240
11241    private int getUidTargetSdkVersionLockedLPr(int uid) {
11242        Object obj = mSettings.getUserIdLPr(uid);
11243        if (obj instanceof SharedUserSetting) {
11244            final SharedUserSetting sus = (SharedUserSetting) obj;
11245            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11246            final Iterator<PackageSetting> it = sus.packages.iterator();
11247            while (it.hasNext()) {
11248                final PackageSetting ps = it.next();
11249                if (ps.pkg != null) {
11250                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11251                    if (v < vers) vers = v;
11252                }
11253            }
11254            return vers;
11255        } else if (obj instanceof PackageSetting) {
11256            final PackageSetting ps = (PackageSetting) obj;
11257            if (ps.pkg != null) {
11258                return ps.pkg.applicationInfo.targetSdkVersion;
11259            }
11260        }
11261        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11262    }
11263
11264    @Override
11265    public void addPreferredActivity(IntentFilter filter, int match,
11266            ComponentName[] set, ComponentName activity, int userId) {
11267        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11268                "Adding preferred");
11269    }
11270
11271    private void addPreferredActivityInternal(IntentFilter filter, int match,
11272            ComponentName[] set, ComponentName activity, boolean always, int userId,
11273            String opname) {
11274        // writer
11275        int callingUid = Binder.getCallingUid();
11276        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11277        if (filter.countActions() == 0) {
11278            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11279            return;
11280        }
11281        synchronized (mPackages) {
11282            if (mContext.checkCallingOrSelfPermission(
11283                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11284                    != PackageManager.PERMISSION_GRANTED) {
11285                if (getUidTargetSdkVersionLockedLPr(callingUid)
11286                        < Build.VERSION_CODES.FROYO) {
11287                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11288                            + callingUid);
11289                    return;
11290                }
11291                mContext.enforceCallingOrSelfPermission(
11292                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11293            }
11294
11295            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11296            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11297                    + userId + ":");
11298            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11299            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11300            mSettings.writePackageRestrictionsLPr(userId);
11301        }
11302    }
11303
11304    @Override
11305    public void replacePreferredActivity(IntentFilter filter, int match,
11306            ComponentName[] set, ComponentName activity, int userId) {
11307        if (filter.countActions() != 1) {
11308            throw new IllegalArgumentException(
11309                    "replacePreferredActivity expects filter to have only 1 action.");
11310        }
11311        if (filter.countDataAuthorities() != 0
11312                || filter.countDataPaths() != 0
11313                || filter.countDataSchemes() > 1
11314                || filter.countDataTypes() != 0) {
11315            throw new IllegalArgumentException(
11316                    "replacePreferredActivity expects filter to have no data authorities, " +
11317                    "paths, or types; and at most one scheme.");
11318        }
11319
11320        final int callingUid = Binder.getCallingUid();
11321        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11322        synchronized (mPackages) {
11323            if (mContext.checkCallingOrSelfPermission(
11324                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11325                    != PackageManager.PERMISSION_GRANTED) {
11326                if (getUidTargetSdkVersionLockedLPr(callingUid)
11327                        < Build.VERSION_CODES.FROYO) {
11328                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11329                            + Binder.getCallingUid());
11330                    return;
11331                }
11332                mContext.enforceCallingOrSelfPermission(
11333                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11334            }
11335
11336            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11337            if (pir != null) {
11338                // Get all of the existing entries that exactly match this filter.
11339                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11340                if (existing != null && existing.size() == 1) {
11341                    PreferredActivity cur = existing.get(0);
11342                    if (DEBUG_PREFERRED) {
11343                        Slog.i(TAG, "Checking replace of preferred:");
11344                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11345                        if (!cur.mPref.mAlways) {
11346                            Slog.i(TAG, "  -- CUR; not mAlways!");
11347                        } else {
11348                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11349                            Slog.i(TAG, "  -- CUR: mSet="
11350                                    + Arrays.toString(cur.mPref.mSetComponents));
11351                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11352                            Slog.i(TAG, "  -- NEW: mMatch="
11353                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11354                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11355                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11356                        }
11357                    }
11358                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11359                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11360                            && cur.mPref.sameSet(set)) {
11361                        if (DEBUG_PREFERRED) {
11362                            Slog.i(TAG, "Replacing with same preferred activity "
11363                                    + cur.mPref.mShortComponent + " for user "
11364                                    + userId + ":");
11365                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11366                        } else {
11367                            Slog.i(TAG, "Replacing with same preferred activity "
11368                                    + cur.mPref.mShortComponent + " for user "
11369                                    + userId);
11370                        }
11371                        return;
11372                    }
11373                }
11374
11375                if (existing != null) {
11376                    if (DEBUG_PREFERRED) {
11377                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11378                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11379                    }
11380                    for (int i = 0; i < existing.size(); i++) {
11381                        PreferredActivity pa = existing.get(i);
11382                        if (DEBUG_PREFERRED) {
11383                            Slog.i(TAG, "Removing existing preferred activity "
11384                                    + pa.mPref.mComponent + ":");
11385                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11386                        }
11387                        pir.removeFilter(pa);
11388                    }
11389                }
11390            }
11391            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11392                    "Replacing preferred");
11393        }
11394    }
11395
11396    @Override
11397    public void clearPackagePreferredActivities(String packageName) {
11398        final int uid = Binder.getCallingUid();
11399        // writer
11400        synchronized (mPackages) {
11401            PackageParser.Package pkg = mPackages.get(packageName);
11402            if (pkg == null || pkg.applicationInfo.uid != uid) {
11403                if (mContext.checkCallingOrSelfPermission(
11404                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11405                        != PackageManager.PERMISSION_GRANTED) {
11406                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11407                            < Build.VERSION_CODES.FROYO) {
11408                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11409                                + Binder.getCallingUid());
11410                        return;
11411                    }
11412                    mContext.enforceCallingOrSelfPermission(
11413                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11414                }
11415            }
11416
11417            int user = UserHandle.getCallingUserId();
11418            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11419                mSettings.writePackageRestrictionsLPr(user);
11420                scheduleWriteSettingsLocked();
11421            }
11422        }
11423    }
11424
11425    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11426    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11427        ArrayList<PreferredActivity> removed = null;
11428        boolean changed = false;
11429        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11430            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11431            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11432            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11433                continue;
11434            }
11435            Iterator<PreferredActivity> it = pir.filterIterator();
11436            while (it.hasNext()) {
11437                PreferredActivity pa = it.next();
11438                // Mark entry for removal only if it matches the package name
11439                // and the entry is of type "always".
11440                if (packageName == null ||
11441                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11442                                && pa.mPref.mAlways)) {
11443                    if (removed == null) {
11444                        removed = new ArrayList<PreferredActivity>();
11445                    }
11446                    removed.add(pa);
11447                }
11448            }
11449            if (removed != null) {
11450                for (int j=0; j<removed.size(); j++) {
11451                    PreferredActivity pa = removed.get(j);
11452                    pir.removeFilter(pa);
11453                }
11454                changed = true;
11455            }
11456        }
11457        return changed;
11458    }
11459
11460    @Override
11461    public void resetPreferredActivities(int userId) {
11462        /* TODO: Actually use userId. Why is it being passed in? */
11463        mContext.enforceCallingOrSelfPermission(
11464                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11465        // writer
11466        synchronized (mPackages) {
11467            int user = UserHandle.getCallingUserId();
11468            clearPackagePreferredActivitiesLPw(null, user);
11469            mSettings.readDefaultPreferredAppsLPw(this, user);
11470            mSettings.writePackageRestrictionsLPr(user);
11471            scheduleWriteSettingsLocked();
11472        }
11473    }
11474
11475    @Override
11476    public int getPreferredActivities(List<IntentFilter> outFilters,
11477            List<ComponentName> outActivities, String packageName) {
11478
11479        int num = 0;
11480        final int userId = UserHandle.getCallingUserId();
11481        // reader
11482        synchronized (mPackages) {
11483            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11484            if (pir != null) {
11485                final Iterator<PreferredActivity> it = pir.filterIterator();
11486                while (it.hasNext()) {
11487                    final PreferredActivity pa = it.next();
11488                    if (packageName == null
11489                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11490                                    && pa.mPref.mAlways)) {
11491                        if (outFilters != null) {
11492                            outFilters.add(new IntentFilter(pa));
11493                        }
11494                        if (outActivities != null) {
11495                            outActivities.add(pa.mPref.mComponent);
11496                        }
11497                    }
11498                }
11499            }
11500        }
11501
11502        return num;
11503    }
11504
11505    @Override
11506    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11507            int userId) {
11508        int callingUid = Binder.getCallingUid();
11509        if (callingUid != Process.SYSTEM_UID) {
11510            throw new SecurityException(
11511                    "addPersistentPreferredActivity can only be run by the system");
11512        }
11513        if (filter.countActions() == 0) {
11514            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11515            return;
11516        }
11517        synchronized (mPackages) {
11518            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11519                    " :");
11520            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11521            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11522                    new PersistentPreferredActivity(filter, activity));
11523            mSettings.writePackageRestrictionsLPr(userId);
11524        }
11525    }
11526
11527    @Override
11528    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11529        int callingUid = Binder.getCallingUid();
11530        if (callingUid != Process.SYSTEM_UID) {
11531            throw new SecurityException(
11532                    "clearPackagePersistentPreferredActivities can only be run by the system");
11533        }
11534        ArrayList<PersistentPreferredActivity> removed = null;
11535        boolean changed = false;
11536        synchronized (mPackages) {
11537            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11538                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11539                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11540                        .valueAt(i);
11541                if (userId != thisUserId) {
11542                    continue;
11543                }
11544                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11545                while (it.hasNext()) {
11546                    PersistentPreferredActivity ppa = it.next();
11547                    // Mark entry for removal only if it matches the package name.
11548                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11549                        if (removed == null) {
11550                            removed = new ArrayList<PersistentPreferredActivity>();
11551                        }
11552                        removed.add(ppa);
11553                    }
11554                }
11555                if (removed != null) {
11556                    for (int j=0; j<removed.size(); j++) {
11557                        PersistentPreferredActivity ppa = removed.get(j);
11558                        ppir.removeFilter(ppa);
11559                    }
11560                    changed = true;
11561                }
11562            }
11563
11564            if (changed) {
11565                mSettings.writePackageRestrictionsLPr(userId);
11566            }
11567        }
11568    }
11569
11570    @Override
11571    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11572            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11573        mContext.enforceCallingOrSelfPermission(
11574                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11575        int callingUid = Binder.getCallingUid();
11576        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11577        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11578        if (intentFilter.countActions() == 0) {
11579            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11580            return;
11581        }
11582        synchronized (mPackages) {
11583            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11584                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11585            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11586            mSettings.writePackageRestrictionsLPr(sourceUserId);
11587        }
11588    }
11589
11590    @Override
11591    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11592            int ownerUserId) {
11593        mContext.enforceCallingOrSelfPermission(
11594                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11595        int callingUid = Binder.getCallingUid();
11596        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11597        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11598        int callingUserId = UserHandle.getUserId(callingUid);
11599        synchronized (mPackages) {
11600            CrossProfileIntentResolver resolver =
11601                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11602            HashSet<CrossProfileIntentFilter> set =
11603                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11604            for (CrossProfileIntentFilter filter : set) {
11605                if (filter.getOwnerPackage().equals(ownerPackage)
11606                        && filter.getOwnerUserId() == callingUserId) {
11607                    resolver.removeFilter(filter);
11608                }
11609            }
11610            mSettings.writePackageRestrictionsLPr(sourceUserId);
11611        }
11612    }
11613
11614    // Enforcing that callingUid is owning pkg on userId
11615    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11616        // The system owns everything.
11617        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11618            return;
11619        }
11620        int callingUserId = UserHandle.getUserId(callingUid);
11621        if (callingUserId != userId) {
11622            throw new SecurityException("calling uid " + callingUid
11623                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11624                    + callingUserId);
11625        }
11626        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11627        if (pi == null) {
11628            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11629                    + callingUserId);
11630        }
11631        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11632            throw new SecurityException("Calling uid " + callingUid
11633                    + " does not own package " + pkg);
11634        }
11635    }
11636
11637    @Override
11638    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11639        Intent intent = new Intent(Intent.ACTION_MAIN);
11640        intent.addCategory(Intent.CATEGORY_HOME);
11641
11642        final int callingUserId = UserHandle.getCallingUserId();
11643        List<ResolveInfo> list = queryIntentActivities(intent, null,
11644                PackageManager.GET_META_DATA, callingUserId);
11645        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11646                true, false, false, callingUserId);
11647
11648        allHomeCandidates.clear();
11649        if (list != null) {
11650            for (ResolveInfo ri : list) {
11651                allHomeCandidates.add(ri);
11652            }
11653        }
11654        return (preferred == null || preferred.activityInfo == null)
11655                ? null
11656                : new ComponentName(preferred.activityInfo.packageName,
11657                        preferred.activityInfo.name);
11658    }
11659
11660    @Override
11661    public void setApplicationEnabledSetting(String appPackageName,
11662            int newState, int flags, int userId, String callingPackage) {
11663        if (!sUserManager.exists(userId)) return;
11664        if (callingPackage == null) {
11665            callingPackage = Integer.toString(Binder.getCallingUid());
11666        }
11667        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11668    }
11669
11670    @Override
11671    public void setComponentEnabledSetting(ComponentName componentName,
11672            int newState, int flags, int userId) {
11673        if (!sUserManager.exists(userId)) return;
11674        setEnabledSetting(componentName.getPackageName(),
11675                componentName.getClassName(), newState, flags, userId, null);
11676    }
11677
11678    private void setEnabledSetting(final String packageName, String className, int newState,
11679            final int flags, int userId, String callingPackage) {
11680        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11681              || newState == COMPONENT_ENABLED_STATE_ENABLED
11682              || newState == COMPONENT_ENABLED_STATE_DISABLED
11683              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11684              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11685            throw new IllegalArgumentException("Invalid new component state: "
11686                    + newState);
11687        }
11688        PackageSetting pkgSetting;
11689        final int uid = Binder.getCallingUid();
11690        final int permission = mContext.checkCallingOrSelfPermission(
11691                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11692        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11693        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11694        boolean sendNow = false;
11695        boolean isApp = (className == null);
11696        String componentName = isApp ? packageName : className;
11697        int packageUid = -1;
11698        ArrayList<String> components;
11699
11700        // writer
11701        synchronized (mPackages) {
11702            pkgSetting = mSettings.mPackages.get(packageName);
11703            if (pkgSetting == null) {
11704                if (className == null) {
11705                    throw new IllegalArgumentException(
11706                            "Unknown package: " + packageName);
11707                }
11708                throw new IllegalArgumentException(
11709                        "Unknown component: " + packageName
11710                        + "/" + className);
11711            }
11712            // Allow root and verify that userId is not being specified by a different user
11713            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11714                throw new SecurityException(
11715                        "Permission Denial: attempt to change component state from pid="
11716                        + Binder.getCallingPid()
11717                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11718            }
11719            if (className == null) {
11720                // We're dealing with an application/package level state change
11721                if (pkgSetting.getEnabled(userId) == newState) {
11722                    // Nothing to do
11723                    return;
11724                }
11725                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11726                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11727                    // Don't care about who enables an app.
11728                    callingPackage = null;
11729                }
11730                pkgSetting.setEnabled(newState, userId, callingPackage);
11731                // pkgSetting.pkg.mSetEnabled = newState;
11732            } else {
11733                // We're dealing with a component level state change
11734                // First, verify that this is a valid class name.
11735                PackageParser.Package pkg = pkgSetting.pkg;
11736                if (pkg == null || !pkg.hasComponentClassName(className)) {
11737                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11738                        throw new IllegalArgumentException("Component class " + className
11739                                + " does not exist in " + packageName);
11740                    } else {
11741                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11742                                + className + " does not exist in " + packageName);
11743                    }
11744                }
11745                switch (newState) {
11746                case COMPONENT_ENABLED_STATE_ENABLED:
11747                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11748                        return;
11749                    }
11750                    break;
11751                case COMPONENT_ENABLED_STATE_DISABLED:
11752                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11753                        return;
11754                    }
11755                    break;
11756                case COMPONENT_ENABLED_STATE_DEFAULT:
11757                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11758                        return;
11759                    }
11760                    break;
11761                default:
11762                    Slog.e(TAG, "Invalid new component state: " + newState);
11763                    return;
11764                }
11765            }
11766            mSettings.writePackageRestrictionsLPr(userId);
11767            components = mPendingBroadcasts.get(userId, packageName);
11768            final boolean newPackage = components == null;
11769            if (newPackage) {
11770                components = new ArrayList<String>();
11771            }
11772            if (!components.contains(componentName)) {
11773                components.add(componentName);
11774            }
11775            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11776                sendNow = true;
11777                // Purge entry from pending broadcast list if another one exists already
11778                // since we are sending one right away.
11779                mPendingBroadcasts.remove(userId, packageName);
11780            } else {
11781                if (newPackage) {
11782                    mPendingBroadcasts.put(userId, packageName, components);
11783                }
11784                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11785                    // Schedule a message
11786                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11787                }
11788            }
11789        }
11790
11791        long callingId = Binder.clearCallingIdentity();
11792        try {
11793            if (sendNow) {
11794                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11795                sendPackageChangedBroadcast(packageName,
11796                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11797            }
11798        } finally {
11799            Binder.restoreCallingIdentity(callingId);
11800        }
11801    }
11802
11803    private void sendPackageChangedBroadcast(String packageName,
11804            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11805        if (DEBUG_INSTALL)
11806            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11807                    + componentNames);
11808        Bundle extras = new Bundle(4);
11809        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11810        String nameList[] = new String[componentNames.size()];
11811        componentNames.toArray(nameList);
11812        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11813        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11814        extras.putInt(Intent.EXTRA_UID, packageUid);
11815        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11816                new int[] {UserHandle.getUserId(packageUid)});
11817    }
11818
11819    @Override
11820    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11821        if (!sUserManager.exists(userId)) return;
11822        final int uid = Binder.getCallingUid();
11823        final int permission = mContext.checkCallingOrSelfPermission(
11824                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11825        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11826        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11827        // writer
11828        synchronized (mPackages) {
11829            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11830                    uid, userId)) {
11831                scheduleWritePackageRestrictionsLocked(userId);
11832            }
11833        }
11834    }
11835
11836    @Override
11837    public String getInstallerPackageName(String packageName) {
11838        // reader
11839        synchronized (mPackages) {
11840            return mSettings.getInstallerPackageNameLPr(packageName);
11841        }
11842    }
11843
11844    @Override
11845    public int getApplicationEnabledSetting(String packageName, int userId) {
11846        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11847        int uid = Binder.getCallingUid();
11848        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11849        // reader
11850        synchronized (mPackages) {
11851            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11852        }
11853    }
11854
11855    @Override
11856    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11857        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11858        int uid = Binder.getCallingUid();
11859        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11860        // reader
11861        synchronized (mPackages) {
11862            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11863        }
11864    }
11865
11866    @Override
11867    public void enterSafeMode() {
11868        enforceSystemOrRoot("Only the system can request entering safe mode");
11869
11870        if (!mSystemReady) {
11871            mSafeMode = true;
11872        }
11873    }
11874
11875    @Override
11876    public void systemReady() {
11877        mSystemReady = true;
11878
11879        // Read the compatibilty setting when the system is ready.
11880        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11881                mContext.getContentResolver(),
11882                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11883        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11884        if (DEBUG_SETTINGS) {
11885            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11886        }
11887
11888        synchronized (mPackages) {
11889            // Verify that all of the preferred activity components actually
11890            // exist.  It is possible for applications to be updated and at
11891            // that point remove a previously declared activity component that
11892            // had been set as a preferred activity.  We try to clean this up
11893            // the next time we encounter that preferred activity, but it is
11894            // possible for the user flow to never be able to return to that
11895            // situation so here we do a sanity check to make sure we haven't
11896            // left any junk around.
11897            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11898            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11899                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11900                removed.clear();
11901                for (PreferredActivity pa : pir.filterSet()) {
11902                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11903                        removed.add(pa);
11904                    }
11905                }
11906                if (removed.size() > 0) {
11907                    for (int r=0; r<removed.size(); r++) {
11908                        PreferredActivity pa = removed.get(r);
11909                        Slog.w(TAG, "Removing dangling preferred activity: "
11910                                + pa.mPref.mComponent);
11911                        pir.removeFilter(pa);
11912                    }
11913                    mSettings.writePackageRestrictionsLPr(
11914                            mSettings.mPreferredActivities.keyAt(i));
11915                }
11916            }
11917        }
11918        sUserManager.systemReady();
11919
11920        // Kick off any messages waiting for system ready
11921        if (mPostSystemReadyMessages != null) {
11922            for (Message msg : mPostSystemReadyMessages) {
11923                msg.sendToTarget();
11924            }
11925            mPostSystemReadyMessages = null;
11926        }
11927    }
11928
11929    @Override
11930    public boolean isSafeMode() {
11931        return mSafeMode;
11932    }
11933
11934    @Override
11935    public boolean hasSystemUidErrors() {
11936        return mHasSystemUidErrors;
11937    }
11938
11939    static String arrayToString(int[] array) {
11940        StringBuffer buf = new StringBuffer(128);
11941        buf.append('[');
11942        if (array != null) {
11943            for (int i=0; i<array.length; i++) {
11944                if (i > 0) buf.append(", ");
11945                buf.append(array[i]);
11946            }
11947        }
11948        buf.append(']');
11949        return buf.toString();
11950    }
11951
11952    static class DumpState {
11953        public static final int DUMP_LIBS = 1 << 0;
11954        public static final int DUMP_FEATURES = 1 << 1;
11955        public static final int DUMP_RESOLVERS = 1 << 2;
11956        public static final int DUMP_PERMISSIONS = 1 << 3;
11957        public static final int DUMP_PACKAGES = 1 << 4;
11958        public static final int DUMP_SHARED_USERS = 1 << 5;
11959        public static final int DUMP_MESSAGES = 1 << 6;
11960        public static final int DUMP_PROVIDERS = 1 << 7;
11961        public static final int DUMP_VERIFIERS = 1 << 8;
11962        public static final int DUMP_PREFERRED = 1 << 9;
11963        public static final int DUMP_PREFERRED_XML = 1 << 10;
11964        public static final int DUMP_KEYSETS = 1 << 11;
11965        public static final int DUMP_VERSION = 1 << 12;
11966        public static final int DUMP_INSTALLS = 1 << 13;
11967
11968        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11969
11970        private int mTypes;
11971
11972        private int mOptions;
11973
11974        private boolean mTitlePrinted;
11975
11976        private SharedUserSetting mSharedUser;
11977
11978        public boolean isDumping(int type) {
11979            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11980                return true;
11981            }
11982
11983            return (mTypes & type) != 0;
11984        }
11985
11986        public void setDump(int type) {
11987            mTypes |= type;
11988        }
11989
11990        public boolean isOptionEnabled(int option) {
11991            return (mOptions & option) != 0;
11992        }
11993
11994        public void setOptionEnabled(int option) {
11995            mOptions |= option;
11996        }
11997
11998        public boolean onTitlePrinted() {
11999            final boolean printed = mTitlePrinted;
12000            mTitlePrinted = true;
12001            return printed;
12002        }
12003
12004        public boolean getTitlePrinted() {
12005            return mTitlePrinted;
12006        }
12007
12008        public void setTitlePrinted(boolean enabled) {
12009            mTitlePrinted = enabled;
12010        }
12011
12012        public SharedUserSetting getSharedUser() {
12013            return mSharedUser;
12014        }
12015
12016        public void setSharedUser(SharedUserSetting user) {
12017            mSharedUser = user;
12018        }
12019    }
12020
12021    @Override
12022    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12023        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12024                != PackageManager.PERMISSION_GRANTED) {
12025            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12026                    + Binder.getCallingPid()
12027                    + ", uid=" + Binder.getCallingUid()
12028                    + " without permission "
12029                    + android.Manifest.permission.DUMP);
12030            return;
12031        }
12032
12033        DumpState dumpState = new DumpState();
12034        boolean fullPreferred = false;
12035        boolean checkin = false;
12036
12037        String packageName = null;
12038
12039        int opti = 0;
12040        while (opti < args.length) {
12041            String opt = args[opti];
12042            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12043                break;
12044            }
12045            opti++;
12046            if ("-a".equals(opt)) {
12047                // Right now we only know how to print all.
12048            } else if ("-h".equals(opt)) {
12049                pw.println("Package manager dump options:");
12050                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12051                pw.println("    --checkin: dump for a checkin");
12052                pw.println("    -f: print details of intent filters");
12053                pw.println("    -h: print this help");
12054                pw.println("  cmd may be one of:");
12055                pw.println("    l[ibraries]: list known shared libraries");
12056                pw.println("    f[ibraries]: list device features");
12057                pw.println("    k[eysets]: print known keysets");
12058                pw.println("    r[esolvers]: dump intent resolvers");
12059                pw.println("    perm[issions]: dump permissions");
12060                pw.println("    pref[erred]: print preferred package settings");
12061                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12062                pw.println("    prov[iders]: dump content providers");
12063                pw.println("    p[ackages]: dump installed packages");
12064                pw.println("    s[hared-users]: dump shared user IDs");
12065                pw.println("    m[essages]: print collected runtime messages");
12066                pw.println("    v[erifiers]: print package verifier info");
12067                pw.println("    version: print database version info");
12068                pw.println("    write: write current settings now");
12069                pw.println("    <package.name>: info about given package");
12070                pw.println("    installs: details about install sessions");
12071                return;
12072            } else if ("--checkin".equals(opt)) {
12073                checkin = true;
12074            } else if ("-f".equals(opt)) {
12075                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12076            } else {
12077                pw.println("Unknown argument: " + opt + "; use -h for help");
12078            }
12079        }
12080
12081        // Is the caller requesting to dump a particular piece of data?
12082        if (opti < args.length) {
12083            String cmd = args[opti];
12084            opti++;
12085            // Is this a package name?
12086            if ("android".equals(cmd) || cmd.contains(".")) {
12087                packageName = cmd;
12088                // When dumping a single package, we always dump all of its
12089                // filter information since the amount of data will be reasonable.
12090                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12091            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12092                dumpState.setDump(DumpState.DUMP_LIBS);
12093            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12094                dumpState.setDump(DumpState.DUMP_FEATURES);
12095            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12096                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12097            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12098                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12099            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12100                dumpState.setDump(DumpState.DUMP_PREFERRED);
12101            } else if ("preferred-xml".equals(cmd)) {
12102                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12103                if (opti < args.length && "--full".equals(args[opti])) {
12104                    fullPreferred = true;
12105                    opti++;
12106                }
12107            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12108                dumpState.setDump(DumpState.DUMP_PACKAGES);
12109            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12110                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12111            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12112                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12113            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12114                dumpState.setDump(DumpState.DUMP_MESSAGES);
12115            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12116                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12117            } else if ("version".equals(cmd)) {
12118                dumpState.setDump(DumpState.DUMP_VERSION);
12119            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12120                dumpState.setDump(DumpState.DUMP_KEYSETS);
12121            } else if ("installs".equals(cmd)) {
12122                dumpState.setDump(DumpState.DUMP_INSTALLS);
12123            } else if ("write".equals(cmd)) {
12124                synchronized (mPackages) {
12125                    mSettings.writeLPr();
12126                    pw.println("Settings written.");
12127                    return;
12128                }
12129            }
12130        }
12131
12132        if (checkin) {
12133            pw.println("vers,1");
12134        }
12135
12136        // reader
12137        synchronized (mPackages) {
12138            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12139                if (!checkin) {
12140                    if (dumpState.onTitlePrinted())
12141                        pw.println();
12142                    pw.println("Database versions:");
12143                    pw.print("  SDK Version:");
12144                    pw.print(" internal=");
12145                    pw.print(mSettings.mInternalSdkPlatform);
12146                    pw.print(" external=");
12147                    pw.println(mSettings.mExternalSdkPlatform);
12148                    pw.print("  DB Version:");
12149                    pw.print(" internal=");
12150                    pw.print(mSettings.mInternalDatabaseVersion);
12151                    pw.print(" external=");
12152                    pw.println(mSettings.mExternalDatabaseVersion);
12153                }
12154            }
12155
12156            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12157                if (!checkin) {
12158                    if (dumpState.onTitlePrinted())
12159                        pw.println();
12160                    pw.println("Verifiers:");
12161                    pw.print("  Required: ");
12162                    pw.print(mRequiredVerifierPackage);
12163                    pw.print(" (uid=");
12164                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12165                    pw.println(")");
12166                } else if (mRequiredVerifierPackage != null) {
12167                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12168                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12169                }
12170            }
12171
12172            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12173                boolean printedHeader = false;
12174                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12175                while (it.hasNext()) {
12176                    String name = it.next();
12177                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12178                    if (!checkin) {
12179                        if (!printedHeader) {
12180                            if (dumpState.onTitlePrinted())
12181                                pw.println();
12182                            pw.println("Libraries:");
12183                            printedHeader = true;
12184                        }
12185                        pw.print("  ");
12186                    } else {
12187                        pw.print("lib,");
12188                    }
12189                    pw.print(name);
12190                    if (!checkin) {
12191                        pw.print(" -> ");
12192                    }
12193                    if (ent.path != null) {
12194                        if (!checkin) {
12195                            pw.print("(jar) ");
12196                            pw.print(ent.path);
12197                        } else {
12198                            pw.print(",jar,");
12199                            pw.print(ent.path);
12200                        }
12201                    } else {
12202                        if (!checkin) {
12203                            pw.print("(apk) ");
12204                            pw.print(ent.apk);
12205                        } else {
12206                            pw.print(",apk,");
12207                            pw.print(ent.apk);
12208                        }
12209                    }
12210                    pw.println();
12211                }
12212            }
12213
12214            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12215                if (dumpState.onTitlePrinted())
12216                    pw.println();
12217                if (!checkin) {
12218                    pw.println("Features:");
12219                }
12220                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12221                while (it.hasNext()) {
12222                    String name = it.next();
12223                    if (!checkin) {
12224                        pw.print("  ");
12225                    } else {
12226                        pw.print("feat,");
12227                    }
12228                    pw.println(name);
12229                }
12230            }
12231
12232            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12233                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12234                        : "Activity Resolver Table:", "  ", packageName,
12235                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12236                    dumpState.setTitlePrinted(true);
12237                }
12238                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12239                        : "Receiver Resolver Table:", "  ", packageName,
12240                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12241                    dumpState.setTitlePrinted(true);
12242                }
12243                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12244                        : "Service Resolver Table:", "  ", packageName,
12245                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12246                    dumpState.setTitlePrinted(true);
12247                }
12248                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12249                        : "Provider Resolver Table:", "  ", packageName,
12250                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12251                    dumpState.setTitlePrinted(true);
12252                }
12253            }
12254
12255            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12256                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12257                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12258                    int user = mSettings.mPreferredActivities.keyAt(i);
12259                    if (pir.dump(pw,
12260                            dumpState.getTitlePrinted()
12261                                ? "\nPreferred Activities User " + user + ":"
12262                                : "Preferred Activities User " + user + ":", "  ",
12263                            packageName, true)) {
12264                        dumpState.setTitlePrinted(true);
12265                    }
12266                }
12267            }
12268
12269            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12270                pw.flush();
12271                FileOutputStream fout = new FileOutputStream(fd);
12272                BufferedOutputStream str = new BufferedOutputStream(fout);
12273                XmlSerializer serializer = new FastXmlSerializer();
12274                try {
12275                    serializer.setOutput(str, "utf-8");
12276                    serializer.startDocument(null, true);
12277                    serializer.setFeature(
12278                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12279                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12280                    serializer.endDocument();
12281                    serializer.flush();
12282                } catch (IllegalArgumentException e) {
12283                    pw.println("Failed writing: " + e);
12284                } catch (IllegalStateException e) {
12285                    pw.println("Failed writing: " + e);
12286                } catch (IOException e) {
12287                    pw.println("Failed writing: " + e);
12288                }
12289            }
12290
12291            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12292                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12293                if (packageName == null) {
12294                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12295                        if (iperm == 0) {
12296                            if (dumpState.onTitlePrinted())
12297                                pw.println();
12298                            pw.println("AppOp Permissions:");
12299                        }
12300                        pw.print("  AppOp Permission ");
12301                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12302                        pw.println(":");
12303                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12304                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12305                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12306                        }
12307                    }
12308                }
12309            }
12310
12311            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12312                boolean printedSomething = false;
12313                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12314                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12315                        continue;
12316                    }
12317                    if (!printedSomething) {
12318                        if (dumpState.onTitlePrinted())
12319                            pw.println();
12320                        pw.println("Registered ContentProviders:");
12321                        printedSomething = true;
12322                    }
12323                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12324                    pw.print("    "); pw.println(p.toString());
12325                }
12326                printedSomething = false;
12327                for (Map.Entry<String, PackageParser.Provider> entry :
12328                        mProvidersByAuthority.entrySet()) {
12329                    PackageParser.Provider p = entry.getValue();
12330                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12331                        continue;
12332                    }
12333                    if (!printedSomething) {
12334                        if (dumpState.onTitlePrinted())
12335                            pw.println();
12336                        pw.println("ContentProvider Authorities:");
12337                        printedSomething = true;
12338                    }
12339                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12340                    pw.print("    "); pw.println(p.toString());
12341                    if (p.info != null && p.info.applicationInfo != null) {
12342                        final String appInfo = p.info.applicationInfo.toString();
12343                        pw.print("      applicationInfo="); pw.println(appInfo);
12344                    }
12345                }
12346            }
12347
12348            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12349                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12350            }
12351
12352            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12353                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12354            }
12355
12356            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12357                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12358            }
12359
12360            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12361                // XXX should handle packageName != null by dumping only install data that
12362                // the given package is involved with.
12363                if (dumpState.onTitlePrinted()) pw.println();
12364                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12365            }
12366
12367            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12368                if (dumpState.onTitlePrinted()) pw.println();
12369                mSettings.dumpReadMessagesLPr(pw, dumpState);
12370
12371                pw.println();
12372                pw.println("Package warning messages:");
12373                final File fname = getSettingsProblemFile();
12374                FileInputStream in = null;
12375                try {
12376                    in = new FileInputStream(fname);
12377                    final int avail = in.available();
12378                    final byte[] data = new byte[avail];
12379                    in.read(data);
12380                    pw.print(new String(data));
12381                } catch (FileNotFoundException e) {
12382                } catch (IOException e) {
12383                } finally {
12384                    if (in != null) {
12385                        try {
12386                            in.close();
12387                        } catch (IOException e) {
12388                        }
12389                    }
12390                }
12391            }
12392        }
12393    }
12394
12395    // ------- apps on sdcard specific code -------
12396    static final boolean DEBUG_SD_INSTALL = false;
12397
12398    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12399
12400    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12401
12402    private boolean mMediaMounted = false;
12403
12404    static String getEncryptKey() {
12405        try {
12406            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12407                    SD_ENCRYPTION_KEYSTORE_NAME);
12408            if (sdEncKey == null) {
12409                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12410                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12411                if (sdEncKey == null) {
12412                    Slog.e(TAG, "Failed to create encryption keys");
12413                    return null;
12414                }
12415            }
12416            return sdEncKey;
12417        } catch (NoSuchAlgorithmException nsae) {
12418            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12419            return null;
12420        } catch (IOException ioe) {
12421            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12422            return null;
12423        }
12424    }
12425
12426    /*
12427     * Update media status on PackageManager.
12428     */
12429    @Override
12430    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12431        int callingUid = Binder.getCallingUid();
12432        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12433            throw new SecurityException("Media status can only be updated by the system");
12434        }
12435        // reader; this apparently protects mMediaMounted, but should probably
12436        // be a different lock in that case.
12437        synchronized (mPackages) {
12438            Log.i(TAG, "Updating external media status from "
12439                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12440                    + (mediaStatus ? "mounted" : "unmounted"));
12441            if (DEBUG_SD_INSTALL)
12442                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12443                        + ", mMediaMounted=" + mMediaMounted);
12444            if (mediaStatus == mMediaMounted) {
12445                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12446                        : 0, -1);
12447                mHandler.sendMessage(msg);
12448                return;
12449            }
12450            mMediaMounted = mediaStatus;
12451        }
12452        // Queue up an async operation since the package installation may take a
12453        // little while.
12454        mHandler.post(new Runnable() {
12455            public void run() {
12456                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12457            }
12458        });
12459    }
12460
12461    /**
12462     * Called by MountService when the initial ASECs to scan are available.
12463     * Should block until all the ASEC containers are finished being scanned.
12464     */
12465    public void scanAvailableAsecs() {
12466        updateExternalMediaStatusInner(true, false, false);
12467        if (mShouldRestoreconData) {
12468            SELinuxMMAC.setRestoreconDone();
12469            mShouldRestoreconData = false;
12470        }
12471    }
12472
12473    /*
12474     * Collect information of applications on external media, map them against
12475     * existing containers and update information based on current mount status.
12476     * Please note that we always have to report status if reportStatus has been
12477     * set to true especially when unloading packages.
12478     */
12479    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12480            boolean externalStorage) {
12481        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12482        int[] uidArr = EmptyArray.INT;
12483
12484        final String[] list = PackageHelper.getSecureContainerList();
12485        if (ArrayUtils.isEmpty(list)) {
12486            Log.i(TAG, "No secure containers found");
12487        } else {
12488            // Process list of secure containers and categorize them
12489            // as active or stale based on their package internal state.
12490
12491            // reader
12492            synchronized (mPackages) {
12493                for (String cid : list) {
12494                    // Leave stages untouched for now; installer service owns them
12495                    if (PackageInstallerService.isStageName(cid)) continue;
12496
12497                    if (DEBUG_SD_INSTALL)
12498                        Log.i(TAG, "Processing container " + cid);
12499                    String pkgName = getAsecPackageName(cid);
12500                    if (pkgName == null) {
12501                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12502                        continue;
12503                    }
12504                    if (DEBUG_SD_INSTALL)
12505                        Log.i(TAG, "Looking for pkg : " + pkgName);
12506
12507                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12508                    if (ps == null) {
12509                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12510                        continue;
12511                    }
12512
12513                    /*
12514                     * Skip packages that are not external if we're unmounting
12515                     * external storage.
12516                     */
12517                    if (externalStorage && !isMounted && !isExternal(ps)) {
12518                        continue;
12519                    }
12520
12521                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12522                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12523                    // The package status is changed only if the code path
12524                    // matches between settings and the container id.
12525                    if (ps.codePathString != null
12526                            && ps.codePathString.startsWith(args.getCodePath())) {
12527                        if (DEBUG_SD_INSTALL) {
12528                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12529                                    + " at code path: " + ps.codePathString);
12530                        }
12531
12532                        // We do have a valid package installed on sdcard
12533                        processCids.put(args, ps.codePathString);
12534                        final int uid = ps.appId;
12535                        if (uid != -1) {
12536                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12537                        }
12538                    } else {
12539                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12540                                + ps.codePathString);
12541                    }
12542                }
12543            }
12544
12545            Arrays.sort(uidArr);
12546        }
12547
12548        // Process packages with valid entries.
12549        if (isMounted) {
12550            if (DEBUG_SD_INSTALL)
12551                Log.i(TAG, "Loading packages");
12552            loadMediaPackages(processCids, uidArr);
12553            startCleaningPackages();
12554            mInstallerService.onSecureContainersAvailable();
12555        } else {
12556            if (DEBUG_SD_INSTALL)
12557                Log.i(TAG, "Unloading packages");
12558            unloadMediaPackages(processCids, uidArr, reportStatus);
12559        }
12560    }
12561
12562    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12563            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12564        int size = pkgList.size();
12565        if (size > 0) {
12566            // Send broadcasts here
12567            Bundle extras = new Bundle();
12568            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12569                    .toArray(new String[size]));
12570            if (uidArr != null) {
12571                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12572            }
12573            if (replacing) {
12574                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12575            }
12576            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12577                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12578            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12579        }
12580    }
12581
12582   /*
12583     * Look at potentially valid container ids from processCids If package
12584     * information doesn't match the one on record or package scanning fails,
12585     * the cid is added to list of removeCids. We currently don't delete stale
12586     * containers.
12587     */
12588    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12589        ArrayList<String> pkgList = new ArrayList<String>();
12590        Set<AsecInstallArgs> keys = processCids.keySet();
12591
12592        for (AsecInstallArgs args : keys) {
12593            String codePath = processCids.get(args);
12594            if (DEBUG_SD_INSTALL)
12595                Log.i(TAG, "Loading container : " + args.cid);
12596            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12597            try {
12598                // Make sure there are no container errors first.
12599                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12600                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12601                            + " when installing from sdcard");
12602                    continue;
12603                }
12604                // Check code path here.
12605                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12606                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12607                            + " does not match one in settings " + codePath);
12608                    continue;
12609                }
12610                // Parse package
12611                int parseFlags = mDefParseFlags;
12612                if (args.isExternal()) {
12613                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12614                }
12615                if (args.isFwdLocked()) {
12616                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12617                }
12618
12619                synchronized (mInstallLock) {
12620                    PackageParser.Package pkg = null;
12621                    try {
12622                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12623                    } catch (PackageManagerException e) {
12624                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12625                    }
12626                    // Scan the package
12627                    if (pkg != null) {
12628                        /*
12629                         * TODO why is the lock being held? doPostInstall is
12630                         * called in other places without the lock. This needs
12631                         * to be straightened out.
12632                         */
12633                        // writer
12634                        synchronized (mPackages) {
12635                            retCode = PackageManager.INSTALL_SUCCEEDED;
12636                            pkgList.add(pkg.packageName);
12637                            // Post process args
12638                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12639                                    pkg.applicationInfo.uid);
12640                        }
12641                    } else {
12642                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12643                    }
12644                }
12645
12646            } finally {
12647                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12648                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12649                }
12650            }
12651        }
12652        // writer
12653        synchronized (mPackages) {
12654            // If the platform SDK has changed since the last time we booted,
12655            // we need to re-grant app permission to catch any new ones that
12656            // appear. This is really a hack, and means that apps can in some
12657            // cases get permissions that the user didn't initially explicitly
12658            // allow... it would be nice to have some better way to handle
12659            // this situation.
12660            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12661            if (regrantPermissions)
12662                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12663                        + mSdkVersion + "; regranting permissions for external storage");
12664            mSettings.mExternalSdkPlatform = mSdkVersion;
12665
12666            // Make sure group IDs have been assigned, and any permission
12667            // changes in other apps are accounted for
12668            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12669                    | (regrantPermissions
12670                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12671                            : 0));
12672
12673            mSettings.updateExternalDatabaseVersion();
12674
12675            // can downgrade to reader
12676            // Persist settings
12677            mSettings.writeLPr();
12678        }
12679        // Send a broadcast to let everyone know we are done processing
12680        if (pkgList.size() > 0) {
12681            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12682        }
12683    }
12684
12685   /*
12686     * Utility method to unload a list of specified containers
12687     */
12688    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12689        // Just unmount all valid containers.
12690        for (AsecInstallArgs arg : cidArgs) {
12691            synchronized (mInstallLock) {
12692                arg.doPostDeleteLI(false);
12693           }
12694       }
12695   }
12696
12697    /*
12698     * Unload packages mounted on external media. This involves deleting package
12699     * data from internal structures, sending broadcasts about diabled packages,
12700     * gc'ing to free up references, unmounting all secure containers
12701     * corresponding to packages on external media, and posting a
12702     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12703     * that we always have to post this message if status has been requested no
12704     * matter what.
12705     */
12706    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12707            final boolean reportStatus) {
12708        if (DEBUG_SD_INSTALL)
12709            Log.i(TAG, "unloading media packages");
12710        ArrayList<String> pkgList = new ArrayList<String>();
12711        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12712        final Set<AsecInstallArgs> keys = processCids.keySet();
12713        for (AsecInstallArgs args : keys) {
12714            String pkgName = args.getPackageName();
12715            if (DEBUG_SD_INSTALL)
12716                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12717            // Delete package internally
12718            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12719            synchronized (mInstallLock) {
12720                boolean res = deletePackageLI(pkgName, null, false, null, null,
12721                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12722                if (res) {
12723                    pkgList.add(pkgName);
12724                } else {
12725                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12726                    failedList.add(args);
12727                }
12728            }
12729        }
12730
12731        // reader
12732        synchronized (mPackages) {
12733            // We didn't update the settings after removing each package;
12734            // write them now for all packages.
12735            mSettings.writeLPr();
12736        }
12737
12738        // We have to absolutely send UPDATED_MEDIA_STATUS only
12739        // after confirming that all the receivers processed the ordered
12740        // broadcast when packages get disabled, force a gc to clean things up.
12741        // and unload all the containers.
12742        if (pkgList.size() > 0) {
12743            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12744                    new IIntentReceiver.Stub() {
12745                public void performReceive(Intent intent, int resultCode, String data,
12746                        Bundle extras, boolean ordered, boolean sticky,
12747                        int sendingUser) throws RemoteException {
12748                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12749                            reportStatus ? 1 : 0, 1, keys);
12750                    mHandler.sendMessage(msg);
12751                }
12752            });
12753        } else {
12754            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12755                    keys);
12756            mHandler.sendMessage(msg);
12757        }
12758    }
12759
12760    /** Binder call */
12761    @Override
12762    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12763            final int flags) {
12764        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12765        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12766        int returnCode = PackageManager.MOVE_SUCCEEDED;
12767        int currInstallFlags = 0;
12768        int newInstallFlags = 0;
12769
12770        File codeFile = null;
12771        String installerPackageName = null;
12772        String packageAbiOverride = null;
12773
12774        // reader
12775        synchronized (mPackages) {
12776            final PackageParser.Package pkg = mPackages.get(packageName);
12777            final PackageSetting ps = mSettings.mPackages.get(packageName);
12778            if (pkg == null || ps == null) {
12779                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12780            } else {
12781                // Disable moving fwd locked apps and system packages
12782                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12783                    Slog.w(TAG, "Cannot move system application");
12784                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12785                } else if (pkg.mOperationPending) {
12786                    Slog.w(TAG, "Attempt to move package which has pending operations");
12787                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12788                } else {
12789                    // Find install location first
12790                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12791                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12792                        Slog.w(TAG, "Ambigous flags specified for move location.");
12793                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12794                    } else {
12795                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12796                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12797                        currInstallFlags = isExternal(pkg)
12798                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12799
12800                        if (newInstallFlags == currInstallFlags) {
12801                            Slog.w(TAG, "No move required. Trying to move to same location");
12802                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12803                        } else {
12804                            if (isForwardLocked(pkg)) {
12805                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12806                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12807                            }
12808                        }
12809                    }
12810                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12811                        pkg.mOperationPending = true;
12812                    }
12813                }
12814
12815                codeFile = new File(pkg.codePath);
12816                installerPackageName = ps.installerPackageName;
12817                packageAbiOverride = ps.cpuAbiOverrideString;
12818            }
12819        }
12820
12821        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12822            try {
12823                observer.packageMoved(packageName, returnCode);
12824            } catch (RemoteException ignored) {
12825            }
12826            return;
12827        }
12828
12829        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12830            @Override
12831            public void onUserActionRequired(Intent intent) throws RemoteException {
12832                throw new IllegalStateException();
12833            }
12834
12835            @Override
12836            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12837                    Bundle extras) throws RemoteException {
12838                Slog.d(TAG, "Install result for move: "
12839                        + PackageManager.installStatusToString(returnCode, msg));
12840
12841                // We usually have a new package now after the install, but if
12842                // we failed we need to clear the pending flag on the original
12843                // package object.
12844                synchronized (mPackages) {
12845                    final PackageParser.Package pkg = mPackages.get(packageName);
12846                    if (pkg != null) {
12847                        pkg.mOperationPending = false;
12848                    }
12849                }
12850
12851                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12852                switch (status) {
12853                    case PackageInstaller.STATUS_SUCCESS:
12854                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12855                        break;
12856                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12857                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12858                        break;
12859                    default:
12860                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12861                        break;
12862                }
12863            }
12864        };
12865
12866        // Treat a move like reinstalling an existing app, which ensures that we
12867        // process everythign uniformly, like unpacking native libraries.
12868        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12869
12870        final Message msg = mHandler.obtainMessage(INIT_COPY);
12871        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12872        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12873                installerPackageName, null, user, packageAbiOverride);
12874        mHandler.sendMessage(msg);
12875    }
12876
12877    @Override
12878    public boolean setInstallLocation(int loc) {
12879        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12880                null);
12881        if (getInstallLocation() == loc) {
12882            return true;
12883        }
12884        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12885                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12886            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12887                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12888            return true;
12889        }
12890        return false;
12891   }
12892
12893    @Override
12894    public int getInstallLocation() {
12895        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12896                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12897                PackageHelper.APP_INSTALL_AUTO);
12898    }
12899
12900    /** Called by UserManagerService */
12901    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12902        mDirtyUsers.remove(userHandle);
12903        mSettings.removeUserLPw(userHandle);
12904        mPendingBroadcasts.remove(userHandle);
12905        if (mInstaller != null) {
12906            // Technically, we shouldn't be doing this with the package lock
12907            // held.  However, this is very rare, and there is already so much
12908            // other disk I/O going on, that we'll let it slide for now.
12909            mInstaller.removeUserDataDirs(userHandle);
12910        }
12911        mUserNeedsBadging.delete(userHandle);
12912        removeUnusedPackagesLILPw(userManager, userHandle);
12913    }
12914
12915    /**
12916     * We're removing userHandle and would like to remove any downloaded packages
12917     * that are no longer in use by any other user.
12918     * @param userHandle the user being removed
12919     */
12920    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12921        final boolean DEBUG_CLEAN_APKS = false;
12922        int [] users = userManager.getUserIdsLPr();
12923        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12924        while (psit.hasNext()) {
12925            PackageSetting ps = psit.next();
12926            if (ps.pkg == null) {
12927                continue;
12928            }
12929            final String packageName = ps.pkg.packageName;
12930            // Skip over if system app
12931            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12932                continue;
12933            }
12934            if (DEBUG_CLEAN_APKS) {
12935                Slog.i(TAG, "Checking package " + packageName);
12936            }
12937            boolean keep = false;
12938            for (int i = 0; i < users.length; i++) {
12939                if (users[i] != userHandle && ps.getInstalled(users[i])) {
12940                    keep = true;
12941                    if (DEBUG_CLEAN_APKS) {
12942                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
12943                                + users[i]);
12944                    }
12945                    break;
12946                }
12947            }
12948            if (!keep) {
12949                if (DEBUG_CLEAN_APKS) {
12950                    Slog.i(TAG, "  Removing package " + packageName);
12951                }
12952                mHandler.post(new Runnable() {
12953                    public void run() {
12954                        deletePackageX(packageName, userHandle, 0);
12955                    } //end run
12956                });
12957            }
12958        }
12959    }
12960
12961    /** Called by UserManagerService */
12962    void createNewUserLILPw(int userHandle, File path) {
12963        if (mInstaller != null) {
12964            mInstaller.createUserConfig(userHandle);
12965            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12966        }
12967    }
12968
12969    @Override
12970    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12971        mContext.enforceCallingOrSelfPermission(
12972                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12973                "Only package verification agents can read the verifier device identity");
12974
12975        synchronized (mPackages) {
12976            return mSettings.getVerifierDeviceIdentityLPw();
12977        }
12978    }
12979
12980    @Override
12981    public void setPermissionEnforced(String permission, boolean enforced) {
12982        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12983        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12984            synchronized (mPackages) {
12985                if (mSettings.mReadExternalStorageEnforced == null
12986                        || mSettings.mReadExternalStorageEnforced != enforced) {
12987                    mSettings.mReadExternalStorageEnforced = enforced;
12988                    mSettings.writeLPr();
12989                }
12990            }
12991            // kill any non-foreground processes so we restart them and
12992            // grant/revoke the GID.
12993            final IActivityManager am = ActivityManagerNative.getDefault();
12994            if (am != null) {
12995                final long token = Binder.clearCallingIdentity();
12996                try {
12997                    am.killProcessesBelowForeground("setPermissionEnforcement");
12998                } catch (RemoteException e) {
12999                } finally {
13000                    Binder.restoreCallingIdentity(token);
13001                }
13002            }
13003        } else {
13004            throw new IllegalArgumentException("No selective enforcement for " + permission);
13005        }
13006    }
13007
13008    @Override
13009    @Deprecated
13010    public boolean isPermissionEnforced(String permission) {
13011        return true;
13012    }
13013
13014    @Override
13015    public boolean isStorageLow() {
13016        final long token = Binder.clearCallingIdentity();
13017        try {
13018            final DeviceStorageMonitorInternal
13019                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13020            if (dsm != null) {
13021                return dsm.isMemoryLow();
13022            } else {
13023                return false;
13024            }
13025        } finally {
13026            Binder.restoreCallingIdentity(token);
13027        }
13028    }
13029
13030    @Override
13031    public IPackageInstaller getPackageInstaller() {
13032        return mInstallerService;
13033    }
13034
13035    private boolean userNeedsBadging(int userId) {
13036        int index = mUserNeedsBadging.indexOfKey(userId);
13037        if (index < 0) {
13038            final UserInfo userInfo;
13039            final long token = Binder.clearCallingIdentity();
13040            try {
13041                userInfo = sUserManager.getUserInfo(userId);
13042            } finally {
13043                Binder.restoreCallingIdentity(token);
13044            }
13045            final boolean b;
13046            if (userInfo != null && userInfo.isManagedProfile()) {
13047                b = true;
13048            } else {
13049                b = false;
13050            }
13051            mUserNeedsBadging.put(userId, b);
13052            return b;
13053        }
13054        return mUserNeedsBadging.valueAt(index);
13055    }
13056
13057    @Override
13058    public KeySet getKeySetByAlias(String packageName, String alias) {
13059        if (packageName == null || alias == null) {
13060            return null;
13061        }
13062        synchronized(mPackages) {
13063            final PackageParser.Package pkg = mPackages.get(packageName);
13064            if (pkg == null) {
13065                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13066                throw new IllegalArgumentException("Unknown package: " + packageName);
13067            }
13068            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13069            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13070        }
13071    }
13072
13073    @Override
13074    public KeySet getSigningKeySet(String packageName) {
13075        if (packageName == null) {
13076            return null;
13077        }
13078        synchronized(mPackages) {
13079            final PackageParser.Package pkg = mPackages.get(packageName);
13080            if (pkg == null) {
13081                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13082                throw new IllegalArgumentException("Unknown package: " + packageName);
13083            }
13084            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13085                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13086                throw new SecurityException("May not access signing KeySet of other apps.");
13087            }
13088            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13089            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13090        }
13091    }
13092
13093    @Override
13094    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13095        if (packageName == null || ks == null) {
13096            return false;
13097        }
13098        synchronized(mPackages) {
13099            final PackageParser.Package pkg = mPackages.get(packageName);
13100            if (pkg == null) {
13101                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13102                throw new IllegalArgumentException("Unknown package: " + packageName);
13103            }
13104            IBinder ksh = ks.getToken();
13105            if (ksh instanceof KeySetHandle) {
13106                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13107                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13108            }
13109            return false;
13110        }
13111    }
13112
13113    @Override
13114    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13115        if (packageName == null || ks == null) {
13116            return false;
13117        }
13118        synchronized(mPackages) {
13119            final PackageParser.Package pkg = mPackages.get(packageName);
13120            if (pkg == null) {
13121                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13122                throw new IllegalArgumentException("Unknown package: " + packageName);
13123            }
13124            IBinder ksh = ks.getToken();
13125            if (ksh instanceof KeySetHandle) {
13126                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13127                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13128            }
13129            return false;
13130        }
13131    }
13132}
13133