PackageManagerService.java revision 7eb599b267d00cbde891c0a87924f2f5086f4497
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.AppGlobals;
84import android.app.IActivityManager;
85import android.app.admin.IDevicePolicyManager;
86import android.app.backup.IBackupManager;
87import android.app.usage.UsageStats;
88import android.app.usage.UsageStatsManager;
89import android.content.BroadcastReceiver;
90import android.content.ComponentName;
91import android.content.Context;
92import android.content.IIntentReceiver;
93import android.content.Intent;
94import android.content.IntentFilter;
95import android.content.IntentSender;
96import android.content.IntentSender.SendIntentException;
97import android.content.ServiceConnection;
98import android.content.pm.ActivityInfo;
99import android.content.pm.ApplicationInfo;
100import android.content.pm.FeatureInfo;
101import android.content.pm.IPackageDataObserver;
102import android.content.pm.IPackageDeleteObserver;
103import android.content.pm.IPackageDeleteObserver2;
104import android.content.pm.IPackageInstallObserver2;
105import android.content.pm.IPackageInstaller;
106import android.content.pm.IPackageManager;
107import android.content.pm.IPackageMoveObserver;
108import android.content.pm.IPackageStatsObserver;
109import android.content.pm.InstrumentationInfo;
110import android.content.pm.KeySet;
111import android.content.pm.ManifestDigest;
112import android.content.pm.PackageCleanItem;
113import android.content.pm.PackageInfo;
114import android.content.pm.PackageInfoLite;
115import android.content.pm.PackageInstaller;
116import android.content.pm.PackageManager;
117import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
118import android.content.pm.PackageParser.ActivityIntentInfo;
119import android.content.pm.PackageParser.PackageLite;
120import android.content.pm.PackageParser.PackageParserException;
121import android.content.pm.PackageParser;
122import android.content.pm.PackageStats;
123import android.content.pm.PackageUserState;
124import android.content.pm.ParceledListSlice;
125import android.content.pm.PermissionGroupInfo;
126import android.content.pm.PermissionInfo;
127import android.content.pm.ProviderInfo;
128import android.content.pm.ResolveInfo;
129import android.content.pm.ServiceInfo;
130import android.content.pm.Signature;
131import android.content.pm.UserInfo;
132import android.content.pm.VerificationParams;
133import android.content.pm.VerifierDeviceIdentity;
134import android.content.pm.VerifierInfo;
135import android.content.res.Resources;
136import android.hardware.display.DisplayManager;
137import android.net.Uri;
138import android.os.Binder;
139import android.os.Build;
140import android.os.Bundle;
141import android.os.Environment;
142import android.os.Environment.UserEnvironment;
143import android.os.storage.StorageManager;
144import android.os.Debug;
145import android.os.FileUtils;
146import android.os.Handler;
147import android.os.IBinder;
148import android.os.Looper;
149import android.os.Message;
150import android.os.Parcel;
151import android.os.ParcelFileDescriptor;
152import android.os.Process;
153import android.os.RemoteException;
154import android.os.SELinux;
155import android.os.ServiceManager;
156import android.os.SystemClock;
157import android.os.SystemProperties;
158import android.os.UserHandle;
159import android.os.UserManager;
160import android.security.KeyStore;
161import android.security.SystemKeyStore;
162import android.system.ErrnoException;
163import android.system.Os;
164import android.system.StructStat;
165import android.text.TextUtils;
166import android.util.ArraySet;
167import android.util.AtomicFile;
168import android.util.DisplayMetrics;
169import android.util.EventLog;
170import android.util.ExceptionUtils;
171import android.util.Log;
172import android.util.LogPrinter;
173import android.util.PrintStreamPrinter;
174import android.util.Slog;
175import android.util.SparseArray;
176import android.util.SparseBooleanArray;
177import android.view.Display;
178
179import java.io.BufferedInputStream;
180import java.io.BufferedOutputStream;
181import java.io.BufferedReader;
182import java.io.File;
183import java.io.FileDescriptor;
184import java.io.FileInputStream;
185import java.io.FileNotFoundException;
186import java.io.FileOutputStream;
187import java.io.FileReader;
188import java.io.FilenameFilter;
189import java.io.IOException;
190import java.io.InputStream;
191import java.io.PrintWriter;
192import java.nio.charset.StandardCharsets;
193import java.security.NoSuchAlgorithmException;
194import java.security.PublicKey;
195import java.security.cert.CertificateEncodingException;
196import java.security.cert.CertificateException;
197import java.text.SimpleDateFormat;
198import java.util.ArrayList;
199import java.util.Arrays;
200import java.util.Collection;
201import java.util.Collections;
202import java.util.Comparator;
203import java.util.Date;
204import java.util.HashMap;
205import java.util.HashSet;
206import java.util.Iterator;
207import java.util.List;
208import java.util.Map;
209import java.util.Objects;
210import java.util.Set;
211import java.util.concurrent.atomic.AtomicBoolean;
212import java.util.concurrent.atomic.AtomicLong;
213
214import dalvik.system.DexFile;
215import dalvik.system.StaleDexCacheError;
216import dalvik.system.VMRuntime;
217
218import libcore.io.IoUtils;
219import libcore.util.EmptyArray;
220
221/**
222 * Keep track of all those .apks everywhere.
223 *
224 * This is very central to the platform's security; please run the unit
225 * tests whenever making modifications here:
226 *
227mmm frameworks/base/tests/AndroidTests
228adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
229adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
230 *
231 * {@hide}
232 */
233public class PackageManagerService extends IPackageManager.Stub {
234    static final String TAG = "PackageManager";
235    static final boolean DEBUG_SETTINGS = false;
236    static final boolean DEBUG_PREFERRED = false;
237    static final boolean DEBUG_UPGRADE = false;
238    private static final boolean DEBUG_INSTALL = false;
239    private static final boolean DEBUG_REMOVE = false;
240    private static final boolean DEBUG_BROADCASTS = false;
241    private static final boolean DEBUG_SHOW_INFO = false;
242    private static final boolean DEBUG_PACKAGE_INFO = false;
243    private static final boolean DEBUG_INTENT_MATCHING = false;
244    private static final boolean DEBUG_PACKAGE_SCANNING = false;
245    private static final boolean DEBUG_VERIFY = false;
246    private static final boolean DEBUG_DEXOPT = false;
247    private static final boolean DEBUG_ABI_SELECTION = false;
248
249    private static final int RADIO_UID = Process.PHONE_UID;
250    private static final int LOG_UID = Process.LOG_UID;
251    private static final int NFC_UID = Process.NFC_UID;
252    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
253    private static final int SHELL_UID = Process.SHELL_UID;
254
255    // Cap the size of permission trees that 3rd party apps can define
256    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
257
258    // Suffix used during package installation when copying/moving
259    // package apks to install directory.
260    private static final String INSTALL_PACKAGE_SUFFIX = "-";
261
262    static final int SCAN_NO_DEX = 1<<1;
263    static final int SCAN_FORCE_DEX = 1<<2;
264    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
265    static final int SCAN_NEW_INSTALL = 1<<4;
266    static final int SCAN_NO_PATHS = 1<<5;
267    static final int SCAN_UPDATE_TIME = 1<<6;
268    static final int SCAN_DEFER_DEX = 1<<7;
269    static final int SCAN_BOOTING = 1<<8;
270    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
271    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
272    static final int SCAN_REPLACING = 1<<11;
273
274    static final int REMOVE_CHATTY = 1<<16;
275
276    /**
277     * Timeout (in milliseconds) after which the watchdog should declare that
278     * our handler thread is wedged.  The usual default for such things is one
279     * minute but we sometimes do very lengthy I/O operations on this thread,
280     * such as installing multi-gigabyte applications, so ours needs to be longer.
281     */
282    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
283
284    /**
285     * Whether verification is enabled by default.
286     */
287    private static final boolean DEFAULT_VERIFY_ENABLE = true;
288
289    /**
290     * The default maximum time to wait for the verification agent to return in
291     * milliseconds.
292     */
293    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
294
295    /**
296     * The default response for package verification timeout.
297     *
298     * This can be either PackageManager.VERIFICATION_ALLOW or
299     * PackageManager.VERIFICATION_REJECT.
300     */
301    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
302
303    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
304
305    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
306            DEFAULT_CONTAINER_PACKAGE,
307            "com.android.defcontainer.DefaultContainerService");
308
309    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
310
311    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
312
313    private static String sPreferredInstructionSet;
314
315    final ServiceThread mHandlerThread;
316
317    private static final String IDMAP_PREFIX = "/data/resource-cache/";
318    private static final String IDMAP_SUFFIX = "@idmap";
319
320    final PackageHandler mHandler;
321
322    /**
323     * Messages for {@link #mHandler} that need to wait for system ready before
324     * being dispatched.
325     */
326    private ArrayList<Message> mPostSystemReadyMessages;
327
328    final int mSdkVersion = Build.VERSION.SDK_INT;
329
330    final Context mContext;
331    final boolean mFactoryTest;
332    final boolean mOnlyCore;
333    final boolean mLazyDexOpt;
334    final long mDexOptLRUThresholdInMills;
335    final DisplayMetrics mMetrics;
336    final int mDefParseFlags;
337    final String[] mSeparateProcesses;
338
339    // This is where all application persistent data goes.
340    final File mAppDataDir;
341
342    // This is where all application persistent data goes for secondary users.
343    final File mUserAppDataDir;
344
345    /** The location for ASEC container files on internal storage. */
346    final String mAsecInternalPath;
347
348    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
349    // LOCK HELD.  Can be called with mInstallLock held.
350    final Installer mInstaller;
351
352    /** Directory where installed third-party apps stored */
353    final File mAppInstallDir;
354
355    /**
356     * Directory to which applications installed internally have their
357     * 32 bit native libraries copied.
358     */
359    private File mAppLib32InstallDir;
360
361    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
362    // apps.
363    final File mDrmAppPrivateInstallDir;
364
365    // ----------------------------------------------------------------
366
367    // Lock for state used when installing and doing other long running
368    // operations.  Methods that must be called with this lock held have
369    // the suffix "LI".
370    final Object mInstallLock = new Object();
371
372    // ----------------------------------------------------------------
373
374    // Keys are String (package name), values are Package.  This also serves
375    // as the lock for the global state.  Methods that must be called with
376    // this lock held have the prefix "LP".
377    final HashMap<String, PackageParser.Package> mPackages =
378            new HashMap<String, PackageParser.Package>();
379
380    // Tracks available target package names -> overlay package paths.
381    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
382        new HashMap<String, HashMap<String, PackageParser.Package>>();
383
384    final Settings mSettings;
385    boolean mRestoredSettings;
386
387    // System configuration read by SystemConfig.
388    final int[] mGlobalGids;
389    final SparseArray<HashSet<String>> mSystemPermissions;
390    final HashMap<String, FeatureInfo> mAvailableFeatures;
391
392    // If mac_permissions.xml was found for seinfo labeling.
393    boolean mFoundPolicyFile;
394
395    // If a recursive restorecon of /data/data/<pkg> is needed.
396    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
397
398    public static final class SharedLibraryEntry {
399        public final String path;
400        public final String apk;
401
402        SharedLibraryEntry(String _path, String _apk) {
403            path = _path;
404            apk = _apk;
405        }
406    }
407
408    // Currently known shared libraries.
409    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
410            new HashMap<String, SharedLibraryEntry>();
411
412    // All available activities, for your resolving pleasure.
413    final ActivityIntentResolver mActivities =
414            new ActivityIntentResolver();
415
416    // All available receivers, for your resolving pleasure.
417    final ActivityIntentResolver mReceivers =
418            new ActivityIntentResolver();
419
420    // All available services, for your resolving pleasure.
421    final ServiceIntentResolver mServices = new ServiceIntentResolver();
422
423    // All available providers, for your resolving pleasure.
424    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
425
426    // Mapping from provider base names (first directory in content URI codePath)
427    // to the provider information.
428    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
429            new HashMap<String, PackageParser.Provider>();
430
431    // Mapping from instrumentation class names to info about them.
432    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
433            new HashMap<ComponentName, PackageParser.Instrumentation>();
434
435    // Mapping from permission names to info about them.
436    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
437            new HashMap<String, PackageParser.PermissionGroup>();
438
439    // Packages whose data we have transfered into another package, thus
440    // should no longer exist.
441    final HashSet<String> mTransferedPackages = new HashSet<String>();
442
443    // Broadcast actions that are only available to the system.
444    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
445
446    /** List of packages waiting for verification. */
447    final SparseArray<PackageVerificationState> mPendingVerification
448            = new SparseArray<PackageVerificationState>();
449
450    /** Set of packages associated with each app op permission. */
451    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
452
453    final PackageInstallerService mInstallerService;
454
455    HashSet<PackageParser.Package> mDeferredDexOpt = null;
456
457    // Cache of users who need badging.
458    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
459
460    /** Token for keys in mPendingVerification. */
461    private int mPendingVerificationToken = 0;
462
463    volatile boolean mSystemReady;
464    volatile boolean mSafeMode;
465    volatile boolean mHasSystemUidErrors;
466
467    ApplicationInfo mAndroidApplication;
468    final ActivityInfo mResolveActivity = new ActivityInfo();
469    final ResolveInfo mResolveInfo = new ResolveInfo();
470    ComponentName mResolveComponentName;
471    PackageParser.Package mPlatformPackage;
472    ComponentName mCustomResolverComponentName;
473
474    boolean mResolverReplaced = false;
475
476    // Set of pending broadcasts for aggregating enable/disable of components.
477    static class PendingPackageBroadcasts {
478        // for each user id, a map of <package name -> components within that package>
479        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
480
481        public PendingPackageBroadcasts() {
482            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
483        }
484
485        public ArrayList<String> get(int userId, String packageName) {
486            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
487            return packages.get(packageName);
488        }
489
490        public void put(int userId, String packageName, ArrayList<String> components) {
491            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
492            packages.put(packageName, components);
493        }
494
495        public void remove(int userId, String packageName) {
496            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
497            if (packages != null) {
498                packages.remove(packageName);
499            }
500        }
501
502        public void remove(int userId) {
503            mUidMap.remove(userId);
504        }
505
506        public int userIdCount() {
507            return mUidMap.size();
508        }
509
510        public int userIdAt(int n) {
511            return mUidMap.keyAt(n);
512        }
513
514        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
515            return mUidMap.get(userId);
516        }
517
518        public int size() {
519            // total number of pending broadcast entries across all userIds
520            int num = 0;
521            for (int i = 0; i< mUidMap.size(); i++) {
522                num += mUidMap.valueAt(i).size();
523            }
524            return num;
525        }
526
527        public void clear() {
528            mUidMap.clear();
529        }
530
531        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
532            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
533            if (map == null) {
534                map = new HashMap<String, ArrayList<String>>();
535                mUidMap.put(userId, map);
536            }
537            return map;
538        }
539    }
540    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
541
542    // Service Connection to remote media container service to copy
543    // package uri's from external media onto secure containers
544    // or internal storage.
545    private IMediaContainerService mContainerService = null;
546
547    static final int SEND_PENDING_BROADCAST = 1;
548    static final int MCS_BOUND = 3;
549    static final int END_COPY = 4;
550    static final int INIT_COPY = 5;
551    static final int MCS_UNBIND = 6;
552    static final int START_CLEANING_PACKAGE = 7;
553    static final int FIND_INSTALL_LOC = 8;
554    static final int POST_INSTALL = 9;
555    static final int MCS_RECONNECT = 10;
556    static final int MCS_GIVE_UP = 11;
557    static final int UPDATED_MEDIA_STATUS = 12;
558    static final int WRITE_SETTINGS = 13;
559    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
560    static final int PACKAGE_VERIFIED = 15;
561    static final int CHECK_PENDING_VERIFICATION = 16;
562
563    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
564
565    // Delay time in millisecs
566    static final int BROADCAST_DELAY = 10 * 1000;
567
568    static UserManagerService sUserManager;
569
570    // Stores a list of users whose package restrictions file needs to be updated
571    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
572
573    final private DefaultContainerConnection mDefContainerConn =
574            new DefaultContainerConnection();
575    class DefaultContainerConnection implements ServiceConnection {
576        public void onServiceConnected(ComponentName name, IBinder service) {
577            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
578            IMediaContainerService imcs =
579                IMediaContainerService.Stub.asInterface(service);
580            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
581        }
582
583        public void onServiceDisconnected(ComponentName name) {
584            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
585        }
586    };
587
588    // Recordkeeping of restore-after-install operations that are currently in flight
589    // between the Package Manager and the Backup Manager
590    class PostInstallData {
591        public InstallArgs args;
592        public PackageInstalledInfo res;
593
594        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
595            args = _a;
596            res = _r;
597        }
598    };
599    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
600    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
601
602    private final String mRequiredVerifierPackage;
603
604    private final PackageUsage mPackageUsage = new PackageUsage();
605
606    private class PackageUsage {
607        private static final int WRITE_INTERVAL
608            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
609
610        private final Object mFileLock = new Object();
611        private final AtomicLong mLastWritten = new AtomicLong(0);
612        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
613
614        private boolean mIsHistoricalPackageUsageAvailable = true;
615
616        boolean isHistoricalPackageUsageAvailable() {
617            return mIsHistoricalPackageUsageAvailable;
618        }
619
620        void write(boolean force) {
621            if (force) {
622                writeInternal();
623                return;
624            }
625            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
626                && !DEBUG_DEXOPT) {
627                return;
628            }
629            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
630                new Thread("PackageUsage_DiskWriter") {
631                    @Override
632                    public void run() {
633                        try {
634                            writeInternal();
635                        } finally {
636                            mBackgroundWriteRunning.set(false);
637                        }
638                    }
639                }.start();
640            }
641        }
642
643        private void writeInternal() {
644            synchronized (mPackages) {
645                synchronized (mFileLock) {
646                    AtomicFile file = getFile();
647                    FileOutputStream f = null;
648                    try {
649                        f = file.startWrite();
650                        BufferedOutputStream out = new BufferedOutputStream(f);
651                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
652                        StringBuilder sb = new StringBuilder();
653                        for (PackageParser.Package pkg : mPackages.values()) {
654                            if (pkg.mLastPackageUsageTimeInMills == 0) {
655                                continue;
656                            }
657                            sb.setLength(0);
658                            sb.append(pkg.packageName);
659                            sb.append(' ');
660                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
661                            sb.append('\n');
662                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
663                        }
664                        out.flush();
665                        file.finishWrite(f);
666                    } catch (IOException e) {
667                        if (f != null) {
668                            file.failWrite(f);
669                        }
670                        Log.e(TAG, "Failed to write package usage times", e);
671                    }
672                }
673            }
674            mLastWritten.set(SystemClock.elapsedRealtime());
675        }
676
677        void readLP() {
678            synchronized (mFileLock) {
679                AtomicFile file = getFile();
680                BufferedInputStream in = null;
681                try {
682                    in = new BufferedInputStream(file.openRead());
683                    StringBuffer sb = new StringBuffer();
684                    while (true) {
685                        String packageName = readToken(in, sb, ' ');
686                        if (packageName == null) {
687                            break;
688                        }
689                        String timeInMillisString = readToken(in, sb, '\n');
690                        if (timeInMillisString == null) {
691                            throw new IOException("Failed to find last usage time for package "
692                                                  + packageName);
693                        }
694                        PackageParser.Package pkg = mPackages.get(packageName);
695                        if (pkg == null) {
696                            continue;
697                        }
698                        long timeInMillis;
699                        try {
700                            timeInMillis = Long.parseLong(timeInMillisString.toString());
701                        } catch (NumberFormatException e) {
702                            throw new IOException("Failed to parse " + timeInMillisString
703                                                  + " as a long.", e);
704                        }
705                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
706                    }
707                } catch (FileNotFoundException expected) {
708                    mIsHistoricalPackageUsageAvailable = false;
709                } catch (IOException e) {
710                    Log.w(TAG, "Failed to read package usage times", e);
711                } finally {
712                    IoUtils.closeQuietly(in);
713                }
714            }
715            mLastWritten.set(SystemClock.elapsedRealtime());
716        }
717
718        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
719                throws IOException {
720            sb.setLength(0);
721            while (true) {
722                int ch = in.read();
723                if (ch == -1) {
724                    if (sb.length() == 0) {
725                        return null;
726                    }
727                    throw new IOException("Unexpected EOF");
728                }
729                if (ch == endOfToken) {
730                    return sb.toString();
731                }
732                sb.append((char)ch);
733            }
734        }
735
736        private AtomicFile getFile() {
737            File dataDir = Environment.getDataDirectory();
738            File systemDir = new File(dataDir, "system");
739            File fname = new File(systemDir, "package-usage.list");
740            return new AtomicFile(fname);
741        }
742    }
743
744    class PackageHandler extends Handler {
745        private boolean mBound = false;
746        final ArrayList<HandlerParams> mPendingInstalls =
747            new ArrayList<HandlerParams>();
748
749        private boolean connectToService() {
750            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
751                    " DefaultContainerService");
752            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
753            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
754            if (mContext.bindServiceAsUser(service, mDefContainerConn,
755                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
756                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
757                mBound = true;
758                return true;
759            }
760            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
761            return false;
762        }
763
764        private void disconnectService() {
765            mContainerService = null;
766            mBound = false;
767            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
768            mContext.unbindService(mDefContainerConn);
769            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
770        }
771
772        PackageHandler(Looper looper) {
773            super(looper);
774        }
775
776        public void handleMessage(Message msg) {
777            try {
778                doHandleMessage(msg);
779            } finally {
780                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781            }
782        }
783
784        void doHandleMessage(Message msg) {
785            switch (msg.what) {
786                case INIT_COPY: {
787                    HandlerParams params = (HandlerParams) msg.obj;
788                    int idx = mPendingInstalls.size();
789                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
790                    // If a bind was already initiated we dont really
791                    // need to do anything. The pending install
792                    // will be processed later on.
793                    if (!mBound) {
794                        // If this is the only one pending we might
795                        // have to bind to the service again.
796                        if (!connectToService()) {
797                            Slog.e(TAG, "Failed to bind to media container service");
798                            params.serviceError();
799                            return;
800                        } else {
801                            // Once we bind to the service, the first
802                            // pending request will be processed.
803                            mPendingInstalls.add(idx, params);
804                        }
805                    } else {
806                        mPendingInstalls.add(idx, params);
807                        // Already bound to the service. Just make
808                        // sure we trigger off processing the first request.
809                        if (idx == 0) {
810                            mHandler.sendEmptyMessage(MCS_BOUND);
811                        }
812                    }
813                    break;
814                }
815                case MCS_BOUND: {
816                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
817                    if (msg.obj != null) {
818                        mContainerService = (IMediaContainerService) msg.obj;
819                    }
820                    if (mContainerService == null) {
821                        // Something seriously wrong. Bail out
822                        Slog.e(TAG, "Cannot bind to media container service");
823                        for (HandlerParams params : mPendingInstalls) {
824                            // Indicate service bind error
825                            params.serviceError();
826                        }
827                        mPendingInstalls.clear();
828                    } else if (mPendingInstalls.size() > 0) {
829                        HandlerParams params = mPendingInstalls.get(0);
830                        if (params != null) {
831                            if (params.startCopy()) {
832                                // We are done...  look for more work or to
833                                // go idle.
834                                if (DEBUG_SD_INSTALL) Log.i(TAG,
835                                        "Checking for more work or unbind...");
836                                // Delete pending install
837                                if (mPendingInstalls.size() > 0) {
838                                    mPendingInstalls.remove(0);
839                                }
840                                if (mPendingInstalls.size() == 0) {
841                                    if (mBound) {
842                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
843                                                "Posting delayed MCS_UNBIND");
844                                        removeMessages(MCS_UNBIND);
845                                        Message ubmsg = obtainMessage(MCS_UNBIND);
846                                        // Unbind after a little delay, to avoid
847                                        // continual thrashing.
848                                        sendMessageDelayed(ubmsg, 10000);
849                                    }
850                                } else {
851                                    // There are more pending requests in queue.
852                                    // Just post MCS_BOUND message to trigger processing
853                                    // of next pending install.
854                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
855                                            "Posting MCS_BOUND for next work");
856                                    mHandler.sendEmptyMessage(MCS_BOUND);
857                                }
858                            }
859                        }
860                    } else {
861                        // Should never happen ideally.
862                        Slog.w(TAG, "Empty queue");
863                    }
864                    break;
865                }
866                case MCS_RECONNECT: {
867                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
868                    if (mPendingInstalls.size() > 0) {
869                        if (mBound) {
870                            disconnectService();
871                        }
872                        if (!connectToService()) {
873                            Slog.e(TAG, "Failed to bind to media container service");
874                            for (HandlerParams params : mPendingInstalls) {
875                                // Indicate service bind error
876                                params.serviceError();
877                            }
878                            mPendingInstalls.clear();
879                        }
880                    }
881                    break;
882                }
883                case MCS_UNBIND: {
884                    // If there is no actual work left, then time to unbind.
885                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
886
887                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
888                        if (mBound) {
889                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
890
891                            disconnectService();
892                        }
893                    } else if (mPendingInstalls.size() > 0) {
894                        // There are more pending requests in queue.
895                        // Just post MCS_BOUND message to trigger processing
896                        // of next pending install.
897                        mHandler.sendEmptyMessage(MCS_BOUND);
898                    }
899
900                    break;
901                }
902                case MCS_GIVE_UP: {
903                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
904                    mPendingInstalls.remove(0);
905                    break;
906                }
907                case SEND_PENDING_BROADCAST: {
908                    String packages[];
909                    ArrayList<String> components[];
910                    int size = 0;
911                    int uids[];
912                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
913                    synchronized (mPackages) {
914                        if (mPendingBroadcasts == null) {
915                            return;
916                        }
917                        size = mPendingBroadcasts.size();
918                        if (size <= 0) {
919                            // Nothing to be done. Just return
920                            return;
921                        }
922                        packages = new String[size];
923                        components = new ArrayList[size];
924                        uids = new int[size];
925                        int i = 0;  // filling out the above arrays
926
927                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
928                            int packageUserId = mPendingBroadcasts.userIdAt(n);
929                            Iterator<Map.Entry<String, ArrayList<String>>> it
930                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
931                                            .entrySet().iterator();
932                            while (it.hasNext() && i < size) {
933                                Map.Entry<String, ArrayList<String>> ent = it.next();
934                                packages[i] = ent.getKey();
935                                components[i] = ent.getValue();
936                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
937                                uids[i] = (ps != null)
938                                        ? UserHandle.getUid(packageUserId, ps.appId)
939                                        : -1;
940                                i++;
941                            }
942                        }
943                        size = i;
944                        mPendingBroadcasts.clear();
945                    }
946                    // Send broadcasts
947                    for (int i = 0; i < size; i++) {
948                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
949                    }
950                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
951                    break;
952                }
953                case START_CLEANING_PACKAGE: {
954                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
955                    final String packageName = (String)msg.obj;
956                    final int userId = msg.arg1;
957                    final boolean andCode = msg.arg2 != 0;
958                    synchronized (mPackages) {
959                        if (userId == UserHandle.USER_ALL) {
960                            int[] users = sUserManager.getUserIds();
961                            for (int user : users) {
962                                mSettings.addPackageToCleanLPw(
963                                        new PackageCleanItem(user, packageName, andCode));
964                            }
965                        } else {
966                            mSettings.addPackageToCleanLPw(
967                                    new PackageCleanItem(userId, packageName, andCode));
968                        }
969                    }
970                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
971                    startCleaningPackages();
972                } break;
973                case POST_INSTALL: {
974                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
975                    PostInstallData data = mRunningInstalls.get(msg.arg1);
976                    mRunningInstalls.delete(msg.arg1);
977                    boolean deleteOld = false;
978
979                    if (data != null) {
980                        InstallArgs args = data.args;
981                        PackageInstalledInfo res = data.res;
982
983                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
984                            res.removedInfo.sendBroadcast(false, true, false);
985                            Bundle extras = new Bundle(1);
986                            extras.putInt(Intent.EXTRA_UID, res.uid);
987                            // Determine the set of users who are adding this
988                            // package for the first time vs. those who are seeing
989                            // an update.
990                            int[] firstUsers;
991                            int[] updateUsers = new int[0];
992                            if (res.origUsers == null || res.origUsers.length == 0) {
993                                firstUsers = res.newUsers;
994                            } else {
995                                firstUsers = new int[0];
996                                for (int i=0; i<res.newUsers.length; i++) {
997                                    int user = res.newUsers[i];
998                                    boolean isNew = true;
999                                    for (int j=0; j<res.origUsers.length; j++) {
1000                                        if (res.origUsers[j] == user) {
1001                                            isNew = false;
1002                                            break;
1003                                        }
1004                                    }
1005                                    if (isNew) {
1006                                        int[] newFirst = new int[firstUsers.length+1];
1007                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1008                                                firstUsers.length);
1009                                        newFirst[firstUsers.length] = user;
1010                                        firstUsers = newFirst;
1011                                    } else {
1012                                        int[] newUpdate = new int[updateUsers.length+1];
1013                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1014                                                updateUsers.length);
1015                                        newUpdate[updateUsers.length] = user;
1016                                        updateUsers = newUpdate;
1017                                    }
1018                                }
1019                            }
1020                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1021                                    res.pkg.applicationInfo.packageName,
1022                                    extras, null, null, firstUsers);
1023                            final boolean update = res.removedInfo.removedPackage != null;
1024                            if (update) {
1025                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1026                            }
1027                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1028                                    res.pkg.applicationInfo.packageName,
1029                                    extras, null, null, updateUsers);
1030                            if (update) {
1031                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1032                                        res.pkg.applicationInfo.packageName,
1033                                        extras, null, null, updateUsers);
1034                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1035                                        null, null,
1036                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1037
1038                                // treat asec-hosted packages like removable media on upgrade
1039                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1040                                    if (DEBUG_INSTALL) {
1041                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1042                                                + " is ASEC-hosted -> AVAILABLE");
1043                                    }
1044                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1045                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1046                                    pkgList.add(res.pkg.applicationInfo.packageName);
1047                                    sendResourcesChangedBroadcast(true, true,
1048                                            pkgList,uidArray, null);
1049                                }
1050                            }
1051                            if (res.removedInfo.args != null) {
1052                                // Remove the replaced package's older resources safely now
1053                                deleteOld = true;
1054                            }
1055
1056                            // Log current value of "unknown sources" setting
1057                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1058                                getUnknownSourcesSettings());
1059                        }
1060                        // Force a gc to clear up things
1061                        Runtime.getRuntime().gc();
1062                        // We delete after a gc for applications  on sdcard.
1063                        if (deleteOld) {
1064                            synchronized (mInstallLock) {
1065                                res.removedInfo.args.doPostDeleteLI(true);
1066                            }
1067                        }
1068                        if (args.observer != null) {
1069                            try {
1070                                Bundle extras = extrasForInstallResult(res);
1071                                args.observer.onPackageInstalled(res.name, res.returnCode,
1072                                        res.returnMsg, extras);
1073                            } catch (RemoteException e) {
1074                                Slog.i(TAG, "Observer no longer exists.");
1075                            }
1076                        }
1077                    } else {
1078                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1079                    }
1080                } break;
1081                case UPDATED_MEDIA_STATUS: {
1082                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1083                    boolean reportStatus = msg.arg1 == 1;
1084                    boolean doGc = msg.arg2 == 1;
1085                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1086                    if (doGc) {
1087                        // Force a gc to clear up stale containers.
1088                        Runtime.getRuntime().gc();
1089                    }
1090                    if (msg.obj != null) {
1091                        @SuppressWarnings("unchecked")
1092                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1093                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1094                        // Unload containers
1095                        unloadAllContainers(args);
1096                    }
1097                    if (reportStatus) {
1098                        try {
1099                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1100                            PackageHelper.getMountService().finishMediaUpdate();
1101                        } catch (RemoteException e) {
1102                            Log.e(TAG, "MountService not running?");
1103                        }
1104                    }
1105                } break;
1106                case WRITE_SETTINGS: {
1107                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1108                    synchronized (mPackages) {
1109                        removeMessages(WRITE_SETTINGS);
1110                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1111                        mSettings.writeLPr();
1112                        mDirtyUsers.clear();
1113                    }
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1115                } break;
1116                case WRITE_PACKAGE_RESTRICTIONS: {
1117                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1118                    synchronized (mPackages) {
1119                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1120                        for (int userId : mDirtyUsers) {
1121                            mSettings.writePackageRestrictionsLPr(userId);
1122                        }
1123                        mDirtyUsers.clear();
1124                    }
1125                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                } break;
1127                case CHECK_PENDING_VERIFICATION: {
1128                    final int verificationId = msg.arg1;
1129                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1130
1131                    if ((state != null) && !state.timeoutExtended()) {
1132                        final InstallArgs args = state.getInstallArgs();
1133                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1134
1135                        Slog.i(TAG, "Verification timed out for " + originUri);
1136                        mPendingVerification.remove(verificationId);
1137
1138                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1139
1140                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1141                            Slog.i(TAG, "Continuing with installation of " + originUri);
1142                            state.setVerifierResponse(Binder.getCallingUid(),
1143                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1144                            broadcastPackageVerified(verificationId, originUri,
1145                                    PackageManager.VERIFICATION_ALLOW,
1146                                    state.getInstallArgs().getUser());
1147                            try {
1148                                ret = args.copyApk(mContainerService, true);
1149                            } catch (RemoteException e) {
1150                                Slog.e(TAG, "Could not contact the ContainerService");
1151                            }
1152                        } else {
1153                            broadcastPackageVerified(verificationId, originUri,
1154                                    PackageManager.VERIFICATION_REJECT,
1155                                    state.getInstallArgs().getUser());
1156                        }
1157
1158                        processPendingInstall(args, ret);
1159                        mHandler.sendEmptyMessage(MCS_UNBIND);
1160                    }
1161                    break;
1162                }
1163                case PACKAGE_VERIFIED: {
1164                    final int verificationId = msg.arg1;
1165
1166                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1167                    if (state == null) {
1168                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1169                        break;
1170                    }
1171
1172                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1173
1174                    state.setVerifierResponse(response.callerUid, response.code);
1175
1176                    if (state.isVerificationComplete()) {
1177                        mPendingVerification.remove(verificationId);
1178
1179                        final InstallArgs args = state.getInstallArgs();
1180                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1181
1182                        int ret;
1183                        if (state.isInstallAllowed()) {
1184                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1185                            broadcastPackageVerified(verificationId, originUri,
1186                                    response.code, state.getInstallArgs().getUser());
1187                            try {
1188                                ret = args.copyApk(mContainerService, true);
1189                            } catch (RemoteException e) {
1190                                Slog.e(TAG, "Could not contact the ContainerService");
1191                            }
1192                        } else {
1193                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1194                        }
1195
1196                        processPendingInstall(args, ret);
1197
1198                        mHandler.sendEmptyMessage(MCS_UNBIND);
1199                    }
1200
1201                    break;
1202                }
1203            }
1204        }
1205    }
1206
1207    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1208        Bundle extras = null;
1209        switch (res.returnCode) {
1210            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1211                extras = new Bundle();
1212                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1213                        res.origPermission);
1214                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1215                        res.origPackage);
1216                break;
1217            }
1218        }
1219        return extras;
1220    }
1221
1222    void scheduleWriteSettingsLocked() {
1223        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1224            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1225        }
1226    }
1227
1228    void scheduleWritePackageRestrictionsLocked(int userId) {
1229        if (!sUserManager.exists(userId)) return;
1230        mDirtyUsers.add(userId);
1231        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1232            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1233        }
1234    }
1235
1236    public static final PackageManagerService main(Context context, Installer installer,
1237            boolean factoryTest, boolean onlyCore) {
1238        PackageManagerService m = new PackageManagerService(context, installer,
1239                factoryTest, onlyCore);
1240        ServiceManager.addService("package", m);
1241        return m;
1242    }
1243
1244    static String[] splitString(String str, char sep) {
1245        int count = 1;
1246        int i = 0;
1247        while ((i=str.indexOf(sep, i)) >= 0) {
1248            count++;
1249            i++;
1250        }
1251
1252        String[] res = new String[count];
1253        i=0;
1254        count = 0;
1255        int lastI=0;
1256        while ((i=str.indexOf(sep, i)) >= 0) {
1257            res[count] = str.substring(lastI, i);
1258            count++;
1259            i++;
1260            lastI = i;
1261        }
1262        res[count] = str.substring(lastI, str.length());
1263        return res;
1264    }
1265
1266    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1267        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1268                Context.DISPLAY_SERVICE);
1269        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1270    }
1271
1272    public PackageManagerService(Context context, Installer installer,
1273            boolean factoryTest, boolean onlyCore) {
1274        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1275                SystemClock.uptimeMillis());
1276
1277        if (mSdkVersion <= 0) {
1278            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1279        }
1280
1281        mContext = context;
1282        mFactoryTest = factoryTest;
1283        mOnlyCore = onlyCore;
1284        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1285        mMetrics = new DisplayMetrics();
1286        mSettings = new Settings(context);
1287        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1296                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1297        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1298                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1299
1300        // TODO: add a property to control this?
1301        long dexOptLRUThresholdInMinutes;
1302        if (mLazyDexOpt) {
1303            dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
1304        } else {
1305            dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
1306        }
1307        mDexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
1308
1309        String separateProcesses = SystemProperties.get("debug.separate_processes");
1310        if (separateProcesses != null && separateProcesses.length() > 0) {
1311            if ("*".equals(separateProcesses)) {
1312                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1313                mSeparateProcesses = null;
1314                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1315            } else {
1316                mDefParseFlags = 0;
1317                mSeparateProcesses = separateProcesses.split(",");
1318                Slog.w(TAG, "Running with debug.separate_processes: "
1319                        + separateProcesses);
1320            }
1321        } else {
1322            mDefParseFlags = 0;
1323            mSeparateProcesses = null;
1324        }
1325
1326        mInstaller = installer;
1327
1328        getDefaultDisplayMetrics(context, mMetrics);
1329
1330        SystemConfig systemConfig = SystemConfig.getInstance();
1331        mGlobalGids = systemConfig.getGlobalGids();
1332        mSystemPermissions = systemConfig.getSystemPermissions();
1333        mAvailableFeatures = systemConfig.getAvailableFeatures();
1334
1335        synchronized (mInstallLock) {
1336        // writer
1337        synchronized (mPackages) {
1338            mHandlerThread = new ServiceThread(TAG,
1339                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1340            mHandlerThread.start();
1341            mHandler = new PackageHandler(mHandlerThread.getLooper());
1342            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1343
1344            File dataDir = Environment.getDataDirectory();
1345            mAppDataDir = new File(dataDir, "data");
1346            mAppInstallDir = new File(dataDir, "app");
1347            mAppLib32InstallDir = new File(dataDir, "app-lib");
1348            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1349            mUserAppDataDir = new File(dataDir, "user");
1350            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1351
1352            sUserManager = new UserManagerService(context, this,
1353                    mInstallLock, mPackages);
1354
1355            // Propagate permission configuration in to package manager.
1356            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1357                    = systemConfig.getPermissions();
1358            for (int i=0; i<permConfig.size(); i++) {
1359                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1360                BasePermission bp = mSettings.mPermissions.get(perm.name);
1361                if (bp == null) {
1362                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1363                    mSettings.mPermissions.put(perm.name, bp);
1364                }
1365                if (perm.gids != null) {
1366                    bp.gids = appendInts(bp.gids, perm.gids);
1367                }
1368            }
1369
1370            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1371            for (int i=0; i<libConfig.size(); i++) {
1372                mSharedLibraries.put(libConfig.keyAt(i),
1373                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1374            }
1375
1376            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1377
1378            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1379                    mSdkVersion, mOnlyCore);
1380
1381            String customResolverActivity = Resources.getSystem().getString(
1382                    R.string.config_customResolverActivity);
1383            if (TextUtils.isEmpty(customResolverActivity)) {
1384                customResolverActivity = null;
1385            } else {
1386                mCustomResolverComponentName = ComponentName.unflattenFromString(
1387                        customResolverActivity);
1388            }
1389
1390            long startTime = SystemClock.uptimeMillis();
1391
1392            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1393                    startTime);
1394
1395            // Set flag to monitor and not change apk file paths when
1396            // scanning install directories.
1397            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1398
1399            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1400
1401            /**
1402             * Add everything in the in the boot class path to the
1403             * list of process files because dexopt will have been run
1404             * if necessary during zygote startup.
1405             */
1406            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1407            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1408
1409            if (bootClassPath != null) {
1410                String[] bootClassPathElements = splitString(bootClassPath, ':');
1411                for (String element : bootClassPathElements) {
1412                    alreadyDexOpted.add(element);
1413                }
1414            } else {
1415                Slog.w(TAG, "No BOOTCLASSPATH found!");
1416            }
1417
1418            if (systemServerClassPath != null) {
1419                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1420                for (String element : systemServerClassPathElements) {
1421                    alreadyDexOpted.add(element);
1422                }
1423            } else {
1424                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1425            }
1426
1427            boolean didDexOptLibraryOrTool = false;
1428
1429            final List<String> allInstructionSets = getAllInstructionSets();
1430            final String[] dexCodeInstructionSets =
1431                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1432
1433            /**
1434             * Ensure all external libraries have had dexopt run on them.
1435             */
1436            if (mSharedLibraries.size() > 0) {
1437                // NOTE: For now, we're compiling these system "shared libraries"
1438                // (and framework jars) into all available architectures. It's possible
1439                // to compile them only when we come across an app that uses them (there's
1440                // already logic for that in scanPackageLI) but that adds some complexity.
1441                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1442                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1443                        final String lib = libEntry.path;
1444                        if (lib == null) {
1445                            continue;
1446                        }
1447
1448                        try {
1449                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1450                                                                                 dexCodeInstructionSet,
1451                                                                                 false);
1452                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1453                                alreadyDexOpted.add(lib);
1454
1455                                // The list of "shared libraries" we have at this point is
1456                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1457                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1458                                } else {
1459                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1460                                }
1461                                didDexOptLibraryOrTool = true;
1462                            }
1463                        } catch (FileNotFoundException e) {
1464                            Slog.w(TAG, "Library not found: " + lib);
1465                        } catch (IOException e) {
1466                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1467                                    + e.getMessage());
1468                        }
1469                    }
1470                }
1471            }
1472
1473            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1474
1475            // Gross hack for now: we know this file doesn't contain any
1476            // code, so don't dexopt it to avoid the resulting log spew.
1477            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1478
1479            // Gross hack for now: we know this file is only part of
1480            // the boot class path for art, so don't dexopt it to
1481            // avoid the resulting log spew.
1482            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1483
1484            /**
1485             * And there are a number of commands implemented in Java, which
1486             * we currently need to do the dexopt on so that they can be
1487             * run from a non-root shell.
1488             */
1489            String[] frameworkFiles = frameworkDir.list();
1490            if (frameworkFiles != null) {
1491                // TODO: We could compile these only for the most preferred ABI. We should
1492                // first double check that the dex files for these commands are not referenced
1493                // by other system apps.
1494                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1495                    for (int i=0; i<frameworkFiles.length; i++) {
1496                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1497                        String path = libPath.getPath();
1498                        // Skip the file if we already did it.
1499                        if (alreadyDexOpted.contains(path)) {
1500                            continue;
1501                        }
1502                        // Skip the file if it is not a type we want to dexopt.
1503                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1504                            continue;
1505                        }
1506                        try {
1507                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1508                                                                                 dexCodeInstructionSet,
1509                                                                                 false);
1510                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1511                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1512                                didDexOptLibraryOrTool = true;
1513                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1514                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1515                                didDexOptLibraryOrTool = true;
1516                            }
1517                        } catch (FileNotFoundException e) {
1518                            Slog.w(TAG, "Jar not found: " + path);
1519                        } catch (IOException e) {
1520                            Slog.w(TAG, "Exception reading jar: " + path, e);
1521                        }
1522                    }
1523                }
1524            }
1525
1526            // Collect vendor overlay packages.
1527            // (Do this before scanning any apps.)
1528            // For security and version matching reason, only consider
1529            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1530            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1531            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1532                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1533
1534            // Find base frameworks (resource packages without code).
1535            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1536                    | PackageParser.PARSE_IS_SYSTEM_DIR
1537                    | PackageParser.PARSE_IS_PRIVILEGED,
1538                    scanFlags | SCAN_NO_DEX, 0);
1539
1540            // Collected privileged system packages.
1541            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1542            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1543                    | PackageParser.PARSE_IS_SYSTEM_DIR
1544                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1545
1546            // Collect ordinary system packages.
1547            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1548            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1549                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1550
1551            // Collect all vendor packages.
1552            File vendorAppDir = new File("/vendor/app");
1553            try {
1554                vendorAppDir = vendorAppDir.getCanonicalFile();
1555            } catch (IOException e) {
1556                // failed to look up canonical path, continue with original one
1557            }
1558            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1559                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1560
1561            // Collect all OEM packages.
1562            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1563            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1564                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1565
1566            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1567            mInstaller.moveFiles();
1568
1569            // Prune any system packages that no longer exist.
1570            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1571            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1572            if (!mOnlyCore) {
1573                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1574                while (psit.hasNext()) {
1575                    PackageSetting ps = psit.next();
1576
1577                    /*
1578                     * If this is not a system app, it can't be a
1579                     * disable system app.
1580                     */
1581                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1582                        continue;
1583                    }
1584
1585                    /*
1586                     * If the package is scanned, it's not erased.
1587                     */
1588                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1589                    if (scannedPkg != null) {
1590                        /*
1591                         * If the system app is both scanned and in the
1592                         * disabled packages list, then it must have been
1593                         * added via OTA. Remove it from the currently
1594                         * scanned package so the previously user-installed
1595                         * application can be scanned.
1596                         */
1597                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1598                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1599                                    + ps.name + "; removing system app.  Last known codePath="
1600                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1601                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1602                                    + scannedPkg.mVersionCode);
1603                            removePackageLI(ps, true);
1604                            expectingBetter.put(ps.name, ps.codePath);
1605                        }
1606
1607                        continue;
1608                    }
1609
1610                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1611                        psit.remove();
1612                        logCriticalInfo(Log.WARN, "System package " + ps.name
1613                                + " no longer exists; wiping its data");
1614                        removeDataDirsLI(ps.name);
1615                    } else {
1616                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1617                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1618                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1619                        }
1620                    }
1621                }
1622            }
1623
1624            //look for any incomplete package installations
1625            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1626            //clean up list
1627            for(int i = 0; i < deletePkgsList.size(); i++) {
1628                //clean up here
1629                cleanupInstallFailedPackage(deletePkgsList.get(i));
1630            }
1631            //delete tmp files
1632            deleteTempPackageFiles();
1633
1634            // Remove any shared userIDs that have no associated packages
1635            mSettings.pruneSharedUsersLPw();
1636
1637            if (!mOnlyCore) {
1638                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1639                        SystemClock.uptimeMillis());
1640                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1641
1642                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1643                        scanFlags, 0);
1644
1645                /**
1646                 * Remove disable package settings for any updated system
1647                 * apps that were removed via an OTA. If they're not a
1648                 * previously-updated app, remove them completely.
1649                 * Otherwise, just revoke their system-level permissions.
1650                 */
1651                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1652                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1653                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1654
1655                    String msg;
1656                    if (deletedPkg == null) {
1657                        msg = "Updated system package " + deletedAppName
1658                                + " no longer exists; wiping its data";
1659                        removeDataDirsLI(deletedAppName);
1660                    } else {
1661                        msg = "Updated system app + " + deletedAppName
1662                                + " no longer present; removing system privileges for "
1663                                + deletedAppName;
1664
1665                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1666
1667                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1668                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1669                    }
1670                    logCriticalInfo(Log.WARN, msg);
1671                }
1672
1673                /**
1674                 * Make sure all system apps that we expected to appear on
1675                 * the userdata partition actually showed up. If they never
1676                 * appeared, crawl back and revive the system version.
1677                 */
1678                for (int i = 0; i < expectingBetter.size(); i++) {
1679                    final String packageName = expectingBetter.keyAt(i);
1680                    if (!mPackages.containsKey(packageName)) {
1681                        final File scanFile = expectingBetter.valueAt(i);
1682
1683                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1684                                + " but never showed up; reverting to system");
1685
1686                        final int reparseFlags;
1687                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1688                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1689                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1690                                    | PackageParser.PARSE_IS_PRIVILEGED;
1691                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1692                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1693                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1694                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1695                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1696                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1697                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1698                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1699                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1700                        } else {
1701                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1702                            continue;
1703                        }
1704
1705                        mSettings.enableSystemPackageLPw(packageName);
1706
1707                        try {
1708                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1709                        } catch (PackageManagerException e) {
1710                            Slog.e(TAG, "Failed to parse original system package: "
1711                                    + e.getMessage());
1712                        }
1713                    }
1714                }
1715            }
1716
1717            // Now that we know all of the shared libraries, update all clients to have
1718            // the correct library paths.
1719            updateAllSharedLibrariesLPw();
1720
1721            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1722                // NOTE: We ignore potential failures here during a system scan (like
1723                // the rest of the commands above) because there's precious little we
1724                // can do about it. A settings error is reported, though.
1725                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1726                        false /* force dexopt */, false /* defer dexopt */);
1727            }
1728
1729            // Now that we know all the packages we are keeping,
1730            // read and update their last usage times.
1731            mPackageUsage.readLP();
1732
1733            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1734                    SystemClock.uptimeMillis());
1735            Slog.i(TAG, "Time to scan packages: "
1736                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1737                    + " seconds");
1738
1739            // If the platform SDK has changed since the last time we booted,
1740            // we need to re-grant app permission to catch any new ones that
1741            // appear.  This is really a hack, and means that apps can in some
1742            // cases get permissions that the user didn't initially explicitly
1743            // allow...  it would be nice to have some better way to handle
1744            // this situation.
1745            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1746                    != mSdkVersion;
1747            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1748                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1749                    + "; regranting permissions for internal storage");
1750            mSettings.mInternalSdkPlatform = mSdkVersion;
1751
1752            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1753                    | (regrantPermissions
1754                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1755                            : 0));
1756
1757            // If this is the first boot, and it is a normal boot, then
1758            // we need to initialize the default preferred apps.
1759            if (!mRestoredSettings && !onlyCore) {
1760                mSettings.readDefaultPreferredAppsLPw(this, 0);
1761            }
1762
1763            // If this is first boot after an OTA, and a normal boot, then
1764            // we need to clear code cache directories.
1765            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1766                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1767                for (String pkgName : mSettings.mPackages.keySet()) {
1768                    deleteCodeCacheDirsLI(pkgName);
1769                }
1770                mSettings.mFingerprint = Build.FINGERPRINT;
1771            }
1772
1773            // All the changes are done during package scanning.
1774            mSettings.updateInternalDatabaseVersion();
1775
1776            // can downgrade to reader
1777            mSettings.writeLPr();
1778
1779            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1780                    SystemClock.uptimeMillis());
1781
1782
1783            mRequiredVerifierPackage = getRequiredVerifierLPr();
1784        } // synchronized (mPackages)
1785        } // synchronized (mInstallLock)
1786
1787        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1788
1789        // Now after opening every single application zip, make sure they
1790        // are all flushed.  Not really needed, but keeps things nice and
1791        // tidy.
1792        Runtime.getRuntime().gc();
1793    }
1794
1795    @Override
1796    public boolean isFirstBoot() {
1797        return !mRestoredSettings;
1798    }
1799
1800    @Override
1801    public boolean isOnlyCoreApps() {
1802        return mOnlyCore;
1803    }
1804
1805    private String getRequiredVerifierLPr() {
1806        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1807        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1808                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1809
1810        String requiredVerifier = null;
1811
1812        final int N = receivers.size();
1813        for (int i = 0; i < N; i++) {
1814            final ResolveInfo info = receivers.get(i);
1815
1816            if (info.activityInfo == null) {
1817                continue;
1818            }
1819
1820            final String packageName = info.activityInfo.packageName;
1821
1822            final PackageSetting ps = mSettings.mPackages.get(packageName);
1823            if (ps == null) {
1824                continue;
1825            }
1826
1827            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1828            if (!gp.grantedPermissions
1829                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1830                continue;
1831            }
1832
1833            if (requiredVerifier != null) {
1834                throw new RuntimeException("There can be only one required verifier");
1835            }
1836
1837            requiredVerifier = packageName;
1838        }
1839
1840        return requiredVerifier;
1841    }
1842
1843    @Override
1844    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1845            throws RemoteException {
1846        try {
1847            return super.onTransact(code, data, reply, flags);
1848        } catch (RuntimeException e) {
1849            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1850                Slog.wtf(TAG, "Package Manager Crash", e);
1851            }
1852            throw e;
1853        }
1854    }
1855
1856    void cleanupInstallFailedPackage(PackageSetting ps) {
1857        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1858
1859        removeDataDirsLI(ps.name);
1860        if (ps.codePath != null) {
1861            if (ps.codePath.isDirectory()) {
1862                FileUtils.deleteContents(ps.codePath);
1863            }
1864            ps.codePath.delete();
1865        }
1866        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1867            if (ps.resourcePath.isDirectory()) {
1868                FileUtils.deleteContents(ps.resourcePath);
1869            }
1870            ps.resourcePath.delete();
1871        }
1872        mSettings.removePackageLPw(ps.name);
1873    }
1874
1875    static int[] appendInts(int[] cur, int[] add) {
1876        if (add == null) return cur;
1877        if (cur == null) return add;
1878        final int N = add.length;
1879        for (int i=0; i<N; i++) {
1880            cur = appendInt(cur, add[i]);
1881        }
1882        return cur;
1883    }
1884
1885    static int[] removeInts(int[] cur, int[] rem) {
1886        if (rem == null) return cur;
1887        if (cur == null) return cur;
1888        final int N = rem.length;
1889        for (int i=0; i<N; i++) {
1890            cur = removeInt(cur, rem[i]);
1891        }
1892        return cur;
1893    }
1894
1895    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1896        if (!sUserManager.exists(userId)) return null;
1897        final PackageSetting ps = (PackageSetting) p.mExtras;
1898        if (ps == null) {
1899            return null;
1900        }
1901        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1902        final PackageUserState state = ps.readUserState(userId);
1903        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1904                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1905                state, userId);
1906    }
1907
1908    @Override
1909    public boolean isPackageAvailable(String packageName, int userId) {
1910        if (!sUserManager.exists(userId)) return false;
1911        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1912        synchronized (mPackages) {
1913            PackageParser.Package p = mPackages.get(packageName);
1914            if (p != null) {
1915                final PackageSetting ps = (PackageSetting) p.mExtras;
1916                if (ps != null) {
1917                    final PackageUserState state = ps.readUserState(userId);
1918                    if (state != null) {
1919                        return PackageParser.isAvailable(state);
1920                    }
1921                }
1922            }
1923        }
1924        return false;
1925    }
1926
1927    @Override
1928    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1929        if (!sUserManager.exists(userId)) return null;
1930        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1931        // reader
1932        synchronized (mPackages) {
1933            PackageParser.Package p = mPackages.get(packageName);
1934            if (DEBUG_PACKAGE_INFO)
1935                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1936            if (p != null) {
1937                return generatePackageInfo(p, flags, userId);
1938            }
1939            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1940                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1941            }
1942        }
1943        return null;
1944    }
1945
1946    @Override
1947    public String[] currentToCanonicalPackageNames(String[] names) {
1948        String[] out = new String[names.length];
1949        // reader
1950        synchronized (mPackages) {
1951            for (int i=names.length-1; i>=0; i--) {
1952                PackageSetting ps = mSettings.mPackages.get(names[i]);
1953                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1954            }
1955        }
1956        return out;
1957    }
1958
1959    @Override
1960    public String[] canonicalToCurrentPackageNames(String[] names) {
1961        String[] out = new String[names.length];
1962        // reader
1963        synchronized (mPackages) {
1964            for (int i=names.length-1; i>=0; i--) {
1965                String cur = mSettings.mRenamedPackages.get(names[i]);
1966                out[i] = cur != null ? cur : names[i];
1967            }
1968        }
1969        return out;
1970    }
1971
1972    @Override
1973    public int getPackageUid(String packageName, int userId) {
1974        if (!sUserManager.exists(userId)) return -1;
1975        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1976        // reader
1977        synchronized (mPackages) {
1978            PackageParser.Package p = mPackages.get(packageName);
1979            if(p != null) {
1980                return UserHandle.getUid(userId, p.applicationInfo.uid);
1981            }
1982            PackageSetting ps = mSettings.mPackages.get(packageName);
1983            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1984                return -1;
1985            }
1986            p = ps.pkg;
1987            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1988        }
1989    }
1990
1991    @Override
1992    public int[] getPackageGids(String packageName) {
1993        // reader
1994        synchronized (mPackages) {
1995            PackageParser.Package p = mPackages.get(packageName);
1996            if (DEBUG_PACKAGE_INFO)
1997                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1998            if (p != null) {
1999                final PackageSetting ps = (PackageSetting)p.mExtras;
2000                return ps.getGids();
2001            }
2002        }
2003        // stupid thing to indicate an error.
2004        return new int[0];
2005    }
2006
2007    static final PermissionInfo generatePermissionInfo(
2008            BasePermission bp, int flags) {
2009        if (bp.perm != null) {
2010            return PackageParser.generatePermissionInfo(bp.perm, flags);
2011        }
2012        PermissionInfo pi = new PermissionInfo();
2013        pi.name = bp.name;
2014        pi.packageName = bp.sourcePackage;
2015        pi.nonLocalizedLabel = bp.name;
2016        pi.protectionLevel = bp.protectionLevel;
2017        return pi;
2018    }
2019
2020    @Override
2021    public PermissionInfo getPermissionInfo(String name, int flags) {
2022        // reader
2023        synchronized (mPackages) {
2024            final BasePermission p = mSettings.mPermissions.get(name);
2025            if (p != null) {
2026                return generatePermissionInfo(p, flags);
2027            }
2028            return null;
2029        }
2030    }
2031
2032    @Override
2033    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2034        // reader
2035        synchronized (mPackages) {
2036            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2037            for (BasePermission p : mSettings.mPermissions.values()) {
2038                if (group == null) {
2039                    if (p.perm == null || p.perm.info.group == null) {
2040                        out.add(generatePermissionInfo(p, flags));
2041                    }
2042                } else {
2043                    if (p.perm != null && group.equals(p.perm.info.group)) {
2044                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2045                    }
2046                }
2047            }
2048
2049            if (out.size() > 0) {
2050                return out;
2051            }
2052            return mPermissionGroups.containsKey(group) ? out : null;
2053        }
2054    }
2055
2056    @Override
2057    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2058        // reader
2059        synchronized (mPackages) {
2060            return PackageParser.generatePermissionGroupInfo(
2061                    mPermissionGroups.get(name), flags);
2062        }
2063    }
2064
2065    @Override
2066    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2067        // reader
2068        synchronized (mPackages) {
2069            final int N = mPermissionGroups.size();
2070            ArrayList<PermissionGroupInfo> out
2071                    = new ArrayList<PermissionGroupInfo>(N);
2072            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2073                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2074            }
2075            return out;
2076        }
2077    }
2078
2079    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2080            int userId) {
2081        if (!sUserManager.exists(userId)) return null;
2082        PackageSetting ps = mSettings.mPackages.get(packageName);
2083        if (ps != null) {
2084            if (ps.pkg == null) {
2085                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2086                        flags, userId);
2087                if (pInfo != null) {
2088                    return pInfo.applicationInfo;
2089                }
2090                return null;
2091            }
2092            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2093                    ps.readUserState(userId), userId);
2094        }
2095        return null;
2096    }
2097
2098    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2099            int userId) {
2100        if (!sUserManager.exists(userId)) return null;
2101        PackageSetting ps = mSettings.mPackages.get(packageName);
2102        if (ps != null) {
2103            PackageParser.Package pkg = ps.pkg;
2104            if (pkg == null) {
2105                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2106                    return null;
2107                }
2108                // Only data remains, so we aren't worried about code paths
2109                pkg = new PackageParser.Package(packageName);
2110                pkg.applicationInfo.packageName = packageName;
2111                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2112                pkg.applicationInfo.dataDir =
2113                        getDataPathForPackage(packageName, 0).getPath();
2114                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2115                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2116            }
2117            return generatePackageInfo(pkg, flags, userId);
2118        }
2119        return null;
2120    }
2121
2122    @Override
2123    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2124        if (!sUserManager.exists(userId)) return null;
2125        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2126        // writer
2127        synchronized (mPackages) {
2128            PackageParser.Package p = mPackages.get(packageName);
2129            if (DEBUG_PACKAGE_INFO) Log.v(
2130                    TAG, "getApplicationInfo " + packageName
2131                    + ": " + p);
2132            if (p != null) {
2133                PackageSetting ps = mSettings.mPackages.get(packageName);
2134                if (ps == null) return null;
2135                // Note: isEnabledLP() does not apply here - always return info
2136                return PackageParser.generateApplicationInfo(
2137                        p, flags, ps.readUserState(userId), userId);
2138            }
2139            if ("android".equals(packageName)||"system".equals(packageName)) {
2140                return mAndroidApplication;
2141            }
2142            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2143                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2144            }
2145        }
2146        return null;
2147    }
2148
2149
2150    @Override
2151    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2152        mContext.enforceCallingOrSelfPermission(
2153                android.Manifest.permission.CLEAR_APP_CACHE, null);
2154        // Queue up an async operation since clearing cache may take a little while.
2155        mHandler.post(new Runnable() {
2156            public void run() {
2157                mHandler.removeCallbacks(this);
2158                int retCode = -1;
2159                synchronized (mInstallLock) {
2160                    retCode = mInstaller.freeCache(freeStorageSize);
2161                    if (retCode < 0) {
2162                        Slog.w(TAG, "Couldn't clear application caches");
2163                    }
2164                }
2165                if (observer != null) {
2166                    try {
2167                        observer.onRemoveCompleted(null, (retCode >= 0));
2168                    } catch (RemoteException e) {
2169                        Slog.w(TAG, "RemoveException when invoking call back");
2170                    }
2171                }
2172            }
2173        });
2174    }
2175
2176    @Override
2177    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2178        mContext.enforceCallingOrSelfPermission(
2179                android.Manifest.permission.CLEAR_APP_CACHE, null);
2180        // Queue up an async operation since clearing cache may take a little while.
2181        mHandler.post(new Runnable() {
2182            public void run() {
2183                mHandler.removeCallbacks(this);
2184                int retCode = -1;
2185                synchronized (mInstallLock) {
2186                    retCode = mInstaller.freeCache(freeStorageSize);
2187                    if (retCode < 0) {
2188                        Slog.w(TAG, "Couldn't clear application caches");
2189                    }
2190                }
2191                if(pi != null) {
2192                    try {
2193                        // Callback via pending intent
2194                        int code = (retCode >= 0) ? 1 : 0;
2195                        pi.sendIntent(null, code, null,
2196                                null, null);
2197                    } catch (SendIntentException e1) {
2198                        Slog.i(TAG, "Failed to send pending intent");
2199                    }
2200                }
2201            }
2202        });
2203    }
2204
2205    void freeStorage(long freeStorageSize) throws IOException {
2206        synchronized (mInstallLock) {
2207            if (mInstaller.freeCache(freeStorageSize) < 0) {
2208                throw new IOException("Failed to free enough space");
2209            }
2210        }
2211    }
2212
2213    @Override
2214    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2215        if (!sUserManager.exists(userId)) return null;
2216        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2217        synchronized (mPackages) {
2218            PackageParser.Activity a = mActivities.mActivities.get(component);
2219
2220            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2221            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2222                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2223                if (ps == null) return null;
2224                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2225                        userId);
2226            }
2227            if (mResolveComponentName.equals(component)) {
2228                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2229                        new PackageUserState(), userId);
2230            }
2231        }
2232        return null;
2233    }
2234
2235    @Override
2236    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2237            String resolvedType) {
2238        synchronized (mPackages) {
2239            PackageParser.Activity a = mActivities.mActivities.get(component);
2240            if (a == null) {
2241                return false;
2242            }
2243            for (int i=0; i<a.intents.size(); i++) {
2244                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2245                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2246                    return true;
2247                }
2248            }
2249            return false;
2250        }
2251    }
2252
2253    @Override
2254    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2255        if (!sUserManager.exists(userId)) return null;
2256        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2257        synchronized (mPackages) {
2258            PackageParser.Activity a = mReceivers.mActivities.get(component);
2259            if (DEBUG_PACKAGE_INFO) Log.v(
2260                TAG, "getReceiverInfo " + component + ": " + a);
2261            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2262                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2263                if (ps == null) return null;
2264                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2265                        userId);
2266            }
2267        }
2268        return null;
2269    }
2270
2271    @Override
2272    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2273        if (!sUserManager.exists(userId)) return null;
2274        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2275        synchronized (mPackages) {
2276            PackageParser.Service s = mServices.mServices.get(component);
2277            if (DEBUG_PACKAGE_INFO) Log.v(
2278                TAG, "getServiceInfo " + component + ": " + s);
2279            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2280                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2281                if (ps == null) return null;
2282                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2283                        userId);
2284            }
2285        }
2286        return null;
2287    }
2288
2289    @Override
2290    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2291        if (!sUserManager.exists(userId)) return null;
2292        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2293        synchronized (mPackages) {
2294            PackageParser.Provider p = mProviders.mProviders.get(component);
2295            if (DEBUG_PACKAGE_INFO) Log.v(
2296                TAG, "getProviderInfo " + component + ": " + p);
2297            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2298                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2299                if (ps == null) return null;
2300                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2301                        userId);
2302            }
2303        }
2304        return null;
2305    }
2306
2307    @Override
2308    public String[] getSystemSharedLibraryNames() {
2309        Set<String> libSet;
2310        synchronized (mPackages) {
2311            libSet = mSharedLibraries.keySet();
2312            int size = libSet.size();
2313            if (size > 0) {
2314                String[] libs = new String[size];
2315                libSet.toArray(libs);
2316                return libs;
2317            }
2318        }
2319        return null;
2320    }
2321
2322    @Override
2323    public FeatureInfo[] getSystemAvailableFeatures() {
2324        Collection<FeatureInfo> featSet;
2325        synchronized (mPackages) {
2326            featSet = mAvailableFeatures.values();
2327            int size = featSet.size();
2328            if (size > 0) {
2329                FeatureInfo[] features = new FeatureInfo[size+1];
2330                featSet.toArray(features);
2331                FeatureInfo fi = new FeatureInfo();
2332                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2333                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2334                features[size] = fi;
2335                return features;
2336            }
2337        }
2338        return null;
2339    }
2340
2341    @Override
2342    public boolean hasSystemFeature(String name) {
2343        synchronized (mPackages) {
2344            return mAvailableFeatures.containsKey(name);
2345        }
2346    }
2347
2348    private void checkValidCaller(int uid, int userId) {
2349        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2350            return;
2351
2352        throw new SecurityException("Caller uid=" + uid
2353                + " is not privileged to communicate with user=" + userId);
2354    }
2355
2356    @Override
2357    public int checkPermission(String permName, String pkgName) {
2358        synchronized (mPackages) {
2359            PackageParser.Package p = mPackages.get(pkgName);
2360            if (p != null && p.mExtras != null) {
2361                PackageSetting ps = (PackageSetting)p.mExtras;
2362                if (ps.sharedUser != null) {
2363                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2364                        return PackageManager.PERMISSION_GRANTED;
2365                    }
2366                } else if (ps.grantedPermissions.contains(permName)) {
2367                    return PackageManager.PERMISSION_GRANTED;
2368                }
2369            }
2370        }
2371        return PackageManager.PERMISSION_DENIED;
2372    }
2373
2374    @Override
2375    public int checkUidPermission(String permName, int uid) {
2376        synchronized (mPackages) {
2377            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2378            if (obj != null) {
2379                GrantedPermissions gp = (GrantedPermissions)obj;
2380                if (gp.grantedPermissions.contains(permName)) {
2381                    return PackageManager.PERMISSION_GRANTED;
2382                }
2383            } else {
2384                HashSet<String> perms = mSystemPermissions.get(uid);
2385                if (perms != null && perms.contains(permName)) {
2386                    return PackageManager.PERMISSION_GRANTED;
2387                }
2388            }
2389        }
2390        return PackageManager.PERMISSION_DENIED;
2391    }
2392
2393    /**
2394     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2395     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2396     * @param checkShell TODO(yamasani):
2397     * @param message the message to log on security exception
2398     */
2399    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2400            boolean checkShell, String message) {
2401        if (userId < 0) {
2402            throw new IllegalArgumentException("Invalid userId " + userId);
2403        }
2404        if (checkShell) {
2405            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2406        }
2407        if (userId == UserHandle.getUserId(callingUid)) return;
2408        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2409            if (requireFullPermission) {
2410                mContext.enforceCallingOrSelfPermission(
2411                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2412            } else {
2413                try {
2414                    mContext.enforceCallingOrSelfPermission(
2415                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2416                } catch (SecurityException se) {
2417                    mContext.enforceCallingOrSelfPermission(
2418                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2419                }
2420            }
2421        }
2422    }
2423
2424    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2425        if (callingUid == Process.SHELL_UID) {
2426            if (userHandle >= 0
2427                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2428                throw new SecurityException("Shell does not have permission to access user "
2429                        + userHandle);
2430            } else if (userHandle < 0) {
2431                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2432                        + Debug.getCallers(3));
2433            }
2434        }
2435    }
2436
2437    private BasePermission findPermissionTreeLP(String permName) {
2438        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2439            if (permName.startsWith(bp.name) &&
2440                    permName.length() > bp.name.length() &&
2441                    permName.charAt(bp.name.length()) == '.') {
2442                return bp;
2443            }
2444        }
2445        return null;
2446    }
2447
2448    private BasePermission checkPermissionTreeLP(String permName) {
2449        if (permName != null) {
2450            BasePermission bp = findPermissionTreeLP(permName);
2451            if (bp != null) {
2452                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2453                    return bp;
2454                }
2455                throw new SecurityException("Calling uid "
2456                        + Binder.getCallingUid()
2457                        + " is not allowed to add to permission tree "
2458                        + bp.name + " owned by uid " + bp.uid);
2459            }
2460        }
2461        throw new SecurityException("No permission tree found for " + permName);
2462    }
2463
2464    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2465        if (s1 == null) {
2466            return s2 == null;
2467        }
2468        if (s2 == null) {
2469            return false;
2470        }
2471        if (s1.getClass() != s2.getClass()) {
2472            return false;
2473        }
2474        return s1.equals(s2);
2475    }
2476
2477    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2478        if (pi1.icon != pi2.icon) return false;
2479        if (pi1.logo != pi2.logo) return false;
2480        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2481        if (!compareStrings(pi1.name, pi2.name)) return false;
2482        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2483        // We'll take care of setting this one.
2484        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2485        // These are not currently stored in settings.
2486        //if (!compareStrings(pi1.group, pi2.group)) return false;
2487        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2488        //if (pi1.labelRes != pi2.labelRes) return false;
2489        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2490        return true;
2491    }
2492
2493    int permissionInfoFootprint(PermissionInfo info) {
2494        int size = info.name.length();
2495        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2496        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2497        return size;
2498    }
2499
2500    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2501        int size = 0;
2502        for (BasePermission perm : mSettings.mPermissions.values()) {
2503            if (perm.uid == tree.uid) {
2504                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2505            }
2506        }
2507        return size;
2508    }
2509
2510    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2511        // We calculate the max size of permissions defined by this uid and throw
2512        // if that plus the size of 'info' would exceed our stated maximum.
2513        if (tree.uid != Process.SYSTEM_UID) {
2514            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2515            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2516                throw new SecurityException("Permission tree size cap exceeded");
2517            }
2518        }
2519    }
2520
2521    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2522        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2523            throw new SecurityException("Label must be specified in permission");
2524        }
2525        BasePermission tree = checkPermissionTreeLP(info.name);
2526        BasePermission bp = mSettings.mPermissions.get(info.name);
2527        boolean added = bp == null;
2528        boolean changed = true;
2529        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2530        if (added) {
2531            enforcePermissionCapLocked(info, tree);
2532            bp = new BasePermission(info.name, tree.sourcePackage,
2533                    BasePermission.TYPE_DYNAMIC);
2534        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2535            throw new SecurityException(
2536                    "Not allowed to modify non-dynamic permission "
2537                    + info.name);
2538        } else {
2539            if (bp.protectionLevel == fixedLevel
2540                    && bp.perm.owner.equals(tree.perm.owner)
2541                    && bp.uid == tree.uid
2542                    && comparePermissionInfos(bp.perm.info, info)) {
2543                changed = false;
2544            }
2545        }
2546        bp.protectionLevel = fixedLevel;
2547        info = new PermissionInfo(info);
2548        info.protectionLevel = fixedLevel;
2549        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2550        bp.perm.info.packageName = tree.perm.info.packageName;
2551        bp.uid = tree.uid;
2552        if (added) {
2553            mSettings.mPermissions.put(info.name, bp);
2554        }
2555        if (changed) {
2556            if (!async) {
2557                mSettings.writeLPr();
2558            } else {
2559                scheduleWriteSettingsLocked();
2560            }
2561        }
2562        return added;
2563    }
2564
2565    @Override
2566    public boolean addPermission(PermissionInfo info) {
2567        synchronized (mPackages) {
2568            return addPermissionLocked(info, false);
2569        }
2570    }
2571
2572    @Override
2573    public boolean addPermissionAsync(PermissionInfo info) {
2574        synchronized (mPackages) {
2575            return addPermissionLocked(info, true);
2576        }
2577    }
2578
2579    @Override
2580    public void removePermission(String name) {
2581        synchronized (mPackages) {
2582            checkPermissionTreeLP(name);
2583            BasePermission bp = mSettings.mPermissions.get(name);
2584            if (bp != null) {
2585                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2586                    throw new SecurityException(
2587                            "Not allowed to modify non-dynamic permission "
2588                            + name);
2589                }
2590                mSettings.mPermissions.remove(name);
2591                mSettings.writeLPr();
2592            }
2593        }
2594    }
2595
2596    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2597        int index = pkg.requestedPermissions.indexOf(bp.name);
2598        if (index == -1) {
2599            throw new SecurityException("Package " + pkg.packageName
2600                    + " has not requested permission " + bp.name);
2601        }
2602        boolean isNormal =
2603                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2604                        == PermissionInfo.PROTECTION_NORMAL);
2605        boolean isDangerous =
2606                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2607                        == PermissionInfo.PROTECTION_DANGEROUS);
2608        boolean isDevelopment =
2609                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2610
2611        if (!isNormal && !isDangerous && !isDevelopment) {
2612            throw new SecurityException("Permission " + bp.name
2613                    + " is not a changeable permission type");
2614        }
2615
2616        if (isNormal || isDangerous) {
2617            if (pkg.requestedPermissionsRequired.get(index)) {
2618                throw new SecurityException("Can't change " + bp.name
2619                        + ". It is required by the application");
2620            }
2621        }
2622    }
2623
2624    @Override
2625    public void grantPermission(String packageName, String permissionName) {
2626        mContext.enforceCallingOrSelfPermission(
2627                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2628        synchronized (mPackages) {
2629            final PackageParser.Package pkg = mPackages.get(packageName);
2630            if (pkg == null) {
2631                throw new IllegalArgumentException("Unknown package: " + packageName);
2632            }
2633            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2634            if (bp == null) {
2635                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2636            }
2637
2638            checkGrantRevokePermissions(pkg, bp);
2639
2640            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2641            if (ps == null) {
2642                return;
2643            }
2644            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2645            if (gp.grantedPermissions.add(permissionName)) {
2646                if (ps.haveGids) {
2647                    gp.gids = appendInts(gp.gids, bp.gids);
2648                }
2649                mSettings.writeLPr();
2650            }
2651        }
2652    }
2653
2654    @Override
2655    public void revokePermission(String packageName, String permissionName) {
2656        int changedAppId = -1;
2657
2658        synchronized (mPackages) {
2659            final PackageParser.Package pkg = mPackages.get(packageName);
2660            if (pkg == null) {
2661                throw new IllegalArgumentException("Unknown package: " + packageName);
2662            }
2663            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2664                mContext.enforceCallingOrSelfPermission(
2665                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2666            }
2667            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2668            if (bp == null) {
2669                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2670            }
2671
2672            checkGrantRevokePermissions(pkg, bp);
2673
2674            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2675            if (ps == null) {
2676                return;
2677            }
2678            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2679            if (gp.grantedPermissions.remove(permissionName)) {
2680                gp.grantedPermissions.remove(permissionName);
2681                if (ps.haveGids) {
2682                    gp.gids = removeInts(gp.gids, bp.gids);
2683                }
2684                mSettings.writeLPr();
2685                changedAppId = ps.appId;
2686            }
2687        }
2688
2689        if (changedAppId >= 0) {
2690            // We changed the perm on someone, kill its processes.
2691            IActivityManager am = ActivityManagerNative.getDefault();
2692            if (am != null) {
2693                final int callingUserId = UserHandle.getCallingUserId();
2694                final long ident = Binder.clearCallingIdentity();
2695                try {
2696                    //XXX we should only revoke for the calling user's app permissions,
2697                    // but for now we impact all users.
2698                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2699                    //        "revoke " + permissionName);
2700                    int[] users = sUserManager.getUserIds();
2701                    for (int user : users) {
2702                        am.killUid(UserHandle.getUid(user, changedAppId),
2703                                "revoke " + permissionName);
2704                    }
2705                } catch (RemoteException e) {
2706                } finally {
2707                    Binder.restoreCallingIdentity(ident);
2708                }
2709            }
2710        }
2711    }
2712
2713    @Override
2714    public boolean isProtectedBroadcast(String actionName) {
2715        synchronized (mPackages) {
2716            return mProtectedBroadcasts.contains(actionName);
2717        }
2718    }
2719
2720    @Override
2721    public int checkSignatures(String pkg1, String pkg2) {
2722        synchronized (mPackages) {
2723            final PackageParser.Package p1 = mPackages.get(pkg1);
2724            final PackageParser.Package p2 = mPackages.get(pkg2);
2725            if (p1 == null || p1.mExtras == null
2726                    || p2 == null || p2.mExtras == null) {
2727                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2728            }
2729            return compareSignatures(p1.mSignatures, p2.mSignatures);
2730        }
2731    }
2732
2733    @Override
2734    public int checkUidSignatures(int uid1, int uid2) {
2735        // Map to base uids.
2736        uid1 = UserHandle.getAppId(uid1);
2737        uid2 = UserHandle.getAppId(uid2);
2738        // reader
2739        synchronized (mPackages) {
2740            Signature[] s1;
2741            Signature[] s2;
2742            Object obj = mSettings.getUserIdLPr(uid1);
2743            if (obj != null) {
2744                if (obj instanceof SharedUserSetting) {
2745                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2746                } else if (obj instanceof PackageSetting) {
2747                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2748                } else {
2749                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2750                }
2751            } else {
2752                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2753            }
2754            obj = mSettings.getUserIdLPr(uid2);
2755            if (obj != null) {
2756                if (obj instanceof SharedUserSetting) {
2757                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2758                } else if (obj instanceof PackageSetting) {
2759                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2760                } else {
2761                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2762                }
2763            } else {
2764                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2765            }
2766            return compareSignatures(s1, s2);
2767        }
2768    }
2769
2770    /**
2771     * Compares two sets of signatures. Returns:
2772     * <br />
2773     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2774     * <br />
2775     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2776     * <br />
2777     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2778     * <br />
2779     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2780     * <br />
2781     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2782     */
2783    static int compareSignatures(Signature[] s1, Signature[] s2) {
2784        if (s1 == null) {
2785            return s2 == null
2786                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2787                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2788        }
2789
2790        if (s2 == null) {
2791            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2792        }
2793
2794        if (s1.length != s2.length) {
2795            return PackageManager.SIGNATURE_NO_MATCH;
2796        }
2797
2798        // Since both signature sets are of size 1, we can compare without HashSets.
2799        if (s1.length == 1) {
2800            return s1[0].equals(s2[0]) ?
2801                    PackageManager.SIGNATURE_MATCH :
2802                    PackageManager.SIGNATURE_NO_MATCH;
2803        }
2804
2805        HashSet<Signature> set1 = new HashSet<Signature>();
2806        for (Signature sig : s1) {
2807            set1.add(sig);
2808        }
2809        HashSet<Signature> set2 = new HashSet<Signature>();
2810        for (Signature sig : s2) {
2811            set2.add(sig);
2812        }
2813        // Make sure s2 contains all signatures in s1.
2814        if (set1.equals(set2)) {
2815            return PackageManager.SIGNATURE_MATCH;
2816        }
2817        return PackageManager.SIGNATURE_NO_MATCH;
2818    }
2819
2820    /**
2821     * If the database version for this type of package (internal storage or
2822     * external storage) is less than the version where package signatures
2823     * were updated, return true.
2824     */
2825    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2826        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2827                DatabaseVersion.SIGNATURE_END_ENTITY))
2828                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2829                        DatabaseVersion.SIGNATURE_END_ENTITY));
2830    }
2831
2832    /**
2833     * Used for backward compatibility to make sure any packages with
2834     * certificate chains get upgraded to the new style. {@code existingSigs}
2835     * will be in the old format (since they were stored on disk from before the
2836     * system upgrade) and {@code scannedSigs} will be in the newer format.
2837     */
2838    private int compareSignaturesCompat(PackageSignatures existingSigs,
2839            PackageParser.Package scannedPkg) {
2840        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2841            return PackageManager.SIGNATURE_NO_MATCH;
2842        }
2843
2844        HashSet<Signature> existingSet = new HashSet<Signature>();
2845        for (Signature sig : existingSigs.mSignatures) {
2846            existingSet.add(sig);
2847        }
2848        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2849        for (Signature sig : scannedPkg.mSignatures) {
2850            try {
2851                Signature[] chainSignatures = sig.getChainSignatures();
2852                for (Signature chainSig : chainSignatures) {
2853                    scannedCompatSet.add(chainSig);
2854                }
2855            } catch (CertificateEncodingException e) {
2856                scannedCompatSet.add(sig);
2857            }
2858        }
2859        /*
2860         * Make sure the expanded scanned set contains all signatures in the
2861         * existing one.
2862         */
2863        if (scannedCompatSet.equals(existingSet)) {
2864            // Migrate the old signatures to the new scheme.
2865            existingSigs.assignSignatures(scannedPkg.mSignatures);
2866            // The new KeySets will be re-added later in the scanning process.
2867            synchronized (mPackages) {
2868                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2869            }
2870            return PackageManager.SIGNATURE_MATCH;
2871        }
2872        return PackageManager.SIGNATURE_NO_MATCH;
2873    }
2874
2875    @Override
2876    public String[] getPackagesForUid(int uid) {
2877        uid = UserHandle.getAppId(uid);
2878        // reader
2879        synchronized (mPackages) {
2880            Object obj = mSettings.getUserIdLPr(uid);
2881            if (obj instanceof SharedUserSetting) {
2882                final SharedUserSetting sus = (SharedUserSetting) obj;
2883                final int N = sus.packages.size();
2884                final String[] res = new String[N];
2885                final Iterator<PackageSetting> it = sus.packages.iterator();
2886                int i = 0;
2887                while (it.hasNext()) {
2888                    res[i++] = it.next().name;
2889                }
2890                return res;
2891            } else if (obj instanceof PackageSetting) {
2892                final PackageSetting ps = (PackageSetting) obj;
2893                return new String[] { ps.name };
2894            }
2895        }
2896        return null;
2897    }
2898
2899    @Override
2900    public String getNameForUid(int uid) {
2901        // reader
2902        synchronized (mPackages) {
2903            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2904            if (obj instanceof SharedUserSetting) {
2905                final SharedUserSetting sus = (SharedUserSetting) obj;
2906                return sus.name + ":" + sus.userId;
2907            } else if (obj instanceof PackageSetting) {
2908                final PackageSetting ps = (PackageSetting) obj;
2909                return ps.name;
2910            }
2911        }
2912        return null;
2913    }
2914
2915    @Override
2916    public int getUidForSharedUser(String sharedUserName) {
2917        if(sharedUserName == null) {
2918            return -1;
2919        }
2920        // reader
2921        synchronized (mPackages) {
2922            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2923            if (suid == null) {
2924                return -1;
2925            }
2926            return suid.userId;
2927        }
2928    }
2929
2930    @Override
2931    public int getFlagsForUid(int uid) {
2932        synchronized (mPackages) {
2933            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2934            if (obj instanceof SharedUserSetting) {
2935                final SharedUserSetting sus = (SharedUserSetting) obj;
2936                return sus.pkgFlags;
2937            } else if (obj instanceof PackageSetting) {
2938                final PackageSetting ps = (PackageSetting) obj;
2939                return ps.pkgFlags;
2940            }
2941        }
2942        return 0;
2943    }
2944
2945    @Override
2946    public boolean isUidPrivileged(int uid) {
2947        uid = UserHandle.getAppId(uid);
2948        // reader
2949        synchronized (mPackages) {
2950            Object obj = mSettings.getUserIdLPr(uid);
2951            if (obj instanceof SharedUserSetting) {
2952                final SharedUserSetting sus = (SharedUserSetting) obj;
2953                final Iterator<PackageSetting> it = sus.packages.iterator();
2954                while (it.hasNext()) {
2955                    if (it.next().isPrivileged()) {
2956                        return true;
2957                    }
2958                }
2959            } else if (obj instanceof PackageSetting) {
2960                final PackageSetting ps = (PackageSetting) obj;
2961                return ps.isPrivileged();
2962            }
2963        }
2964        return false;
2965    }
2966
2967    @Override
2968    public String[] getAppOpPermissionPackages(String permissionName) {
2969        synchronized (mPackages) {
2970            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2971            if (pkgs == null) {
2972                return null;
2973            }
2974            return pkgs.toArray(new String[pkgs.size()]);
2975        }
2976    }
2977
2978    @Override
2979    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2980            int flags, int userId) {
2981        if (!sUserManager.exists(userId)) return null;
2982        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2983        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2984        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2985    }
2986
2987    @Override
2988    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2989            IntentFilter filter, int match, ComponentName activity) {
2990        final int userId = UserHandle.getCallingUserId();
2991        if (DEBUG_PREFERRED) {
2992            Log.v(TAG, "setLastChosenActivity intent=" + intent
2993                + " resolvedType=" + resolvedType
2994                + " flags=" + flags
2995                + " filter=" + filter
2996                + " match=" + match
2997                + " activity=" + activity);
2998            filter.dump(new PrintStreamPrinter(System.out), "    ");
2999        }
3000        intent.setComponent(null);
3001        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3002        // Find any earlier preferred or last chosen entries and nuke them
3003        findPreferredActivity(intent, resolvedType,
3004                flags, query, 0, false, true, false, userId);
3005        // Add the new activity as the last chosen for this filter
3006        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3007                "Setting last chosen");
3008    }
3009
3010    @Override
3011    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3012        final int userId = UserHandle.getCallingUserId();
3013        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3014        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3015        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3016                false, false, false, userId);
3017    }
3018
3019    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3020            int flags, List<ResolveInfo> query, int userId) {
3021        if (query != null) {
3022            final int N = query.size();
3023            if (N == 1) {
3024                return query.get(0);
3025            } else if (N > 1) {
3026                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3027                // If there is more than one activity with the same priority,
3028                // then let the user decide between them.
3029                ResolveInfo r0 = query.get(0);
3030                ResolveInfo r1 = query.get(1);
3031                if (DEBUG_INTENT_MATCHING || debug) {
3032                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3033                            + r1.activityInfo.name + "=" + r1.priority);
3034                }
3035                // If the first activity has a higher priority, or a different
3036                // default, then it is always desireable to pick it.
3037                if (r0.priority != r1.priority
3038                        || r0.preferredOrder != r1.preferredOrder
3039                        || r0.isDefault != r1.isDefault) {
3040                    return query.get(0);
3041                }
3042                // If we have saved a preference for a preferred activity for
3043                // this Intent, use that.
3044                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3045                        flags, query, r0.priority, true, false, debug, userId);
3046                if (ri != null) {
3047                    return ri;
3048                }
3049                if (userId != 0) {
3050                    ri = new ResolveInfo(mResolveInfo);
3051                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3052                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3053                            ri.activityInfo.applicationInfo);
3054                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3055                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3056                    return ri;
3057                }
3058                return mResolveInfo;
3059            }
3060        }
3061        return null;
3062    }
3063
3064    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3065            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3066        final int N = query.size();
3067        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3068                .get(userId);
3069        // Get the list of persistent preferred activities that handle the intent
3070        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3071        List<PersistentPreferredActivity> pprefs = ppir != null
3072                ? ppir.queryIntent(intent, resolvedType,
3073                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3074                : null;
3075        if (pprefs != null && pprefs.size() > 0) {
3076            final int M = pprefs.size();
3077            for (int i=0; i<M; i++) {
3078                final PersistentPreferredActivity ppa = pprefs.get(i);
3079                if (DEBUG_PREFERRED || debug) {
3080                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3081                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3082                            + "\n  component=" + ppa.mComponent);
3083                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3084                }
3085                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3086                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3087                if (DEBUG_PREFERRED || debug) {
3088                    Slog.v(TAG, "Found persistent preferred activity:");
3089                    if (ai != null) {
3090                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3091                    } else {
3092                        Slog.v(TAG, "  null");
3093                    }
3094                }
3095                if (ai == null) {
3096                    // This previously registered persistent preferred activity
3097                    // component is no longer known. Ignore it and do NOT remove it.
3098                    continue;
3099                }
3100                for (int j=0; j<N; j++) {
3101                    final ResolveInfo ri = query.get(j);
3102                    if (!ri.activityInfo.applicationInfo.packageName
3103                            .equals(ai.applicationInfo.packageName)) {
3104                        continue;
3105                    }
3106                    if (!ri.activityInfo.name.equals(ai.name)) {
3107                        continue;
3108                    }
3109                    //  Found a persistent preference that can handle the intent.
3110                    if (DEBUG_PREFERRED || debug) {
3111                        Slog.v(TAG, "Returning persistent preferred activity: " +
3112                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3113                    }
3114                    return ri;
3115                }
3116            }
3117        }
3118        return null;
3119    }
3120
3121    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3122            List<ResolveInfo> query, int priority, boolean always,
3123            boolean removeMatches, boolean debug, int userId) {
3124        if (!sUserManager.exists(userId)) return null;
3125        // writer
3126        synchronized (mPackages) {
3127            if (intent.getSelector() != null) {
3128                intent = intent.getSelector();
3129            }
3130            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3131
3132            // Try to find a matching persistent preferred activity.
3133            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3134                    debug, userId);
3135
3136            // If a persistent preferred activity matched, use it.
3137            if (pri != null) {
3138                return pri;
3139            }
3140
3141            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3142            // Get the list of preferred activities that handle the intent
3143            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3144            List<PreferredActivity> prefs = pir != null
3145                    ? pir.queryIntent(intent, resolvedType,
3146                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3147                    : null;
3148            if (prefs != null && prefs.size() > 0) {
3149                boolean changed = false;
3150                try {
3151                    // First figure out how good the original match set is.
3152                    // We will only allow preferred activities that came
3153                    // from the same match quality.
3154                    int match = 0;
3155
3156                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3157
3158                    final int N = query.size();
3159                    for (int j=0; j<N; j++) {
3160                        final ResolveInfo ri = query.get(j);
3161                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3162                                + ": 0x" + Integer.toHexString(match));
3163                        if (ri.match > match) {
3164                            match = ri.match;
3165                        }
3166                    }
3167
3168                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3169                            + Integer.toHexString(match));
3170
3171                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3172                    final int M = prefs.size();
3173                    for (int i=0; i<M; i++) {
3174                        final PreferredActivity pa = prefs.get(i);
3175                        if (DEBUG_PREFERRED || debug) {
3176                            Slog.v(TAG, "Checking PreferredActivity ds="
3177                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3178                                    + "\n  component=" + pa.mPref.mComponent);
3179                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3180                        }
3181                        if (pa.mPref.mMatch != match) {
3182                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3183                                    + Integer.toHexString(pa.mPref.mMatch));
3184                            continue;
3185                        }
3186                        // If it's not an "always" type preferred activity and that's what we're
3187                        // looking for, skip it.
3188                        if (always && !pa.mPref.mAlways) {
3189                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3190                            continue;
3191                        }
3192                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3193                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3194                        if (DEBUG_PREFERRED || debug) {
3195                            Slog.v(TAG, "Found preferred activity:");
3196                            if (ai != null) {
3197                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3198                            } else {
3199                                Slog.v(TAG, "  null");
3200                            }
3201                        }
3202                        if (ai == null) {
3203                            // This previously registered preferred activity
3204                            // component is no longer known.  Most likely an update
3205                            // to the app was installed and in the new version this
3206                            // component no longer exists.  Clean it up by removing
3207                            // it from the preferred activities list, and skip it.
3208                            Slog.w(TAG, "Removing dangling preferred activity: "
3209                                    + pa.mPref.mComponent);
3210                            pir.removeFilter(pa);
3211                            changed = true;
3212                            continue;
3213                        }
3214                        for (int j=0; j<N; j++) {
3215                            final ResolveInfo ri = query.get(j);
3216                            if (!ri.activityInfo.applicationInfo.packageName
3217                                    .equals(ai.applicationInfo.packageName)) {
3218                                continue;
3219                            }
3220                            if (!ri.activityInfo.name.equals(ai.name)) {
3221                                continue;
3222                            }
3223
3224                            if (removeMatches) {
3225                                pir.removeFilter(pa);
3226                                changed = true;
3227                                if (DEBUG_PREFERRED) {
3228                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3229                                }
3230                                break;
3231                            }
3232
3233                            // Okay we found a previously set preferred or last chosen app.
3234                            // If the result set is different from when this
3235                            // was created, we need to clear it and re-ask the
3236                            // user their preference, if we're looking for an "always" type entry.
3237                            if (always && !pa.mPref.sameSet(query, priority)) {
3238                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3239                                        + intent + " type " + resolvedType);
3240                                if (DEBUG_PREFERRED) {
3241                                    Slog.v(TAG, "Removing preferred activity since set changed "
3242                                            + pa.mPref.mComponent);
3243                                }
3244                                pir.removeFilter(pa);
3245                                // Re-add the filter as a "last chosen" entry (!always)
3246                                PreferredActivity lastChosen = new PreferredActivity(
3247                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3248                                pir.addFilter(lastChosen);
3249                                changed = true;
3250                                return null;
3251                            }
3252
3253                            // Yay! Either the set matched or we're looking for the last chosen
3254                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3255                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3256                            return ri;
3257                        }
3258                    }
3259                } finally {
3260                    if (changed) {
3261                        if (DEBUG_PREFERRED) {
3262                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3263                        }
3264                        mSettings.writePackageRestrictionsLPr(userId);
3265                    }
3266                }
3267            }
3268        }
3269        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3270        return null;
3271    }
3272
3273    /*
3274     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3275     */
3276    @Override
3277    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3278            int targetUserId) {
3279        mContext.enforceCallingOrSelfPermission(
3280                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3281        List<CrossProfileIntentFilter> matches =
3282                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3283        if (matches != null) {
3284            int size = matches.size();
3285            for (int i = 0; i < size; i++) {
3286                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3287            }
3288        }
3289        return false;
3290    }
3291
3292    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3293            String resolvedType, int userId) {
3294        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3295        if (resolver != null) {
3296            return resolver.queryIntent(intent, resolvedType, false, userId);
3297        }
3298        return null;
3299    }
3300
3301    @Override
3302    public List<ResolveInfo> queryIntentActivities(Intent intent,
3303            String resolvedType, int flags, int userId) {
3304        if (!sUserManager.exists(userId)) return Collections.emptyList();
3305        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3306        ComponentName comp = intent.getComponent();
3307        if (comp == null) {
3308            if (intent.getSelector() != null) {
3309                intent = intent.getSelector();
3310                comp = intent.getComponent();
3311            }
3312        }
3313
3314        if (comp != null) {
3315            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3316            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3317            if (ai != null) {
3318                final ResolveInfo ri = new ResolveInfo();
3319                ri.activityInfo = ai;
3320                list.add(ri);
3321            }
3322            return list;
3323        }
3324
3325        // reader
3326        synchronized (mPackages) {
3327            final String pkgName = intent.getPackage();
3328            if (pkgName == null) {
3329                List<CrossProfileIntentFilter> matchingFilters =
3330                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3331                // Check for results that need to skip the current profile.
3332                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3333                        resolvedType, flags, userId);
3334                if (resolveInfo != null) {
3335                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3336                    result.add(resolveInfo);
3337                    return result;
3338                }
3339                // Check for cross profile results.
3340                resolveInfo = queryCrossProfileIntents(
3341                        matchingFilters, intent, resolvedType, flags, userId);
3342
3343                // Check for results in the current profile.
3344                List<ResolveInfo> result = mActivities.queryIntent(
3345                        intent, resolvedType, flags, userId);
3346                if (resolveInfo != null) {
3347                    result.add(resolveInfo);
3348                    Collections.sort(result, mResolvePrioritySorter);
3349                }
3350                return result;
3351            }
3352            final PackageParser.Package pkg = mPackages.get(pkgName);
3353            if (pkg != null) {
3354                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3355                        pkg.activities, userId);
3356            }
3357            return new ArrayList<ResolveInfo>();
3358        }
3359    }
3360
3361    private ResolveInfo querySkipCurrentProfileIntents(
3362            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3363            int flags, int sourceUserId) {
3364        if (matchingFilters != null) {
3365            int size = matchingFilters.size();
3366            for (int i = 0; i < size; i ++) {
3367                CrossProfileIntentFilter filter = matchingFilters.get(i);
3368                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3369                    // Checking if there are activities in the target user that can handle the
3370                    // intent.
3371                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3372                            flags, sourceUserId);
3373                    if (resolveInfo != null) {
3374                        return resolveInfo;
3375                    }
3376                }
3377            }
3378        }
3379        return null;
3380    }
3381
3382    // Return matching ResolveInfo if any for skip current profile intent filters.
3383    private ResolveInfo queryCrossProfileIntents(
3384            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3385            int flags, int sourceUserId) {
3386        if (matchingFilters != null) {
3387            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3388            // match the same intent. For performance reasons, it is better not to
3389            // run queryIntent twice for the same userId
3390            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3391            int size = matchingFilters.size();
3392            for (int i = 0; i < size; i++) {
3393                CrossProfileIntentFilter filter = matchingFilters.get(i);
3394                int targetUserId = filter.getTargetUserId();
3395                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3396                        && !alreadyTriedUserIds.get(targetUserId)) {
3397                    // Checking if there are activities in the target user that can handle the
3398                    // intent.
3399                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3400                            flags, sourceUserId);
3401                    if (resolveInfo != null) return resolveInfo;
3402                    alreadyTriedUserIds.put(targetUserId, true);
3403                }
3404            }
3405        }
3406        return null;
3407    }
3408
3409    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3410            String resolvedType, int flags, int sourceUserId) {
3411        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3412                resolvedType, flags, filter.getTargetUserId());
3413        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3414            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3415        }
3416        return null;
3417    }
3418
3419    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3420            int sourceUserId, int targetUserId) {
3421        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3422        String className;
3423        if (targetUserId == UserHandle.USER_OWNER) {
3424            className = FORWARD_INTENT_TO_USER_OWNER;
3425        } else {
3426            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3427        }
3428        ComponentName forwardingActivityComponentName = new ComponentName(
3429                mAndroidApplication.packageName, className);
3430        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3431                sourceUserId);
3432        if (targetUserId == UserHandle.USER_OWNER) {
3433            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3434            forwardingResolveInfo.noResourceId = true;
3435        }
3436        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3437        forwardingResolveInfo.priority = 0;
3438        forwardingResolveInfo.preferredOrder = 0;
3439        forwardingResolveInfo.match = 0;
3440        forwardingResolveInfo.isDefault = true;
3441        forwardingResolveInfo.filter = filter;
3442        forwardingResolveInfo.targetUserId = targetUserId;
3443        return forwardingResolveInfo;
3444    }
3445
3446    @Override
3447    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3448            Intent[] specifics, String[] specificTypes, Intent intent,
3449            String resolvedType, int flags, int userId) {
3450        if (!sUserManager.exists(userId)) return Collections.emptyList();
3451        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3452                false, "query intent activity options");
3453        final String resultsAction = intent.getAction();
3454
3455        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3456                | PackageManager.GET_RESOLVED_FILTER, userId);
3457
3458        if (DEBUG_INTENT_MATCHING) {
3459            Log.v(TAG, "Query " + intent + ": " + results);
3460        }
3461
3462        int specificsPos = 0;
3463        int N;
3464
3465        // todo: note that the algorithm used here is O(N^2).  This
3466        // isn't a problem in our current environment, but if we start running
3467        // into situations where we have more than 5 or 10 matches then this
3468        // should probably be changed to something smarter...
3469
3470        // First we go through and resolve each of the specific items
3471        // that were supplied, taking care of removing any corresponding
3472        // duplicate items in the generic resolve list.
3473        if (specifics != null) {
3474            for (int i=0; i<specifics.length; i++) {
3475                final Intent sintent = specifics[i];
3476                if (sintent == null) {
3477                    continue;
3478                }
3479
3480                if (DEBUG_INTENT_MATCHING) {
3481                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3482                }
3483
3484                String action = sintent.getAction();
3485                if (resultsAction != null && resultsAction.equals(action)) {
3486                    // If this action was explicitly requested, then don't
3487                    // remove things that have it.
3488                    action = null;
3489                }
3490
3491                ResolveInfo ri = null;
3492                ActivityInfo ai = null;
3493
3494                ComponentName comp = sintent.getComponent();
3495                if (comp == null) {
3496                    ri = resolveIntent(
3497                        sintent,
3498                        specificTypes != null ? specificTypes[i] : null,
3499                            flags, userId);
3500                    if (ri == null) {
3501                        continue;
3502                    }
3503                    if (ri == mResolveInfo) {
3504                        // ACK!  Must do something better with this.
3505                    }
3506                    ai = ri.activityInfo;
3507                    comp = new ComponentName(ai.applicationInfo.packageName,
3508                            ai.name);
3509                } else {
3510                    ai = getActivityInfo(comp, flags, userId);
3511                    if (ai == null) {
3512                        continue;
3513                    }
3514                }
3515
3516                // Look for any generic query activities that are duplicates
3517                // of this specific one, and remove them from the results.
3518                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3519                N = results.size();
3520                int j;
3521                for (j=specificsPos; j<N; j++) {
3522                    ResolveInfo sri = results.get(j);
3523                    if ((sri.activityInfo.name.equals(comp.getClassName())
3524                            && sri.activityInfo.applicationInfo.packageName.equals(
3525                                    comp.getPackageName()))
3526                        || (action != null && sri.filter.matchAction(action))) {
3527                        results.remove(j);
3528                        if (DEBUG_INTENT_MATCHING) Log.v(
3529                            TAG, "Removing duplicate item from " + j
3530                            + " due to specific " + specificsPos);
3531                        if (ri == null) {
3532                            ri = sri;
3533                        }
3534                        j--;
3535                        N--;
3536                    }
3537                }
3538
3539                // Add this specific item to its proper place.
3540                if (ri == null) {
3541                    ri = new ResolveInfo();
3542                    ri.activityInfo = ai;
3543                }
3544                results.add(specificsPos, ri);
3545                ri.specificIndex = i;
3546                specificsPos++;
3547            }
3548        }
3549
3550        // Now we go through the remaining generic results and remove any
3551        // duplicate actions that are found here.
3552        N = results.size();
3553        for (int i=specificsPos; i<N-1; i++) {
3554            final ResolveInfo rii = results.get(i);
3555            if (rii.filter == null) {
3556                continue;
3557            }
3558
3559            // Iterate over all of the actions of this result's intent
3560            // filter...  typically this should be just one.
3561            final Iterator<String> it = rii.filter.actionsIterator();
3562            if (it == null) {
3563                continue;
3564            }
3565            while (it.hasNext()) {
3566                final String action = it.next();
3567                if (resultsAction != null && resultsAction.equals(action)) {
3568                    // If this action was explicitly requested, then don't
3569                    // remove things that have it.
3570                    continue;
3571                }
3572                for (int j=i+1; j<N; j++) {
3573                    final ResolveInfo rij = results.get(j);
3574                    if (rij.filter != null && rij.filter.hasAction(action)) {
3575                        results.remove(j);
3576                        if (DEBUG_INTENT_MATCHING) Log.v(
3577                            TAG, "Removing duplicate item from " + j
3578                            + " due to action " + action + " at " + i);
3579                        j--;
3580                        N--;
3581                    }
3582                }
3583            }
3584
3585            // If the caller didn't request filter information, drop it now
3586            // so we don't have to marshall/unmarshall it.
3587            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3588                rii.filter = null;
3589            }
3590        }
3591
3592        // Filter out the caller activity if so requested.
3593        if (caller != null) {
3594            N = results.size();
3595            for (int i=0; i<N; i++) {
3596                ActivityInfo ainfo = results.get(i).activityInfo;
3597                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3598                        && caller.getClassName().equals(ainfo.name)) {
3599                    results.remove(i);
3600                    break;
3601                }
3602            }
3603        }
3604
3605        // If the caller didn't request filter information,
3606        // drop them now so we don't have to
3607        // marshall/unmarshall it.
3608        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3609            N = results.size();
3610            for (int i=0; i<N; i++) {
3611                results.get(i).filter = null;
3612            }
3613        }
3614
3615        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3616        return results;
3617    }
3618
3619    @Override
3620    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3621            int userId) {
3622        if (!sUserManager.exists(userId)) return Collections.emptyList();
3623        ComponentName comp = intent.getComponent();
3624        if (comp == null) {
3625            if (intent.getSelector() != null) {
3626                intent = intent.getSelector();
3627                comp = intent.getComponent();
3628            }
3629        }
3630        if (comp != null) {
3631            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3632            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3633            if (ai != null) {
3634                ResolveInfo ri = new ResolveInfo();
3635                ri.activityInfo = ai;
3636                list.add(ri);
3637            }
3638            return list;
3639        }
3640
3641        // reader
3642        synchronized (mPackages) {
3643            String pkgName = intent.getPackage();
3644            if (pkgName == null) {
3645                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3646            }
3647            final PackageParser.Package pkg = mPackages.get(pkgName);
3648            if (pkg != null) {
3649                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3650                        userId);
3651            }
3652            return null;
3653        }
3654    }
3655
3656    @Override
3657    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3658        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3659        if (!sUserManager.exists(userId)) return null;
3660        if (query != null) {
3661            if (query.size() >= 1) {
3662                // If there is more than one service with the same priority,
3663                // just arbitrarily pick the first one.
3664                return query.get(0);
3665            }
3666        }
3667        return null;
3668    }
3669
3670    @Override
3671    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3672            int userId) {
3673        if (!sUserManager.exists(userId)) return Collections.emptyList();
3674        ComponentName comp = intent.getComponent();
3675        if (comp == null) {
3676            if (intent.getSelector() != null) {
3677                intent = intent.getSelector();
3678                comp = intent.getComponent();
3679            }
3680        }
3681        if (comp != null) {
3682            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3683            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3684            if (si != null) {
3685                final ResolveInfo ri = new ResolveInfo();
3686                ri.serviceInfo = si;
3687                list.add(ri);
3688            }
3689            return list;
3690        }
3691
3692        // reader
3693        synchronized (mPackages) {
3694            String pkgName = intent.getPackage();
3695            if (pkgName == null) {
3696                return mServices.queryIntent(intent, resolvedType, flags, userId);
3697            }
3698            final PackageParser.Package pkg = mPackages.get(pkgName);
3699            if (pkg != null) {
3700                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3701                        userId);
3702            }
3703            return null;
3704        }
3705    }
3706
3707    @Override
3708    public List<ResolveInfo> queryIntentContentProviders(
3709            Intent intent, String resolvedType, int flags, int userId) {
3710        if (!sUserManager.exists(userId)) return Collections.emptyList();
3711        ComponentName comp = intent.getComponent();
3712        if (comp == null) {
3713            if (intent.getSelector() != null) {
3714                intent = intent.getSelector();
3715                comp = intent.getComponent();
3716            }
3717        }
3718        if (comp != null) {
3719            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3720            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3721            if (pi != null) {
3722                final ResolveInfo ri = new ResolveInfo();
3723                ri.providerInfo = pi;
3724                list.add(ri);
3725            }
3726            return list;
3727        }
3728
3729        // reader
3730        synchronized (mPackages) {
3731            String pkgName = intent.getPackage();
3732            if (pkgName == null) {
3733                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3734            }
3735            final PackageParser.Package pkg = mPackages.get(pkgName);
3736            if (pkg != null) {
3737                return mProviders.queryIntentForPackage(
3738                        intent, resolvedType, flags, pkg.providers, userId);
3739            }
3740            return null;
3741        }
3742    }
3743
3744    @Override
3745    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3746        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3747
3748        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3749
3750        // writer
3751        synchronized (mPackages) {
3752            ArrayList<PackageInfo> list;
3753            if (listUninstalled) {
3754                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3755                for (PackageSetting ps : mSettings.mPackages.values()) {
3756                    PackageInfo pi;
3757                    if (ps.pkg != null) {
3758                        pi = generatePackageInfo(ps.pkg, flags, userId);
3759                    } else {
3760                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3761                    }
3762                    if (pi != null) {
3763                        list.add(pi);
3764                    }
3765                }
3766            } else {
3767                list = new ArrayList<PackageInfo>(mPackages.size());
3768                for (PackageParser.Package p : mPackages.values()) {
3769                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3770                    if (pi != null) {
3771                        list.add(pi);
3772                    }
3773                }
3774            }
3775
3776            return new ParceledListSlice<PackageInfo>(list);
3777        }
3778    }
3779
3780    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3781            String[] permissions, boolean[] tmp, int flags, int userId) {
3782        int numMatch = 0;
3783        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3784        for (int i=0; i<permissions.length; i++) {
3785            if (gp.grantedPermissions.contains(permissions[i])) {
3786                tmp[i] = true;
3787                numMatch++;
3788            } else {
3789                tmp[i] = false;
3790            }
3791        }
3792        if (numMatch == 0) {
3793            return;
3794        }
3795        PackageInfo pi;
3796        if (ps.pkg != null) {
3797            pi = generatePackageInfo(ps.pkg, flags, userId);
3798        } else {
3799            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3800        }
3801        // The above might return null in cases of uninstalled apps or install-state
3802        // skew across users/profiles.
3803        if (pi != null) {
3804            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3805                if (numMatch == permissions.length) {
3806                    pi.requestedPermissions = permissions;
3807                } else {
3808                    pi.requestedPermissions = new String[numMatch];
3809                    numMatch = 0;
3810                    for (int i=0; i<permissions.length; i++) {
3811                        if (tmp[i]) {
3812                            pi.requestedPermissions[numMatch] = permissions[i];
3813                            numMatch++;
3814                        }
3815                    }
3816                }
3817            }
3818            list.add(pi);
3819        }
3820    }
3821
3822    @Override
3823    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3824            String[] permissions, int flags, int userId) {
3825        if (!sUserManager.exists(userId)) return null;
3826        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3827
3828        // writer
3829        synchronized (mPackages) {
3830            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3831            boolean[] tmpBools = new boolean[permissions.length];
3832            if (listUninstalled) {
3833                for (PackageSetting ps : mSettings.mPackages.values()) {
3834                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3835                }
3836            } else {
3837                for (PackageParser.Package pkg : mPackages.values()) {
3838                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3839                    if (ps != null) {
3840                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3841                                userId);
3842                    }
3843                }
3844            }
3845
3846            return new ParceledListSlice<PackageInfo>(list);
3847        }
3848    }
3849
3850    @Override
3851    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3852        if (!sUserManager.exists(userId)) return null;
3853        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3854
3855        // writer
3856        synchronized (mPackages) {
3857            ArrayList<ApplicationInfo> list;
3858            if (listUninstalled) {
3859                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3860                for (PackageSetting ps : mSettings.mPackages.values()) {
3861                    ApplicationInfo ai;
3862                    if (ps.pkg != null) {
3863                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3864                                ps.readUserState(userId), userId);
3865                    } else {
3866                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3867                    }
3868                    if (ai != null) {
3869                        list.add(ai);
3870                    }
3871                }
3872            } else {
3873                list = new ArrayList<ApplicationInfo>(mPackages.size());
3874                for (PackageParser.Package p : mPackages.values()) {
3875                    if (p.mExtras != null) {
3876                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3877                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3878                        if (ai != null) {
3879                            list.add(ai);
3880                        }
3881                    }
3882                }
3883            }
3884
3885            return new ParceledListSlice<ApplicationInfo>(list);
3886        }
3887    }
3888
3889    public List<ApplicationInfo> getPersistentApplications(int flags) {
3890        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3891
3892        // reader
3893        synchronized (mPackages) {
3894            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3895            final int userId = UserHandle.getCallingUserId();
3896            while (i.hasNext()) {
3897                final PackageParser.Package p = i.next();
3898                if (p.applicationInfo != null
3899                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3900                        && (!mSafeMode || isSystemApp(p))) {
3901                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3902                    if (ps != null) {
3903                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3904                                ps.readUserState(userId), userId);
3905                        if (ai != null) {
3906                            finalList.add(ai);
3907                        }
3908                    }
3909                }
3910            }
3911        }
3912
3913        return finalList;
3914    }
3915
3916    @Override
3917    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3918        if (!sUserManager.exists(userId)) return null;
3919        // reader
3920        synchronized (mPackages) {
3921            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3922            PackageSetting ps = provider != null
3923                    ? mSettings.mPackages.get(provider.owner.packageName)
3924                    : null;
3925            return ps != null
3926                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3927                    && (!mSafeMode || (provider.info.applicationInfo.flags
3928                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3929                    ? PackageParser.generateProviderInfo(provider, flags,
3930                            ps.readUserState(userId), userId)
3931                    : null;
3932        }
3933    }
3934
3935    /**
3936     * @deprecated
3937     */
3938    @Deprecated
3939    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3940        // reader
3941        synchronized (mPackages) {
3942            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3943                    .entrySet().iterator();
3944            final int userId = UserHandle.getCallingUserId();
3945            while (i.hasNext()) {
3946                Map.Entry<String, PackageParser.Provider> entry = i.next();
3947                PackageParser.Provider p = entry.getValue();
3948                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3949
3950                if (ps != null && p.syncable
3951                        && (!mSafeMode || (p.info.applicationInfo.flags
3952                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3953                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3954                            ps.readUserState(userId), userId);
3955                    if (info != null) {
3956                        outNames.add(entry.getKey());
3957                        outInfo.add(info);
3958                    }
3959                }
3960            }
3961        }
3962    }
3963
3964    @Override
3965    public List<ProviderInfo> queryContentProviders(String processName,
3966            int uid, int flags) {
3967        ArrayList<ProviderInfo> finalList = null;
3968        // reader
3969        synchronized (mPackages) {
3970            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3971            final int userId = processName != null ?
3972                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3973            while (i.hasNext()) {
3974                final PackageParser.Provider p = i.next();
3975                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3976                if (ps != null && p.info.authority != null
3977                        && (processName == null
3978                                || (p.info.processName.equals(processName)
3979                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3980                        && mSettings.isEnabledLPr(p.info, flags, userId)
3981                        && (!mSafeMode
3982                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3983                    if (finalList == null) {
3984                        finalList = new ArrayList<ProviderInfo>(3);
3985                    }
3986                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3987                            ps.readUserState(userId), userId);
3988                    if (info != null) {
3989                        finalList.add(info);
3990                    }
3991                }
3992            }
3993        }
3994
3995        if (finalList != null) {
3996            Collections.sort(finalList, mProviderInitOrderSorter);
3997        }
3998
3999        return finalList;
4000    }
4001
4002    @Override
4003    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4004            int flags) {
4005        // reader
4006        synchronized (mPackages) {
4007            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4008            return PackageParser.generateInstrumentationInfo(i, flags);
4009        }
4010    }
4011
4012    @Override
4013    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4014            int flags) {
4015        ArrayList<InstrumentationInfo> finalList =
4016            new ArrayList<InstrumentationInfo>();
4017
4018        // reader
4019        synchronized (mPackages) {
4020            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4021            while (i.hasNext()) {
4022                final PackageParser.Instrumentation p = i.next();
4023                if (targetPackage == null
4024                        || targetPackage.equals(p.info.targetPackage)) {
4025                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4026                            flags);
4027                    if (ii != null) {
4028                        finalList.add(ii);
4029                    }
4030                }
4031            }
4032        }
4033
4034        return finalList;
4035    }
4036
4037    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4038        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4039        if (overlays == null) {
4040            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4041            return;
4042        }
4043        for (PackageParser.Package opkg : overlays.values()) {
4044            // Not much to do if idmap fails: we already logged the error
4045            // and we certainly don't want to abort installation of pkg simply
4046            // because an overlay didn't fit properly. For these reasons,
4047            // ignore the return value of createIdmapForPackagePairLI.
4048            createIdmapForPackagePairLI(pkg, opkg);
4049        }
4050    }
4051
4052    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4053            PackageParser.Package opkg) {
4054        if (!opkg.mTrustedOverlay) {
4055            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4056                    opkg.baseCodePath + ": overlay not trusted");
4057            return false;
4058        }
4059        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4060        if (overlaySet == null) {
4061            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4062                    opkg.baseCodePath + " but target package has no known overlays");
4063            return false;
4064        }
4065        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4066        // TODO: generate idmap for split APKs
4067        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4068            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4069                    + opkg.baseCodePath);
4070            return false;
4071        }
4072        PackageParser.Package[] overlayArray =
4073            overlaySet.values().toArray(new PackageParser.Package[0]);
4074        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4075            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4076                return p1.mOverlayPriority - p2.mOverlayPriority;
4077            }
4078        };
4079        Arrays.sort(overlayArray, cmp);
4080
4081        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4082        int i = 0;
4083        for (PackageParser.Package p : overlayArray) {
4084            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4085        }
4086        return true;
4087    }
4088
4089    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4090        final File[] files = dir.listFiles();
4091        if (ArrayUtils.isEmpty(files)) {
4092            Log.d(TAG, "No files in app dir " + dir);
4093            return;
4094        }
4095
4096        if (DEBUG_PACKAGE_SCANNING) {
4097            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4098                    + " flags=0x" + Integer.toHexString(parseFlags));
4099        }
4100
4101        for (File file : files) {
4102            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4103                    && !PackageInstallerService.isStageName(file.getName());
4104            if (!isPackage) {
4105                // Ignore entries which are not packages
4106                continue;
4107            }
4108            try {
4109                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4110                        scanFlags, currentTime, null);
4111            } catch (PackageManagerException e) {
4112                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4113
4114                // Delete invalid userdata apps
4115                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4116                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4117                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4118                    if (file.isDirectory()) {
4119                        FileUtils.deleteContents(file);
4120                    }
4121                    file.delete();
4122                }
4123            }
4124        }
4125    }
4126
4127    private static File getSettingsProblemFile() {
4128        File dataDir = Environment.getDataDirectory();
4129        File systemDir = new File(dataDir, "system");
4130        File fname = new File(systemDir, "uiderrors.txt");
4131        return fname;
4132    }
4133
4134    static void reportSettingsProblem(int priority, String msg) {
4135        logCriticalInfo(priority, msg);
4136    }
4137
4138    static void logCriticalInfo(int priority, String msg) {
4139        Slog.println(priority, TAG, msg);
4140        EventLogTags.writePmCriticalInfo(msg);
4141        try {
4142            File fname = getSettingsProblemFile();
4143            FileOutputStream out = new FileOutputStream(fname, true);
4144            PrintWriter pw = new FastPrintWriter(out);
4145            SimpleDateFormat formatter = new SimpleDateFormat();
4146            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4147            pw.println(dateString + ": " + msg);
4148            pw.close();
4149            FileUtils.setPermissions(
4150                    fname.toString(),
4151                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4152                    -1, -1);
4153        } catch (java.io.IOException e) {
4154        }
4155    }
4156
4157    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4158            PackageParser.Package pkg, File srcFile, int parseFlags)
4159            throws PackageManagerException {
4160        if (ps != null
4161                && ps.codePath.equals(srcFile)
4162                && ps.timeStamp == srcFile.lastModified()
4163                && !isCompatSignatureUpdateNeeded(pkg)) {
4164            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4165            if (ps.signatures.mSignatures != null
4166                    && ps.signatures.mSignatures.length != 0
4167                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4168                // Optimization: reuse the existing cached certificates
4169                // if the package appears to be unchanged.
4170                pkg.mSignatures = ps.signatures.mSignatures;
4171                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4172                synchronized (mPackages) {
4173                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4174                }
4175                return;
4176            }
4177
4178            Slog.w(TAG, "PackageSetting for " + ps.name
4179                    + " is missing signatures.  Collecting certs again to recover them.");
4180        } else {
4181            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4182        }
4183
4184        try {
4185            pp.collectCertificates(pkg, parseFlags);
4186            pp.collectManifestDigest(pkg);
4187        } catch (PackageParserException e) {
4188            throw PackageManagerException.from(e);
4189        }
4190    }
4191
4192    /*
4193     *  Scan a package and return the newly parsed package.
4194     *  Returns null in case of errors and the error code is stored in mLastScanError
4195     */
4196    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4197            long currentTime, UserHandle user) throws PackageManagerException {
4198        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4199        parseFlags |= mDefParseFlags;
4200        PackageParser pp = new PackageParser();
4201        pp.setSeparateProcesses(mSeparateProcesses);
4202        pp.setOnlyCoreApps(mOnlyCore);
4203        pp.setDisplayMetrics(mMetrics);
4204
4205        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4206            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4207        }
4208
4209        final PackageParser.Package pkg;
4210        try {
4211            pkg = pp.parsePackage(scanFile, parseFlags);
4212        } catch (PackageParserException e) {
4213            throw PackageManagerException.from(e);
4214        }
4215
4216        PackageSetting ps = null;
4217        PackageSetting updatedPkg;
4218        // reader
4219        synchronized (mPackages) {
4220            // Look to see if we already know about this package.
4221            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4222            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4223                // This package has been renamed to its original name.  Let's
4224                // use that.
4225                ps = mSettings.peekPackageLPr(oldName);
4226            }
4227            // If there was no original package, see one for the real package name.
4228            if (ps == null) {
4229                ps = mSettings.peekPackageLPr(pkg.packageName);
4230            }
4231            // Check to see if this package could be hiding/updating a system
4232            // package.  Must look for it either under the original or real
4233            // package name depending on our state.
4234            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4235            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4236        }
4237        boolean updatedPkgBetter = false;
4238        // First check if this is a system package that may involve an update
4239        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4240            if (ps != null && !ps.codePath.equals(scanFile)) {
4241                // The path has changed from what was last scanned...  check the
4242                // version of the new path against what we have stored to determine
4243                // what to do.
4244                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4245                if (pkg.mVersionCode < ps.versionCode) {
4246                    // The system package has been updated and the code path does not match
4247                    // Ignore entry. Skip it.
4248                    logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
4249                            + " ignored: updated version " + ps.versionCode
4250                            + " better than this " + pkg.mVersionCode);
4251                    if (!updatedPkg.codePath.equals(scanFile)) {
4252                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4253                                + ps.name + " changing from " + updatedPkg.codePathString
4254                                + " to " + scanFile);
4255                        updatedPkg.codePath = scanFile;
4256                        updatedPkg.codePathString = scanFile.toString();
4257                        // This is the point at which we know that the system-disk APK
4258                        // for this package has moved during a reboot (e.g. due to an OTA),
4259                        // so we need to reevaluate it for privilege policy.
4260                        if (locationIsPrivileged(scanFile)) {
4261                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4262                        }
4263                    }
4264                    updatedPkg.pkg = pkg;
4265                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4266                } else {
4267                    // The current app on the system partition is better than
4268                    // what we have updated to on the data partition; switch
4269                    // back to the system partition version.
4270                    // At this point, its safely assumed that package installation for
4271                    // apps in system partition will go through. If not there won't be a working
4272                    // version of the app
4273                    // writer
4274                    synchronized (mPackages) {
4275                        // Just remove the loaded entries from package lists.
4276                        mPackages.remove(ps.name);
4277                    }
4278
4279                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4280                            + " reverting from " + ps.codePathString
4281                            + ": new version " + pkg.mVersionCode
4282                            + " better than installed " + ps.versionCode);
4283
4284                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4285                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4286                            getAppDexInstructionSets(ps));
4287                    synchronized (mInstallLock) {
4288                        args.cleanUpResourcesLI();
4289                    }
4290                    synchronized (mPackages) {
4291                        mSettings.enableSystemPackageLPw(ps.name);
4292                    }
4293                    updatedPkgBetter = true;
4294                }
4295            }
4296        }
4297
4298        if (updatedPkg != null) {
4299            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4300            // initially
4301            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4302
4303            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4304            // flag set initially
4305            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4306                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4307            }
4308        }
4309
4310        // Verify certificates against what was last scanned
4311        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4312
4313        /*
4314         * A new system app appeared, but we already had a non-system one of the
4315         * same name installed earlier.
4316         */
4317        boolean shouldHideSystemApp = false;
4318        if (updatedPkg == null && ps != null
4319                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4320            /*
4321             * Check to make sure the signatures match first. If they don't,
4322             * wipe the installed application and its data.
4323             */
4324            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4325                    != PackageManager.SIGNATURE_MATCH) {
4326                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4327                        + " signatures don't match existing userdata copy; removing");
4328                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4329                ps = null;
4330            } else {
4331                /*
4332                 * If the newly-added system app is an older version than the
4333                 * already installed version, hide it. It will be scanned later
4334                 * and re-added like an update.
4335                 */
4336                if (pkg.mVersionCode < ps.versionCode) {
4337                    shouldHideSystemApp = true;
4338                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4339                            + " but new version " + pkg.mVersionCode + " better than installed "
4340                            + ps.versionCode + "; hiding system");
4341                } else {
4342                    /*
4343                     * The newly found system app is a newer version that the
4344                     * one previously installed. Simply remove the
4345                     * already-installed application and replace it with our own
4346                     * while keeping the application data.
4347                     */
4348                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4349                            + " reverting from " + ps.codePathString + ": new version "
4350                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4351                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4352                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4353                            getAppDexInstructionSets(ps));
4354                    synchronized (mInstallLock) {
4355                        args.cleanUpResourcesLI();
4356                    }
4357                }
4358            }
4359        }
4360
4361        // The apk is forward locked (not public) if its code and resources
4362        // are kept in different files. (except for app in either system or
4363        // vendor path).
4364        // TODO grab this value from PackageSettings
4365        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4366            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4367                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4368            }
4369        }
4370
4371        // TODO: extend to support forward-locked splits
4372        String resourcePath = null;
4373        String baseResourcePath = null;
4374        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4375            if (ps != null && ps.resourcePathString != null) {
4376                resourcePath = ps.resourcePathString;
4377                baseResourcePath = ps.resourcePathString;
4378            } else {
4379                // Should not happen at all. Just log an error.
4380                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4381            }
4382        } else {
4383            resourcePath = pkg.codePath;
4384            baseResourcePath = pkg.baseCodePath;
4385        }
4386
4387        // Set application objects path explicitly.
4388        pkg.applicationInfo.setCodePath(pkg.codePath);
4389        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4390        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4391        pkg.applicationInfo.setResourcePath(resourcePath);
4392        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4393        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4394
4395        // Note that we invoke the following method only if we are about to unpack an application
4396        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4397                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4398
4399        /*
4400         * If the system app should be overridden by a previously installed
4401         * data, hide the system app now and let the /data/app scan pick it up
4402         * again.
4403         */
4404        if (shouldHideSystemApp) {
4405            synchronized (mPackages) {
4406                /*
4407                 * We have to grant systems permissions before we hide, because
4408                 * grantPermissions will assume the package update is trying to
4409                 * expand its permissions.
4410                 */
4411                grantPermissionsLPw(pkg, true, pkg.packageName);
4412                mSettings.disableSystemPackageLPw(pkg.packageName);
4413            }
4414        }
4415
4416        return scannedPkg;
4417    }
4418
4419    private static String fixProcessName(String defProcessName,
4420            String processName, int uid) {
4421        if (processName == null) {
4422            return defProcessName;
4423        }
4424        return processName;
4425    }
4426
4427    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4428            throws PackageManagerException {
4429        if (pkgSetting.signatures.mSignatures != null) {
4430            // Already existing package. Make sure signatures match
4431            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4432                    == PackageManager.SIGNATURE_MATCH;
4433            if (!match) {
4434                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4435                        == PackageManager.SIGNATURE_MATCH;
4436            }
4437            if (!match) {
4438                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4439                        + pkg.packageName + " signatures do not match the "
4440                        + "previously installed version; ignoring!");
4441            }
4442        }
4443
4444        // Check for shared user signatures
4445        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4446            // Already existing package. Make sure signatures match
4447            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4448                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4449            if (!match) {
4450                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4451                        == PackageManager.SIGNATURE_MATCH;
4452            }
4453            if (!match) {
4454                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4455                        "Package " + pkg.packageName
4456                        + " has no signatures that match those in shared user "
4457                        + pkgSetting.sharedUser.name + "; ignoring!");
4458            }
4459        }
4460    }
4461
4462    /**
4463     * Enforces that only the system UID or root's UID can call a method exposed
4464     * via Binder.
4465     *
4466     * @param message used as message if SecurityException is thrown
4467     * @throws SecurityException if the caller is not system or root
4468     */
4469    private static final void enforceSystemOrRoot(String message) {
4470        final int uid = Binder.getCallingUid();
4471        if (uid != Process.SYSTEM_UID && uid != 0) {
4472            throw new SecurityException(message);
4473        }
4474    }
4475
4476    @Override
4477    public void performBootDexOpt() {
4478        enforceSystemOrRoot("Only the system can request dexopt be performed");
4479
4480        final HashSet<PackageParser.Package> pkgs;
4481        synchronized (mPackages) {
4482            pkgs = mDeferredDexOpt;
4483            mDeferredDexOpt = null;
4484        }
4485
4486        if (pkgs != null) {
4487            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4488            // in case the device runs out of space.
4489            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4490            // Give priority to core apps.
4491            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4492                PackageParser.Package pkg = it.next();
4493                if (pkg.coreApp) {
4494                    if (DEBUG_DEXOPT) {
4495                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4496                    }
4497                    sortedPkgs.add(pkg);
4498                    it.remove();
4499                }
4500            }
4501            // Give priority to system apps that listen for pre boot complete.
4502            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4503            HashSet<String> pkgNames = getPackageNamesForIntent(intent);
4504            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4505                PackageParser.Package pkg = it.next();
4506                if (pkgNames.contains(pkg.packageName)) {
4507                    if (DEBUG_DEXOPT) {
4508                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4509                    }
4510                    sortedPkgs.add(pkg);
4511                    it.remove();
4512                }
4513            }
4514            // Give priority to system apps.
4515            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4516                PackageParser.Package pkg = it.next();
4517                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4518                    if (DEBUG_DEXOPT) {
4519                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4520                    }
4521                    sortedPkgs.add(pkg);
4522                    it.remove();
4523                }
4524            }
4525            // Give priority to updated system apps.
4526            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4527                PackageParser.Package pkg = it.next();
4528                if (isUpdatedSystemApp(pkg)) {
4529                    if (DEBUG_DEXOPT) {
4530                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4531                    }
4532                    sortedPkgs.add(pkg);
4533                    it.remove();
4534                }
4535            }
4536            // Give priority to apps that listen for boot complete.
4537            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4538            pkgNames = getPackageNamesForIntent(intent);
4539            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4540                PackageParser.Package pkg = it.next();
4541                if (pkgNames.contains(pkg.packageName)) {
4542                    if (DEBUG_DEXOPT) {
4543                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4544                    }
4545                    sortedPkgs.add(pkg);
4546                    it.remove();
4547                }
4548            }
4549            // Filter out packages that aren't recently used.
4550            filterRecentlyUsedApps(pkgs);
4551            // Add all remaining apps.
4552            for (PackageParser.Package pkg : pkgs) {
4553                if (DEBUG_DEXOPT) {
4554                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4555                }
4556                sortedPkgs.add(pkg);
4557            }
4558
4559            int i = 0;
4560            int total = sortedPkgs.size();
4561            File dataDir = Environment.getDataDirectory();
4562            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4563            if (lowThreshold == 0) {
4564                throw new IllegalStateException("Invalid low memory threshold");
4565            }
4566            for (PackageParser.Package pkg : sortedPkgs) {
4567                long usableSpace = dataDir.getUsableSpace();
4568                if (usableSpace < lowThreshold) {
4569                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4570                    break;
4571                }
4572                performBootDexOpt(pkg, ++i, total);
4573            }
4574        }
4575    }
4576
4577    private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) {
4578        // Filter out packages that aren't recently used.
4579        //
4580        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4581        // should do a full dexopt.
4582        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4583            int total = pkgs.size();
4584            int skipped = 0;
4585            long now = System.currentTimeMillis();
4586            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4587                PackageParser.Package pkg = i.next();
4588                long then = pkg.mLastPackageUsageTimeInMills;
4589                if (then + mDexOptLRUThresholdInMills < now) {
4590                    if (DEBUG_DEXOPT) {
4591                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4592                              ((then == 0) ? "never" : new Date(then)));
4593                    }
4594                    i.remove();
4595                    skipped++;
4596                }
4597            }
4598            if (DEBUG_DEXOPT) {
4599                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4600            }
4601        }
4602    }
4603
4604    private HashSet<String> getPackageNamesForIntent(Intent intent) {
4605        List<ResolveInfo> ris = null;
4606        try {
4607            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4608                    intent, null, 0, UserHandle.USER_OWNER);
4609        } catch (RemoteException e) {
4610        }
4611        HashSet<String> pkgNames = new HashSet<String>();
4612        if (ris != null) {
4613            for (ResolveInfo ri : ris) {
4614                pkgNames.add(ri.activityInfo.packageName);
4615            }
4616        }
4617        return pkgNames;
4618    }
4619
4620    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4621        if (DEBUG_DEXOPT) {
4622            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4623        }
4624        if (!isFirstBoot()) {
4625            try {
4626                ActivityManagerNative.getDefault().showBootMessage(
4627                        mContext.getResources().getString(R.string.android_upgrading_apk,
4628                                curr, total), true);
4629            } catch (RemoteException e) {
4630            }
4631        }
4632        PackageParser.Package p = pkg;
4633        synchronized (mInstallLock) {
4634            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4635                            false /* defer */, true /* include dependencies */);
4636        }
4637    }
4638
4639    @Override
4640    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4641        return performDexOpt(packageName, instructionSet, false);
4642    }
4643
4644    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4645        if (info.primaryCpuAbi == null) {
4646            return getPreferredInstructionSet();
4647        }
4648
4649        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4650    }
4651
4652    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4653        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4654        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4655        if (!dexopt && !updateUsage) {
4656            // We aren't going to dexopt or update usage, so bail early.
4657            return false;
4658        }
4659        PackageParser.Package p;
4660        final String targetInstructionSet;
4661        synchronized (mPackages) {
4662            p = mPackages.get(packageName);
4663            if (p == null) {
4664                return false;
4665            }
4666            if (updateUsage) {
4667                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4668            }
4669            mPackageUsage.write(false);
4670            if (!dexopt) {
4671                // We aren't going to dexopt, so bail early.
4672                return false;
4673            }
4674
4675            targetInstructionSet = instructionSet != null ? instructionSet :
4676                    getPrimaryInstructionSet(p.applicationInfo);
4677            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4678                return false;
4679            }
4680        }
4681
4682        synchronized (mInstallLock) {
4683            final String[] instructionSets = new String[] { targetInstructionSet };
4684            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4685                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4686        }
4687    }
4688
4689    public HashSet<String> getPackagesThatNeedDexOpt() {
4690        HashSet<String> pkgs = null;
4691        synchronized (mPackages) {
4692            for (PackageParser.Package p : mPackages.values()) {
4693                if (DEBUG_DEXOPT) {
4694                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4695                }
4696                if (!p.mDexOptPerformed.isEmpty()) {
4697                    continue;
4698                }
4699                if (pkgs == null) {
4700                    pkgs = new HashSet<String>();
4701                }
4702                pkgs.add(p.packageName);
4703            }
4704        }
4705        return pkgs;
4706    }
4707
4708    public void shutdown() {
4709        mPackageUsage.write(true);
4710    }
4711
4712    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4713             boolean forceDex, boolean defer, HashSet<String> done) {
4714        for (int i=0; i<libs.size(); i++) {
4715            PackageParser.Package libPkg;
4716            String libName;
4717            synchronized (mPackages) {
4718                libName = libs.get(i);
4719                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4720                if (lib != null && lib.apk != null) {
4721                    libPkg = mPackages.get(lib.apk);
4722                } else {
4723                    libPkg = null;
4724                }
4725            }
4726            if (libPkg != null && !done.contains(libName)) {
4727                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4728            }
4729        }
4730    }
4731
4732    static final int DEX_OPT_SKIPPED = 0;
4733    static final int DEX_OPT_PERFORMED = 1;
4734    static final int DEX_OPT_DEFERRED = 2;
4735    static final int DEX_OPT_FAILED = -1;
4736
4737    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4738            boolean forceDex, boolean defer, HashSet<String> done) {
4739        final String[] instructionSets = targetInstructionSets != null ?
4740                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4741
4742        if (done != null) {
4743            done.add(pkg.packageName);
4744            if (pkg.usesLibraries != null) {
4745                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4746            }
4747            if (pkg.usesOptionalLibraries != null) {
4748                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4749            }
4750        }
4751
4752        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4753            return DEX_OPT_SKIPPED;
4754        }
4755
4756        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4757
4758        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4759        boolean performedDexOpt = false;
4760        // There are three basic cases here:
4761        // 1.) we need to dexopt, either because we are forced or it is needed
4762        // 2.) we are defering a needed dexopt
4763        // 3.) we are skipping an unneeded dexopt
4764        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4765        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4766            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4767                continue;
4768            }
4769
4770            for (String path : paths) {
4771                try {
4772                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4773                    // patckage or the one we find does not match the image checksum (i.e. it was
4774                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4775                    // odex file and it matches the checksum of the image but not its base address,
4776                    // meaning we need to move it.
4777                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4778                            pkg.packageName, dexCodeInstructionSet, defer);
4779                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4780                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4781                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4782                                + " vmSafeMode=" + vmSafeMode);
4783                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4784                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4785                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4786
4787                        if (ret < 0) {
4788                            // Don't bother running dexopt again if we failed, it will probably
4789                            // just result in an error again. Also, don't bother dexopting for other
4790                            // paths & ISAs.
4791                            return DEX_OPT_FAILED;
4792                        }
4793
4794                        performedDexOpt = true;
4795                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4796                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4797                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4798                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4799                                pkg.packageName, dexCodeInstructionSet);
4800
4801                        if (ret < 0) {
4802                            // Don't bother running patchoat again if we failed, it will probably
4803                            // just result in an error again. Also, don't bother dexopting for other
4804                            // paths & ISAs.
4805                            return DEX_OPT_FAILED;
4806                        }
4807
4808                        performedDexOpt = true;
4809                    }
4810
4811                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4812                    // paths and instruction sets. We'll deal with them all together when we process
4813                    // our list of deferred dexopts.
4814                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4815                        if (mDeferredDexOpt == null) {
4816                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4817                        }
4818                        mDeferredDexOpt.add(pkg);
4819                        return DEX_OPT_DEFERRED;
4820                    }
4821                } catch (FileNotFoundException e) {
4822                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4823                    return DEX_OPT_FAILED;
4824                } catch (IOException e) {
4825                    Slog.w(TAG, "IOException reading apk: " + path, e);
4826                    return DEX_OPT_FAILED;
4827                } catch (StaleDexCacheError e) {
4828                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4829                    return DEX_OPT_FAILED;
4830                } catch (Exception e) {
4831                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4832                    return DEX_OPT_FAILED;
4833                }
4834            }
4835
4836            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4837            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4838            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4839            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4840            // it.
4841            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4842        }
4843
4844        // If we've gotten here, we're sure that no error occurred and that we haven't
4845        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4846        // we've skipped all of them because they are up to date. In both cases this
4847        // package doesn't need dexopt any longer.
4848        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4849    }
4850
4851    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4852        if (info.primaryCpuAbi != null) {
4853            if (info.secondaryCpuAbi != null) {
4854                return new String[] {
4855                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4856                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4857            } else {
4858                return new String[] {
4859                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4860            }
4861        }
4862
4863        return new String[] { getPreferredInstructionSet() };
4864    }
4865
4866    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4867        if (ps.primaryCpuAbiString != null) {
4868            if (ps.secondaryCpuAbiString != null) {
4869                return new String[] {
4870                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4871                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4872            } else {
4873                return new String[] {
4874                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4875            }
4876        }
4877
4878        return new String[] { getPreferredInstructionSet() };
4879    }
4880
4881    private static String getPreferredInstructionSet() {
4882        if (sPreferredInstructionSet == null) {
4883            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4884        }
4885
4886        return sPreferredInstructionSet;
4887    }
4888
4889    private static List<String> getAllInstructionSets() {
4890        final String[] allAbis = Build.SUPPORTED_ABIS;
4891        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4892
4893        for (String abi : allAbis) {
4894            final String instructionSet = VMRuntime.getInstructionSet(abi);
4895            if (!allInstructionSets.contains(instructionSet)) {
4896                allInstructionSets.add(instructionSet);
4897            }
4898        }
4899
4900        return allInstructionSets;
4901    }
4902
4903    /**
4904     * Returns the instruction set that should be used to compile dex code. In the presence of
4905     * a native bridge this might be different than the one shared libraries use.
4906     */
4907    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4908        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4909        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4910    }
4911
4912    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4913        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4914        for (String instructionSet : instructionSets) {
4915            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4916        }
4917        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4918    }
4919
4920    /**
4921     * Returns deduplicated list of supported instructions for dex code.
4922     */
4923    public static String[] getAllDexCodeInstructionSets() {
4924        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4925        for (int i = 0; i < supportedInstructionSets.length; i++) {
4926            String abi = Build.SUPPORTED_ABIS[i];
4927            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4928        }
4929        return getDexCodeInstructionSets(supportedInstructionSets);
4930    }
4931
4932    @Override
4933    public void forceDexOpt(String packageName) {
4934        enforceSystemOrRoot("forceDexOpt");
4935
4936        PackageParser.Package pkg;
4937        synchronized (mPackages) {
4938            pkg = mPackages.get(packageName);
4939            if (pkg == null) {
4940                throw new IllegalArgumentException("Missing package: " + packageName);
4941            }
4942        }
4943
4944        synchronized (mInstallLock) {
4945            final String[] instructionSets = new String[] {
4946                    getPrimaryInstructionSet(pkg.applicationInfo) };
4947            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4948            if (res != DEX_OPT_PERFORMED) {
4949                throw new IllegalStateException("Failed to dexopt: " + res);
4950            }
4951        }
4952    }
4953
4954    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4955                                boolean forceDex, boolean defer, boolean inclDependencies) {
4956        HashSet<String> done;
4957        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4958            done = new HashSet<String>();
4959            done.add(pkg.packageName);
4960        } else {
4961            done = null;
4962        }
4963        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4964    }
4965
4966    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4967        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4968            Slog.w(TAG, "Unable to update from " + oldPkg.name
4969                    + " to " + newPkg.packageName
4970                    + ": old package not in system partition");
4971            return false;
4972        } else if (mPackages.get(oldPkg.name) != null) {
4973            Slog.w(TAG, "Unable to update from " + oldPkg.name
4974                    + " to " + newPkg.packageName
4975                    + ": old package still exists");
4976            return false;
4977        }
4978        return true;
4979    }
4980
4981    File getDataPathForUser(int userId) {
4982        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4983    }
4984
4985    private File getDataPathForPackage(String packageName, int userId) {
4986        /*
4987         * Until we fully support multiple users, return the directory we
4988         * previously would have. The PackageManagerTests will need to be
4989         * revised when this is changed back..
4990         */
4991        if (userId == 0) {
4992            return new File(mAppDataDir, packageName);
4993        } else {
4994            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4995                + File.separator + packageName);
4996        }
4997    }
4998
4999    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5000        int[] users = sUserManager.getUserIds();
5001        int res = mInstaller.install(packageName, uid, uid, seinfo);
5002        if (res < 0) {
5003            return res;
5004        }
5005        for (int user : users) {
5006            if (user != 0) {
5007                res = mInstaller.createUserData(packageName,
5008                        UserHandle.getUid(user, uid), user, seinfo);
5009                if (res < 0) {
5010                    return res;
5011                }
5012            }
5013        }
5014        return res;
5015    }
5016
5017    private int removeDataDirsLI(String packageName) {
5018        int[] users = sUserManager.getUserIds();
5019        int res = 0;
5020        for (int user : users) {
5021            int resInner = mInstaller.remove(packageName, user);
5022            if (resInner < 0) {
5023                res = resInner;
5024            }
5025        }
5026
5027        return res;
5028    }
5029
5030    private int deleteCodeCacheDirsLI(String packageName) {
5031        int[] users = sUserManager.getUserIds();
5032        int res = 0;
5033        for (int user : users) {
5034            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5035            if (resInner < 0) {
5036                res = resInner;
5037            }
5038        }
5039        return res;
5040    }
5041
5042    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5043            PackageParser.Package changingLib) {
5044        if (file.path != null) {
5045            usesLibraryFiles.add(file.path);
5046            return;
5047        }
5048        PackageParser.Package p = mPackages.get(file.apk);
5049        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5050            // If we are doing this while in the middle of updating a library apk,
5051            // then we need to make sure to use that new apk for determining the
5052            // dependencies here.  (We haven't yet finished committing the new apk
5053            // to the package manager state.)
5054            if (p == null || p.packageName.equals(changingLib.packageName)) {
5055                p = changingLib;
5056            }
5057        }
5058        if (p != null) {
5059            usesLibraryFiles.addAll(p.getAllCodePaths());
5060        }
5061    }
5062
5063    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5064            PackageParser.Package changingLib) throws PackageManagerException {
5065        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5066            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5067            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5068            for (int i=0; i<N; i++) {
5069                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5070                if (file == null) {
5071                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5072                            "Package " + pkg.packageName + " requires unavailable shared library "
5073                            + pkg.usesLibraries.get(i) + "; failing!");
5074                }
5075                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5076            }
5077            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5078            for (int i=0; i<N; i++) {
5079                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5080                if (file == null) {
5081                    Slog.w(TAG, "Package " + pkg.packageName
5082                            + " desires unavailable shared library "
5083                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5084                } else {
5085                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5086                }
5087            }
5088            N = usesLibraryFiles.size();
5089            if (N > 0) {
5090                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5091            } else {
5092                pkg.usesLibraryFiles = null;
5093            }
5094        }
5095    }
5096
5097    private static boolean hasString(List<String> list, List<String> which) {
5098        if (list == null) {
5099            return false;
5100        }
5101        for (int i=list.size()-1; i>=0; i--) {
5102            for (int j=which.size()-1; j>=0; j--) {
5103                if (which.get(j).equals(list.get(i))) {
5104                    return true;
5105                }
5106            }
5107        }
5108        return false;
5109    }
5110
5111    private void updateAllSharedLibrariesLPw() {
5112        for (PackageParser.Package pkg : mPackages.values()) {
5113            try {
5114                updateSharedLibrariesLPw(pkg, null);
5115            } catch (PackageManagerException e) {
5116                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5117            }
5118        }
5119    }
5120
5121    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5122            PackageParser.Package changingPkg) {
5123        ArrayList<PackageParser.Package> res = null;
5124        for (PackageParser.Package pkg : mPackages.values()) {
5125            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5126                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5127                if (res == null) {
5128                    res = new ArrayList<PackageParser.Package>();
5129                }
5130                res.add(pkg);
5131                try {
5132                    updateSharedLibrariesLPw(pkg, changingPkg);
5133                } catch (PackageManagerException e) {
5134                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5135                }
5136            }
5137        }
5138        return res;
5139    }
5140
5141    /**
5142     * Derive the value of the {@code cpuAbiOverride} based on the provided
5143     * value and an optional stored value from the package settings.
5144     */
5145    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5146        String cpuAbiOverride = null;
5147
5148        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5149            cpuAbiOverride = null;
5150        } else if (abiOverride != null) {
5151            cpuAbiOverride = abiOverride;
5152        } else if (settings != null) {
5153            cpuAbiOverride = settings.cpuAbiOverrideString;
5154        }
5155
5156        return cpuAbiOverride;
5157    }
5158
5159    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5160            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5161        boolean success = false;
5162        try {
5163            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5164                    currentTime, user);
5165            success = true;
5166            return res;
5167        } finally {
5168            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5169                removeDataDirsLI(pkg.packageName);
5170            }
5171        }
5172    }
5173
5174    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5175            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5176        final File scanFile = new File(pkg.codePath);
5177        if (pkg.applicationInfo.getCodePath() == null ||
5178                pkg.applicationInfo.getResourcePath() == null) {
5179            // Bail out. The resource and code paths haven't been set.
5180            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5181                    "Code and resource paths haven't been set correctly");
5182        }
5183
5184        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5185            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5186        } else {
5187            // Only allow system apps to be flagged as core apps.
5188            pkg.coreApp = false;
5189        }
5190
5191        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5192            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5193        }
5194
5195        if (mCustomResolverComponentName != null &&
5196                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5197            setUpCustomResolverActivity(pkg);
5198        }
5199
5200        if (pkg.packageName.equals("android")) {
5201            synchronized (mPackages) {
5202                if (mAndroidApplication != null) {
5203                    Slog.w(TAG, "*************************************************");
5204                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5205                    Slog.w(TAG, " file=" + scanFile);
5206                    Slog.w(TAG, "*************************************************");
5207                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5208                            "Core android package being redefined.  Skipping.");
5209                }
5210
5211                // Set up information for our fall-back user intent resolution activity.
5212                mPlatformPackage = pkg;
5213                pkg.mVersionCode = mSdkVersion;
5214                mAndroidApplication = pkg.applicationInfo;
5215
5216                if (!mResolverReplaced) {
5217                    mResolveActivity.applicationInfo = mAndroidApplication;
5218                    mResolveActivity.name = ResolverActivity.class.getName();
5219                    mResolveActivity.packageName = mAndroidApplication.packageName;
5220                    mResolveActivity.processName = "system:ui";
5221                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5222                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5223                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5224                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5225                    mResolveActivity.exported = true;
5226                    mResolveActivity.enabled = true;
5227                    mResolveInfo.activityInfo = mResolveActivity;
5228                    mResolveInfo.priority = 0;
5229                    mResolveInfo.preferredOrder = 0;
5230                    mResolveInfo.match = 0;
5231                    mResolveComponentName = new ComponentName(
5232                            mAndroidApplication.packageName, mResolveActivity.name);
5233                }
5234            }
5235        }
5236
5237        if (DEBUG_PACKAGE_SCANNING) {
5238            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5239                Log.d(TAG, "Scanning package " + pkg.packageName);
5240        }
5241
5242        if (mPackages.containsKey(pkg.packageName)
5243                || mSharedLibraries.containsKey(pkg.packageName)) {
5244            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5245                    "Application package " + pkg.packageName
5246                    + " already installed.  Skipping duplicate.");
5247        }
5248
5249        // Initialize package source and resource directories
5250        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5251        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5252
5253        SharedUserSetting suid = null;
5254        PackageSetting pkgSetting = null;
5255
5256        if (!isSystemApp(pkg)) {
5257            // Only system apps can use these features.
5258            pkg.mOriginalPackages = null;
5259            pkg.mRealPackage = null;
5260            pkg.mAdoptPermissions = null;
5261        }
5262
5263        // writer
5264        synchronized (mPackages) {
5265            if (pkg.mSharedUserId != null) {
5266                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5267                if (suid == null) {
5268                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5269                            "Creating application package " + pkg.packageName
5270                            + " for shared user failed");
5271                }
5272                if (DEBUG_PACKAGE_SCANNING) {
5273                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5274                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5275                                + "): packages=" + suid.packages);
5276                }
5277            }
5278
5279            // Check if we are renaming from an original package name.
5280            PackageSetting origPackage = null;
5281            String realName = null;
5282            if (pkg.mOriginalPackages != null) {
5283                // This package may need to be renamed to a previously
5284                // installed name.  Let's check on that...
5285                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5286                if (pkg.mOriginalPackages.contains(renamed)) {
5287                    // This package had originally been installed as the
5288                    // original name, and we have already taken care of
5289                    // transitioning to the new one.  Just update the new
5290                    // one to continue using the old name.
5291                    realName = pkg.mRealPackage;
5292                    if (!pkg.packageName.equals(renamed)) {
5293                        // Callers into this function may have already taken
5294                        // care of renaming the package; only do it here if
5295                        // it is not already done.
5296                        pkg.setPackageName(renamed);
5297                    }
5298
5299                } else {
5300                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5301                        if ((origPackage = mSettings.peekPackageLPr(
5302                                pkg.mOriginalPackages.get(i))) != null) {
5303                            // We do have the package already installed under its
5304                            // original name...  should we use it?
5305                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5306                                // New package is not compatible with original.
5307                                origPackage = null;
5308                                continue;
5309                            } else if (origPackage.sharedUser != null) {
5310                                // Make sure uid is compatible between packages.
5311                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5312                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5313                                            + " to " + pkg.packageName + ": old uid "
5314                                            + origPackage.sharedUser.name
5315                                            + " differs from " + pkg.mSharedUserId);
5316                                    origPackage = null;
5317                                    continue;
5318                                }
5319                            } else {
5320                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5321                                        + pkg.packageName + " to old name " + origPackage.name);
5322                            }
5323                            break;
5324                        }
5325                    }
5326                }
5327            }
5328
5329            if (mTransferedPackages.contains(pkg.packageName)) {
5330                Slog.w(TAG, "Package " + pkg.packageName
5331                        + " was transferred to another, but its .apk remains");
5332            }
5333
5334            // Just create the setting, don't add it yet. For already existing packages
5335            // the PkgSetting exists already and doesn't have to be created.
5336            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5337                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5338                    pkg.applicationInfo.primaryCpuAbi,
5339                    pkg.applicationInfo.secondaryCpuAbi,
5340                    pkg.applicationInfo.flags, user, false);
5341            if (pkgSetting == null) {
5342                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5343                        "Creating application package " + pkg.packageName + " failed");
5344            }
5345
5346            if (pkgSetting.origPackage != null) {
5347                // If we are first transitioning from an original package,
5348                // fix up the new package's name now.  We need to do this after
5349                // looking up the package under its new name, so getPackageLP
5350                // can take care of fiddling things correctly.
5351                pkg.setPackageName(origPackage.name);
5352
5353                // File a report about this.
5354                String msg = "New package " + pkgSetting.realName
5355                        + " renamed to replace old package " + pkgSetting.name;
5356                reportSettingsProblem(Log.WARN, msg);
5357
5358                // Make a note of it.
5359                mTransferedPackages.add(origPackage.name);
5360
5361                // No longer need to retain this.
5362                pkgSetting.origPackage = null;
5363            }
5364
5365            if (realName != null) {
5366                // Make a note of it.
5367                mTransferedPackages.add(pkg.packageName);
5368            }
5369
5370            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5371                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5372            }
5373
5374            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5375                // Check all shared libraries and map to their actual file path.
5376                // We only do this here for apps not on a system dir, because those
5377                // are the only ones that can fail an install due to this.  We
5378                // will take care of the system apps by updating all of their
5379                // library paths after the scan is done.
5380                updateSharedLibrariesLPw(pkg, null);
5381            }
5382
5383            if (mFoundPolicyFile) {
5384                SELinuxMMAC.assignSeinfoValue(pkg);
5385            }
5386
5387            pkg.applicationInfo.uid = pkgSetting.appId;
5388            pkg.mExtras = pkgSetting;
5389            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5390                try {
5391                    verifySignaturesLP(pkgSetting, pkg);
5392                } catch (PackageManagerException e) {
5393                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5394                        throw e;
5395                    }
5396                    // The signature has changed, but this package is in the system
5397                    // image...  let's recover!
5398                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5399                    // However...  if this package is part of a shared user, but it
5400                    // doesn't match the signature of the shared user, let's fail.
5401                    // What this means is that you can't change the signatures
5402                    // associated with an overall shared user, which doesn't seem all
5403                    // that unreasonable.
5404                    if (pkgSetting.sharedUser != null) {
5405                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5406                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5407                            throw new PackageManagerException(
5408                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5409                                            "Signature mismatch for shared user : "
5410                                            + pkgSetting.sharedUser);
5411                        }
5412                    }
5413                    // File a report about this.
5414                    String msg = "System package " + pkg.packageName
5415                        + " signature changed; retaining data.";
5416                    reportSettingsProblem(Log.WARN, msg);
5417                }
5418            } else {
5419                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5420                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5421                            + pkg.packageName + " upgrade keys do not match the "
5422                            + "previously installed version");
5423                } else {
5424                    // signatures may have changed as result of upgrade
5425                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5426                }
5427            }
5428            // Verify that this new package doesn't have any content providers
5429            // that conflict with existing packages.  Only do this if the
5430            // package isn't already installed, since we don't want to break
5431            // things that are installed.
5432            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5433                final int N = pkg.providers.size();
5434                int i;
5435                for (i=0; i<N; i++) {
5436                    PackageParser.Provider p = pkg.providers.get(i);
5437                    if (p.info.authority != null) {
5438                        String names[] = p.info.authority.split(";");
5439                        for (int j = 0; j < names.length; j++) {
5440                            if (mProvidersByAuthority.containsKey(names[j])) {
5441                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5442                                final String otherPackageName =
5443                                        ((other != null && other.getComponentName() != null) ?
5444                                                other.getComponentName().getPackageName() : "?");
5445                                throw new PackageManagerException(
5446                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5447                                                "Can't install because provider name " + names[j]
5448                                                + " (in package " + pkg.applicationInfo.packageName
5449                                                + ") is already used by " + otherPackageName);
5450                            }
5451                        }
5452                    }
5453                }
5454            }
5455
5456            if (pkg.mAdoptPermissions != null) {
5457                // This package wants to adopt ownership of permissions from
5458                // another package.
5459                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5460                    final String origName = pkg.mAdoptPermissions.get(i);
5461                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5462                    if (orig != null) {
5463                        if (verifyPackageUpdateLPr(orig, pkg)) {
5464                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5465                                    + pkg.packageName);
5466                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5467                        }
5468                    }
5469                }
5470            }
5471        }
5472
5473        final String pkgName = pkg.packageName;
5474
5475        final long scanFileTime = scanFile.lastModified();
5476        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5477        pkg.applicationInfo.processName = fixProcessName(
5478                pkg.applicationInfo.packageName,
5479                pkg.applicationInfo.processName,
5480                pkg.applicationInfo.uid);
5481
5482        File dataPath;
5483        if (mPlatformPackage == pkg) {
5484            // The system package is special.
5485            dataPath = new File(Environment.getDataDirectory(), "system");
5486
5487            pkg.applicationInfo.dataDir = dataPath.getPath();
5488
5489        } else {
5490            // This is a normal package, need to make its data directory.
5491            dataPath = getDataPathForPackage(pkg.packageName, 0);
5492
5493            boolean uidError = false;
5494            if (dataPath.exists()) {
5495                int currentUid = 0;
5496                try {
5497                    StructStat stat = Os.stat(dataPath.getPath());
5498                    currentUid = stat.st_uid;
5499                } catch (ErrnoException e) {
5500                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5501                }
5502
5503                // If we have mismatched owners for the data path, we have a problem.
5504                if (currentUid != pkg.applicationInfo.uid) {
5505                    boolean recovered = false;
5506                    if (currentUid == 0) {
5507                        // The directory somehow became owned by root.  Wow.
5508                        // This is probably because the system was stopped while
5509                        // installd was in the middle of messing with its libs
5510                        // directory.  Ask installd to fix that.
5511                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5512                                pkg.applicationInfo.uid);
5513                        if (ret >= 0) {
5514                            recovered = true;
5515                            String msg = "Package " + pkg.packageName
5516                                    + " unexpectedly changed to uid 0; recovered to " +
5517                                    + pkg.applicationInfo.uid;
5518                            reportSettingsProblem(Log.WARN, msg);
5519                        }
5520                    }
5521                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5522                            || (scanFlags&SCAN_BOOTING) != 0)) {
5523                        // If this is a system app, we can at least delete its
5524                        // current data so the application will still work.
5525                        int ret = removeDataDirsLI(pkgName);
5526                        if (ret >= 0) {
5527                            // TODO: Kill the processes first
5528                            // Old data gone!
5529                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5530                                    ? "System package " : "Third party package ";
5531                            String msg = prefix + pkg.packageName
5532                                    + " has changed from uid: "
5533                                    + currentUid + " to "
5534                                    + pkg.applicationInfo.uid + "; old data erased";
5535                            reportSettingsProblem(Log.WARN, msg);
5536                            recovered = true;
5537
5538                            // And now re-install the app.
5539                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5540                                                   pkg.applicationInfo.seinfo);
5541                            if (ret == -1) {
5542                                // Ack should not happen!
5543                                msg = prefix + pkg.packageName
5544                                        + " could not have data directory re-created after delete.";
5545                                reportSettingsProblem(Log.WARN, msg);
5546                                throw new PackageManagerException(
5547                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5548                            }
5549                        }
5550                        if (!recovered) {
5551                            mHasSystemUidErrors = true;
5552                        }
5553                    } else if (!recovered) {
5554                        // If we allow this install to proceed, we will be broken.
5555                        // Abort, abort!
5556                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5557                                "scanPackageLI");
5558                    }
5559                    if (!recovered) {
5560                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5561                            + pkg.applicationInfo.uid + "/fs_"
5562                            + currentUid;
5563                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5564                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5565                        String msg = "Package " + pkg.packageName
5566                                + " has mismatched uid: "
5567                                + currentUid + " on disk, "
5568                                + pkg.applicationInfo.uid + " in settings";
5569                        // writer
5570                        synchronized (mPackages) {
5571                            mSettings.mReadMessages.append(msg);
5572                            mSettings.mReadMessages.append('\n');
5573                            uidError = true;
5574                            if (!pkgSetting.uidError) {
5575                                reportSettingsProblem(Log.ERROR, msg);
5576                            }
5577                        }
5578                    }
5579                }
5580                pkg.applicationInfo.dataDir = dataPath.getPath();
5581                if (mShouldRestoreconData) {
5582                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5583                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5584                                pkg.applicationInfo.uid);
5585                }
5586            } else {
5587                if (DEBUG_PACKAGE_SCANNING) {
5588                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5589                        Log.v(TAG, "Want this data dir: " + dataPath);
5590                }
5591                //invoke installer to do the actual installation
5592                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5593                                           pkg.applicationInfo.seinfo);
5594                if (ret < 0) {
5595                    // Error from installer
5596                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5597                            "Unable to create data dirs [errorCode=" + ret + "]");
5598                }
5599
5600                if (dataPath.exists()) {
5601                    pkg.applicationInfo.dataDir = dataPath.getPath();
5602                } else {
5603                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5604                    pkg.applicationInfo.dataDir = null;
5605                }
5606            }
5607
5608            pkgSetting.uidError = uidError;
5609        }
5610
5611        final String path = scanFile.getPath();
5612        final String codePath = pkg.applicationInfo.getCodePath();
5613        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5614        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5615            setBundledAppAbisAndRoots(pkg, pkgSetting);
5616
5617            // If we haven't found any native libraries for the app, check if it has
5618            // renderscript code. We'll need to force the app to 32 bit if it has
5619            // renderscript bitcode.
5620            if (pkg.applicationInfo.primaryCpuAbi == null
5621                    && pkg.applicationInfo.secondaryCpuAbi == null
5622                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5623                NativeLibraryHelper.Handle handle = null;
5624                try {
5625                    handle = NativeLibraryHelper.Handle.create(scanFile);
5626                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5627                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5628                    }
5629                } catch (IOException ioe) {
5630                    Slog.w(TAG, "Error scanning system app : " + ioe);
5631                } finally {
5632                    IoUtils.closeQuietly(handle);
5633                }
5634            }
5635
5636            setNativeLibraryPaths(pkg);
5637        } else {
5638            // TODO: We can probably be smarter about this stuff. For installed apps,
5639            // we can calculate this information at install time once and for all. For
5640            // system apps, we can probably assume that this information doesn't change
5641            // after the first boot scan. As things stand, we do lots of unnecessary work.
5642
5643            // Give ourselves some initial paths; we'll come back for another
5644            // pass once we've determined ABI below.
5645            setNativeLibraryPaths(pkg);
5646
5647            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5648            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5649            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5650
5651            NativeLibraryHelper.Handle handle = null;
5652            try {
5653                handle = NativeLibraryHelper.Handle.create(scanFile);
5654                // TODO(multiArch): This can be null for apps that didn't go through the
5655                // usual installation process. We can calculate it again, like we
5656                // do during install time.
5657                //
5658                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5659                // unnecessary.
5660                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5661
5662                // Null out the abis so that they can be recalculated.
5663                pkg.applicationInfo.primaryCpuAbi = null;
5664                pkg.applicationInfo.secondaryCpuAbi = null;
5665                if (isMultiArch(pkg.applicationInfo)) {
5666                    // Warn if we've set an abiOverride for multi-lib packages..
5667                    // By definition, we need to copy both 32 and 64 bit libraries for
5668                    // such packages.
5669                    if (pkg.cpuAbiOverride != null
5670                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5671                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5672                    }
5673
5674                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5675                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5676                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5677                        if (isAsec) {
5678                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5679                        } else {
5680                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5681                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5682                                    useIsaSpecificSubdirs);
5683                        }
5684                    }
5685
5686                    maybeThrowExceptionForMultiArchCopy(
5687                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5688
5689                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5690                        if (isAsec) {
5691                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5692                        } else {
5693                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5694                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5695                                    useIsaSpecificSubdirs);
5696                        }
5697                    }
5698
5699                    maybeThrowExceptionForMultiArchCopy(
5700                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5701
5702                    if (abi64 >= 0) {
5703                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5704                    }
5705
5706                    if (abi32 >= 0) {
5707                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5708                        if (abi64 >= 0) {
5709                            pkg.applicationInfo.secondaryCpuAbi = abi;
5710                        } else {
5711                            pkg.applicationInfo.primaryCpuAbi = abi;
5712                        }
5713                    }
5714                } else {
5715                    String[] abiList = (cpuAbiOverride != null) ?
5716                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5717
5718                    // Enable gross and lame hacks for apps that are built with old
5719                    // SDK tools. We must scan their APKs for renderscript bitcode and
5720                    // not launch them if it's present. Don't bother checking on devices
5721                    // that don't have 64 bit support.
5722                    boolean needsRenderScriptOverride = false;
5723                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5724                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5725                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5726                        needsRenderScriptOverride = true;
5727                    }
5728
5729                    final int copyRet;
5730                    if (isAsec) {
5731                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5732                    } else {
5733                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5734                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5735                    }
5736
5737                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5738                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5739                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5740                    }
5741
5742                    if (copyRet >= 0) {
5743                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5744                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5745                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5746                    } else if (needsRenderScriptOverride) {
5747                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5748                    }
5749                }
5750            } catch (IOException ioe) {
5751                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5752            } finally {
5753                IoUtils.closeQuietly(handle);
5754            }
5755
5756            // Now that we've calculated the ABIs and determined if it's an internal app,
5757            // we will go ahead and populate the nativeLibraryPath.
5758            setNativeLibraryPaths(pkg);
5759
5760            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5761            final int[] userIds = sUserManager.getUserIds();
5762            synchronized (mInstallLock) {
5763                // Create a native library symlink only if we have native libraries
5764                // and if the native libraries are 32 bit libraries. We do not provide
5765                // this symlink for 64 bit libraries.
5766                if (pkg.applicationInfo.primaryCpuAbi != null &&
5767                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5768                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5769                    for (int userId : userIds) {
5770                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5771                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5772                                    "Failed linking native library dir (user=" + userId + ")");
5773                        }
5774                    }
5775                }
5776            }
5777        }
5778
5779        // This is a special case for the "system" package, where the ABI is
5780        // dictated by the zygote configuration (and init.rc). We should keep track
5781        // of this ABI so that we can deal with "normal" applications that run under
5782        // the same UID correctly.
5783        if (mPlatformPackage == pkg) {
5784            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5785                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5786        }
5787
5788        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5789        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5790        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5791        // Copy the derived override back to the parsed package, so that we can
5792        // update the package settings accordingly.
5793        pkg.cpuAbiOverride = cpuAbiOverride;
5794
5795        if (DEBUG_ABI_SELECTION) {
5796            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5797                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5798                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5799        }
5800
5801        // Push the derived path down into PackageSettings so we know what to
5802        // clean up at uninstall time.
5803        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5804
5805        if (DEBUG_ABI_SELECTION) {
5806            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5807                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5808                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5809        }
5810
5811        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5812            // We don't do this here during boot because we can do it all
5813            // at once after scanning all existing packages.
5814            //
5815            // We also do this *before* we perform dexopt on this package, so that
5816            // we can avoid redundant dexopts, and also to make sure we've got the
5817            // code and package path correct.
5818            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5819                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5820        }
5821
5822        if ((scanFlags & SCAN_NO_DEX) == 0) {
5823            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5824                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5825                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5826            }
5827        }
5828
5829        if (mFactoryTest && pkg.requestedPermissions.contains(
5830                android.Manifest.permission.FACTORY_TEST)) {
5831            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5832        }
5833
5834        ArrayList<PackageParser.Package> clientLibPkgs = null;
5835
5836        // writer
5837        synchronized (mPackages) {
5838            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5839                // Only system apps can add new shared libraries.
5840                if (pkg.libraryNames != null) {
5841                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5842                        String name = pkg.libraryNames.get(i);
5843                        boolean allowed = false;
5844                        if (isUpdatedSystemApp(pkg)) {
5845                            // New library entries can only be added through the
5846                            // system image.  This is important to get rid of a lot
5847                            // of nasty edge cases: for example if we allowed a non-
5848                            // system update of the app to add a library, then uninstalling
5849                            // the update would make the library go away, and assumptions
5850                            // we made such as through app install filtering would now
5851                            // have allowed apps on the device which aren't compatible
5852                            // with it.  Better to just have the restriction here, be
5853                            // conservative, and create many fewer cases that can negatively
5854                            // impact the user experience.
5855                            final PackageSetting sysPs = mSettings
5856                                    .getDisabledSystemPkgLPr(pkg.packageName);
5857                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5858                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5859                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5860                                        allowed = true;
5861                                        allowed = true;
5862                                        break;
5863                                    }
5864                                }
5865                            }
5866                        } else {
5867                            allowed = true;
5868                        }
5869                        if (allowed) {
5870                            if (!mSharedLibraries.containsKey(name)) {
5871                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5872                            } else if (!name.equals(pkg.packageName)) {
5873                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5874                                        + name + " already exists; skipping");
5875                            }
5876                        } else {
5877                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5878                                    + name + " that is not declared on system image; skipping");
5879                        }
5880                    }
5881                    if ((scanFlags&SCAN_BOOTING) == 0) {
5882                        // If we are not booting, we need to update any applications
5883                        // that are clients of our shared library.  If we are booting,
5884                        // this will all be done once the scan is complete.
5885                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5886                    }
5887                }
5888            }
5889        }
5890
5891        // We also need to dexopt any apps that are dependent on this library.  Note that
5892        // if these fail, we should abort the install since installing the library will
5893        // result in some apps being broken.
5894        if (clientLibPkgs != null) {
5895            if ((scanFlags & SCAN_NO_DEX) == 0) {
5896                for (int i = 0; i < clientLibPkgs.size(); i++) {
5897                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5898                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5899                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5900                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5901                                "scanPackageLI failed to dexopt clientLibPkgs");
5902                    }
5903                }
5904            }
5905        }
5906
5907        // Request the ActivityManager to kill the process(only for existing packages)
5908        // so that we do not end up in a confused state while the user is still using the older
5909        // version of the application while the new one gets installed.
5910        if ((scanFlags & SCAN_REPLACING) != 0) {
5911            killApplication(pkg.applicationInfo.packageName,
5912                        pkg.applicationInfo.uid, "update pkg");
5913        }
5914
5915        // Also need to kill any apps that are dependent on the library.
5916        if (clientLibPkgs != null) {
5917            for (int i=0; i<clientLibPkgs.size(); i++) {
5918                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5919                killApplication(clientPkg.applicationInfo.packageName,
5920                        clientPkg.applicationInfo.uid, "update lib");
5921            }
5922        }
5923
5924        // writer
5925        synchronized (mPackages) {
5926            // We don't expect installation to fail beyond this point
5927
5928            // Add the new setting to mSettings
5929            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5930            // Add the new setting to mPackages
5931            mPackages.put(pkg.applicationInfo.packageName, pkg);
5932            // Make sure we don't accidentally delete its data.
5933            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5934            while (iter.hasNext()) {
5935                PackageCleanItem item = iter.next();
5936                if (pkgName.equals(item.packageName)) {
5937                    iter.remove();
5938                }
5939            }
5940
5941            // Take care of first install / last update times.
5942            if (currentTime != 0) {
5943                if (pkgSetting.firstInstallTime == 0) {
5944                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5945                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5946                    pkgSetting.lastUpdateTime = currentTime;
5947                }
5948            } else if (pkgSetting.firstInstallTime == 0) {
5949                // We need *something*.  Take time time stamp of the file.
5950                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5951            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5952                if (scanFileTime != pkgSetting.timeStamp) {
5953                    // A package on the system image has changed; consider this
5954                    // to be an update.
5955                    pkgSetting.lastUpdateTime = scanFileTime;
5956                }
5957            }
5958
5959            // Add the package's KeySets to the global KeySetManagerService
5960            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5961            try {
5962                // Old KeySetData no longer valid.
5963                ksms.removeAppKeySetDataLPw(pkg.packageName);
5964                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5965                if (pkg.mKeySetMapping != null) {
5966                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5967                            pkg.mKeySetMapping.entrySet()) {
5968                        if (entry.getValue() != null) {
5969                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5970                                                          entry.getValue(), entry.getKey());
5971                        }
5972                    }
5973                    if (pkg.mUpgradeKeySets != null) {
5974                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5975                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5976                        }
5977                    }
5978                }
5979            } catch (NullPointerException e) {
5980                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5981            } catch (IllegalArgumentException e) {
5982                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5983            }
5984
5985            int N = pkg.providers.size();
5986            StringBuilder r = null;
5987            int i;
5988            for (i=0; i<N; i++) {
5989                PackageParser.Provider p = pkg.providers.get(i);
5990                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5991                        p.info.processName, pkg.applicationInfo.uid);
5992                mProviders.addProvider(p);
5993                p.syncable = p.info.isSyncable;
5994                if (p.info.authority != null) {
5995                    String names[] = p.info.authority.split(";");
5996                    p.info.authority = null;
5997                    for (int j = 0; j < names.length; j++) {
5998                        if (j == 1 && p.syncable) {
5999                            // We only want the first authority for a provider to possibly be
6000                            // syncable, so if we already added this provider using a different
6001                            // authority clear the syncable flag. We copy the provider before
6002                            // changing it because the mProviders object contains a reference
6003                            // to a provider that we don't want to change.
6004                            // Only do this for the second authority since the resulting provider
6005                            // object can be the same for all future authorities for this provider.
6006                            p = new PackageParser.Provider(p);
6007                            p.syncable = false;
6008                        }
6009                        if (!mProvidersByAuthority.containsKey(names[j])) {
6010                            mProvidersByAuthority.put(names[j], p);
6011                            if (p.info.authority == null) {
6012                                p.info.authority = names[j];
6013                            } else {
6014                                p.info.authority = p.info.authority + ";" + names[j];
6015                            }
6016                            if (DEBUG_PACKAGE_SCANNING) {
6017                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6018                                    Log.d(TAG, "Registered content provider: " + names[j]
6019                                            + ", className = " + p.info.name + ", isSyncable = "
6020                                            + p.info.isSyncable);
6021                            }
6022                        } else {
6023                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6024                            Slog.w(TAG, "Skipping provider name " + names[j] +
6025                                    " (in package " + pkg.applicationInfo.packageName +
6026                                    "): name already used by "
6027                                    + ((other != null && other.getComponentName() != null)
6028                                            ? other.getComponentName().getPackageName() : "?"));
6029                        }
6030                    }
6031                }
6032                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6033                    if (r == null) {
6034                        r = new StringBuilder(256);
6035                    } else {
6036                        r.append(' ');
6037                    }
6038                    r.append(p.info.name);
6039                }
6040            }
6041            if (r != null) {
6042                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6043            }
6044
6045            N = pkg.services.size();
6046            r = null;
6047            for (i=0; i<N; i++) {
6048                PackageParser.Service s = pkg.services.get(i);
6049                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6050                        s.info.processName, pkg.applicationInfo.uid);
6051                mServices.addService(s);
6052                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6053                    if (r == null) {
6054                        r = new StringBuilder(256);
6055                    } else {
6056                        r.append(' ');
6057                    }
6058                    r.append(s.info.name);
6059                }
6060            }
6061            if (r != null) {
6062                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6063            }
6064
6065            N = pkg.receivers.size();
6066            r = null;
6067            for (i=0; i<N; i++) {
6068                PackageParser.Activity a = pkg.receivers.get(i);
6069                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6070                        a.info.processName, pkg.applicationInfo.uid);
6071                mReceivers.addActivity(a, "receiver");
6072                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6073                    if (r == null) {
6074                        r = new StringBuilder(256);
6075                    } else {
6076                        r.append(' ');
6077                    }
6078                    r.append(a.info.name);
6079                }
6080            }
6081            if (r != null) {
6082                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6083            }
6084
6085            N = pkg.activities.size();
6086            r = null;
6087            for (i=0; i<N; i++) {
6088                PackageParser.Activity a = pkg.activities.get(i);
6089                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6090                        a.info.processName, pkg.applicationInfo.uid);
6091                mActivities.addActivity(a, "activity");
6092                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6093                    if (r == null) {
6094                        r = new StringBuilder(256);
6095                    } else {
6096                        r.append(' ');
6097                    }
6098                    r.append(a.info.name);
6099                }
6100            }
6101            if (r != null) {
6102                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6103            }
6104
6105            N = pkg.permissionGroups.size();
6106            r = null;
6107            for (i=0; i<N; i++) {
6108                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6109                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6110                if (cur == null) {
6111                    mPermissionGroups.put(pg.info.name, pg);
6112                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6113                        if (r == null) {
6114                            r = new StringBuilder(256);
6115                        } else {
6116                            r.append(' ');
6117                        }
6118                        r.append(pg.info.name);
6119                    }
6120                } else {
6121                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6122                            + pg.info.packageName + " ignored: original from "
6123                            + cur.info.packageName);
6124                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6125                        if (r == null) {
6126                            r = new StringBuilder(256);
6127                        } else {
6128                            r.append(' ');
6129                        }
6130                        r.append("DUP:");
6131                        r.append(pg.info.name);
6132                    }
6133                }
6134            }
6135            if (r != null) {
6136                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6137            }
6138
6139            N = pkg.permissions.size();
6140            r = null;
6141            for (i=0; i<N; i++) {
6142                PackageParser.Permission p = pkg.permissions.get(i);
6143                HashMap<String, BasePermission> permissionMap =
6144                        p.tree ? mSettings.mPermissionTrees
6145                        : mSettings.mPermissions;
6146                p.group = mPermissionGroups.get(p.info.group);
6147                if (p.info.group == null || p.group != null) {
6148                    BasePermission bp = permissionMap.get(p.info.name);
6149
6150                    // Allow system apps to redefine non-system permissions
6151                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6152                        final boolean currentOwnerIsSystem = (bp.perm != null
6153                                && isSystemApp(bp.perm.owner));
6154                        if (isSystemApp(p.owner)) {
6155                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6156                                // It's a built-in permission and no owner, take ownership now
6157                                bp.packageSetting = pkgSetting;
6158                                bp.perm = p;
6159                                bp.uid = pkg.applicationInfo.uid;
6160                                bp.sourcePackage = p.info.packageName;
6161                            } else if (!currentOwnerIsSystem) {
6162                                String msg = "New decl " + p.owner + " of permission  "
6163                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6164                                reportSettingsProblem(Log.WARN, msg);
6165                                bp = null;
6166                            }
6167                        }
6168                    }
6169
6170                    if (bp == null) {
6171                        bp = new BasePermission(p.info.name, p.info.packageName,
6172                                BasePermission.TYPE_NORMAL);
6173                        permissionMap.put(p.info.name, bp);
6174                    }
6175
6176                    if (bp.perm == null) {
6177                        if (bp.sourcePackage == null
6178                                || bp.sourcePackage.equals(p.info.packageName)) {
6179                            BasePermission tree = findPermissionTreeLP(p.info.name);
6180                            if (tree == null
6181                                    || tree.sourcePackage.equals(p.info.packageName)) {
6182                                bp.packageSetting = pkgSetting;
6183                                bp.perm = p;
6184                                bp.uid = pkg.applicationInfo.uid;
6185                                bp.sourcePackage = p.info.packageName;
6186                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6187                                    if (r == null) {
6188                                        r = new StringBuilder(256);
6189                                    } else {
6190                                        r.append(' ');
6191                                    }
6192                                    r.append(p.info.name);
6193                                }
6194                            } else {
6195                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6196                                        + p.info.packageName + " ignored: base tree "
6197                                        + tree.name + " is from package "
6198                                        + tree.sourcePackage);
6199                            }
6200                        } else {
6201                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6202                                    + p.info.packageName + " ignored: original from "
6203                                    + bp.sourcePackage);
6204                        }
6205                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6206                        if (r == null) {
6207                            r = new StringBuilder(256);
6208                        } else {
6209                            r.append(' ');
6210                        }
6211                        r.append("DUP:");
6212                        r.append(p.info.name);
6213                    }
6214                    if (bp.perm == p) {
6215                        bp.protectionLevel = p.info.protectionLevel;
6216                    }
6217                } else {
6218                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6219                            + p.info.packageName + " ignored: no group "
6220                            + p.group);
6221                }
6222            }
6223            if (r != null) {
6224                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6225            }
6226
6227            N = pkg.instrumentation.size();
6228            r = null;
6229            for (i=0; i<N; i++) {
6230                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6231                a.info.packageName = pkg.applicationInfo.packageName;
6232                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6233                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6234                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6235                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6236                a.info.dataDir = pkg.applicationInfo.dataDir;
6237
6238                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6239                // need other information about the application, like the ABI and what not ?
6240                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6241                mInstrumentation.put(a.getComponentName(), a);
6242                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6243                    if (r == null) {
6244                        r = new StringBuilder(256);
6245                    } else {
6246                        r.append(' ');
6247                    }
6248                    r.append(a.info.name);
6249                }
6250            }
6251            if (r != null) {
6252                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6253            }
6254
6255            if (pkg.protectedBroadcasts != null) {
6256                N = pkg.protectedBroadcasts.size();
6257                for (i=0; i<N; i++) {
6258                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6259                }
6260            }
6261
6262            pkgSetting.setTimeStamp(scanFileTime);
6263
6264            // Create idmap files for pairs of (packages, overlay packages).
6265            // Note: "android", ie framework-res.apk, is handled by native layers.
6266            if (pkg.mOverlayTarget != null) {
6267                // This is an overlay package.
6268                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6269                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6270                        mOverlays.put(pkg.mOverlayTarget,
6271                                new HashMap<String, PackageParser.Package>());
6272                    }
6273                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6274                    map.put(pkg.packageName, pkg);
6275                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6276                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6277                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6278                                "scanPackageLI failed to createIdmap");
6279                    }
6280                }
6281            } else if (mOverlays.containsKey(pkg.packageName) &&
6282                    !pkg.packageName.equals("android")) {
6283                // This is a regular package, with one or more known overlay packages.
6284                createIdmapsForPackageLI(pkg);
6285            }
6286        }
6287
6288        return pkg;
6289    }
6290
6291    /**
6292     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6293     * i.e, so that all packages can be run inside a single process if required.
6294     *
6295     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6296     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6297     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6298     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6299     * updating a package that belongs to a shared user.
6300     *
6301     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6302     * adds unnecessary complexity.
6303     */
6304    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6305            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6306        String requiredInstructionSet = null;
6307        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6308            requiredInstructionSet = VMRuntime.getInstructionSet(
6309                     scannedPackage.applicationInfo.primaryCpuAbi);
6310        }
6311
6312        PackageSetting requirer = null;
6313        for (PackageSetting ps : packagesForUser) {
6314            // If packagesForUser contains scannedPackage, we skip it. This will happen
6315            // when scannedPackage is an update of an existing package. Without this check,
6316            // we will never be able to change the ABI of any package belonging to a shared
6317            // user, even if it's compatible with other packages.
6318            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6319                if (ps.primaryCpuAbiString == null) {
6320                    continue;
6321                }
6322
6323                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6324                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6325                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6326                    // this but there's not much we can do.
6327                    String errorMessage = "Instruction set mismatch, "
6328                            + ((requirer == null) ? "[caller]" : requirer)
6329                            + " requires " + requiredInstructionSet + " whereas " + ps
6330                            + " requires " + instructionSet;
6331                    Slog.w(TAG, errorMessage);
6332                }
6333
6334                if (requiredInstructionSet == null) {
6335                    requiredInstructionSet = instructionSet;
6336                    requirer = ps;
6337                }
6338            }
6339        }
6340
6341        if (requiredInstructionSet != null) {
6342            String adjustedAbi;
6343            if (requirer != null) {
6344                // requirer != null implies that either scannedPackage was null or that scannedPackage
6345                // did not require an ABI, in which case we have to adjust scannedPackage to match
6346                // the ABI of the set (which is the same as requirer's ABI)
6347                adjustedAbi = requirer.primaryCpuAbiString;
6348                if (scannedPackage != null) {
6349                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6350                }
6351            } else {
6352                // requirer == null implies that we're updating all ABIs in the set to
6353                // match scannedPackage.
6354                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6355            }
6356
6357            for (PackageSetting ps : packagesForUser) {
6358                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6359                    if (ps.primaryCpuAbiString != null) {
6360                        continue;
6361                    }
6362
6363                    ps.primaryCpuAbiString = adjustedAbi;
6364                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6365                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6366                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6367
6368                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6369                                deferDexOpt, true) == DEX_OPT_FAILED) {
6370                            ps.primaryCpuAbiString = null;
6371                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6372                            return;
6373                        } else {
6374                            mInstaller.rmdex(ps.codePathString,
6375                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6376                        }
6377                    }
6378                }
6379            }
6380        }
6381    }
6382
6383    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6384        synchronized (mPackages) {
6385            mResolverReplaced = true;
6386            // Set up information for custom user intent resolution activity.
6387            mResolveActivity.applicationInfo = pkg.applicationInfo;
6388            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6389            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6390            mResolveActivity.processName = null;
6391            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6392            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6393                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6394            mResolveActivity.theme = 0;
6395            mResolveActivity.exported = true;
6396            mResolveActivity.enabled = true;
6397            mResolveInfo.activityInfo = mResolveActivity;
6398            mResolveInfo.priority = 0;
6399            mResolveInfo.preferredOrder = 0;
6400            mResolveInfo.match = 0;
6401            mResolveComponentName = mCustomResolverComponentName;
6402            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6403                    mResolveComponentName);
6404        }
6405    }
6406
6407    private static String calculateBundledApkRoot(final String codePathString) {
6408        final File codePath = new File(codePathString);
6409        final File codeRoot;
6410        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6411            codeRoot = Environment.getRootDirectory();
6412        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6413            codeRoot = Environment.getOemDirectory();
6414        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6415            codeRoot = Environment.getVendorDirectory();
6416        } else {
6417            // Unrecognized code path; take its top real segment as the apk root:
6418            // e.g. /something/app/blah.apk => /something
6419            try {
6420                File f = codePath.getCanonicalFile();
6421                File parent = f.getParentFile();    // non-null because codePath is a file
6422                File tmp;
6423                while ((tmp = parent.getParentFile()) != null) {
6424                    f = parent;
6425                    parent = tmp;
6426                }
6427                codeRoot = f;
6428                Slog.w(TAG, "Unrecognized code path "
6429                        + codePath + " - using " + codeRoot);
6430            } catch (IOException e) {
6431                // Can't canonicalize the code path -- shenanigans?
6432                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6433                return Environment.getRootDirectory().getPath();
6434            }
6435        }
6436        return codeRoot.getPath();
6437    }
6438
6439    /**
6440     * Derive and set the location of native libraries for the given package,
6441     * which varies depending on where and how the package was installed.
6442     */
6443    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6444        final ApplicationInfo info = pkg.applicationInfo;
6445        final String codePath = pkg.codePath;
6446        final File codeFile = new File(codePath);
6447        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6448        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6449
6450        info.nativeLibraryRootDir = null;
6451        info.nativeLibraryRootRequiresIsa = false;
6452        info.nativeLibraryDir = null;
6453        info.secondaryNativeLibraryDir = null;
6454
6455        if (isApkFile(codeFile)) {
6456            // Monolithic install
6457            if (bundledApp) {
6458                // If "/system/lib64/apkname" exists, assume that is the per-package
6459                // native library directory to use; otherwise use "/system/lib/apkname".
6460                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6461                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6462                        getPrimaryInstructionSet(info));
6463
6464                // This is a bundled system app so choose the path based on the ABI.
6465                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6466                // is just the default path.
6467                final String apkName = deriveCodePathName(codePath);
6468                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6469                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6470                        apkName).getAbsolutePath();
6471
6472                if (info.secondaryCpuAbi != null) {
6473                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6474                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6475                            secondaryLibDir, apkName).getAbsolutePath();
6476                }
6477            } else if (asecApp) {
6478                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6479                        .getAbsolutePath();
6480            } else {
6481                final String apkName = deriveCodePathName(codePath);
6482                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6483                        .getAbsolutePath();
6484            }
6485
6486            info.nativeLibraryRootRequiresIsa = false;
6487            info.nativeLibraryDir = info.nativeLibraryRootDir;
6488        } else {
6489            // Cluster install
6490            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6491            info.nativeLibraryRootRequiresIsa = true;
6492
6493            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6494                    getPrimaryInstructionSet(info)).getAbsolutePath();
6495
6496            if (info.secondaryCpuAbi != null) {
6497                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6498                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6499            }
6500        }
6501    }
6502
6503    /**
6504     * Calculate the abis and roots for a bundled app. These can uniquely
6505     * be determined from the contents of the system partition, i.e whether
6506     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6507     * of this information, and instead assume that the system was built
6508     * sensibly.
6509     */
6510    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6511                                           PackageSetting pkgSetting) {
6512        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6513
6514        // If "/system/lib64/apkname" exists, assume that is the per-package
6515        // native library directory to use; otherwise use "/system/lib/apkname".
6516        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6517        setBundledAppAbi(pkg, apkRoot, apkName);
6518        // pkgSetting might be null during rescan following uninstall of updates
6519        // to a bundled app, so accommodate that possibility.  The settings in
6520        // that case will be established later from the parsed package.
6521        //
6522        // If the settings aren't null, sync them up with what we've just derived.
6523        // note that apkRoot isn't stored in the package settings.
6524        if (pkgSetting != null) {
6525            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6526            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6527        }
6528    }
6529
6530    /**
6531     * Deduces the ABI of a bundled app and sets the relevant fields on the
6532     * parsed pkg object.
6533     *
6534     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6535     *        under which system libraries are installed.
6536     * @param apkName the name of the installed package.
6537     */
6538    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6539        final File codeFile = new File(pkg.codePath);
6540
6541        final boolean has64BitLibs;
6542        final boolean has32BitLibs;
6543        if (isApkFile(codeFile)) {
6544            // Monolithic install
6545            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6546            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6547        } else {
6548            // Cluster install
6549            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6550            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6551                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6552                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6553                has64BitLibs = (new File(rootDir, isa)).exists();
6554            } else {
6555                has64BitLibs = false;
6556            }
6557            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6558                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6559                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6560                has32BitLibs = (new File(rootDir, isa)).exists();
6561            } else {
6562                has32BitLibs = false;
6563            }
6564        }
6565
6566        if (has64BitLibs && !has32BitLibs) {
6567            // The package has 64 bit libs, but not 32 bit libs. Its primary
6568            // ABI should be 64 bit. We can safely assume here that the bundled
6569            // native libraries correspond to the most preferred ABI in the list.
6570
6571            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6572            pkg.applicationInfo.secondaryCpuAbi = null;
6573        } else if (has32BitLibs && !has64BitLibs) {
6574            // The package has 32 bit libs but not 64 bit libs. Its primary
6575            // ABI should be 32 bit.
6576
6577            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6578            pkg.applicationInfo.secondaryCpuAbi = null;
6579        } else if (has32BitLibs && has64BitLibs) {
6580            // The application has both 64 and 32 bit bundled libraries. We check
6581            // here that the app declares multiArch support, and warn if it doesn't.
6582            //
6583            // We will be lenient here and record both ABIs. The primary will be the
6584            // ABI that's higher on the list, i.e, a device that's configured to prefer
6585            // 64 bit apps will see a 64 bit primary ABI,
6586
6587            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6588                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6589            }
6590
6591            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6592                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6593                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6594            } else {
6595                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6596                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6597            }
6598        } else {
6599            pkg.applicationInfo.primaryCpuAbi = null;
6600            pkg.applicationInfo.secondaryCpuAbi = null;
6601        }
6602    }
6603
6604    private void killApplication(String pkgName, int appId, String reason) {
6605        // Request the ActivityManager to kill the process(only for existing packages)
6606        // so that we do not end up in a confused state while the user is still using the older
6607        // version of the application while the new one gets installed.
6608        IActivityManager am = ActivityManagerNative.getDefault();
6609        if (am != null) {
6610            try {
6611                am.killApplicationWithAppId(pkgName, appId, reason);
6612            } catch (RemoteException e) {
6613            }
6614        }
6615    }
6616
6617    void removePackageLI(PackageSetting ps, boolean chatty) {
6618        if (DEBUG_INSTALL) {
6619            if (chatty)
6620                Log.d(TAG, "Removing package " + ps.name);
6621        }
6622
6623        // writer
6624        synchronized (mPackages) {
6625            mPackages.remove(ps.name);
6626            final PackageParser.Package pkg = ps.pkg;
6627            if (pkg != null) {
6628                cleanPackageDataStructuresLILPw(pkg, chatty);
6629            }
6630        }
6631    }
6632
6633    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6634        if (DEBUG_INSTALL) {
6635            if (chatty)
6636                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6637        }
6638
6639        // writer
6640        synchronized (mPackages) {
6641            mPackages.remove(pkg.applicationInfo.packageName);
6642            cleanPackageDataStructuresLILPw(pkg, chatty);
6643        }
6644    }
6645
6646    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6647        int N = pkg.providers.size();
6648        StringBuilder r = null;
6649        int i;
6650        for (i=0; i<N; i++) {
6651            PackageParser.Provider p = pkg.providers.get(i);
6652            mProviders.removeProvider(p);
6653            if (p.info.authority == null) {
6654
6655                /* There was another ContentProvider with this authority when
6656                 * this app was installed so this authority is null,
6657                 * Ignore it as we don't have to unregister the provider.
6658                 */
6659                continue;
6660            }
6661            String names[] = p.info.authority.split(";");
6662            for (int j = 0; j < names.length; j++) {
6663                if (mProvidersByAuthority.get(names[j]) == p) {
6664                    mProvidersByAuthority.remove(names[j]);
6665                    if (DEBUG_REMOVE) {
6666                        if (chatty)
6667                            Log.d(TAG, "Unregistered content provider: " + names[j]
6668                                    + ", className = " + p.info.name + ", isSyncable = "
6669                                    + p.info.isSyncable);
6670                    }
6671                }
6672            }
6673            if (DEBUG_REMOVE && chatty) {
6674                if (r == null) {
6675                    r = new StringBuilder(256);
6676                } else {
6677                    r.append(' ');
6678                }
6679                r.append(p.info.name);
6680            }
6681        }
6682        if (r != null) {
6683            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6684        }
6685
6686        N = pkg.services.size();
6687        r = null;
6688        for (i=0; i<N; i++) {
6689            PackageParser.Service s = pkg.services.get(i);
6690            mServices.removeService(s);
6691            if (chatty) {
6692                if (r == null) {
6693                    r = new StringBuilder(256);
6694                } else {
6695                    r.append(' ');
6696                }
6697                r.append(s.info.name);
6698            }
6699        }
6700        if (r != null) {
6701            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6702        }
6703
6704        N = pkg.receivers.size();
6705        r = null;
6706        for (i=0; i<N; i++) {
6707            PackageParser.Activity a = pkg.receivers.get(i);
6708            mReceivers.removeActivity(a, "receiver");
6709            if (DEBUG_REMOVE && chatty) {
6710                if (r == null) {
6711                    r = new StringBuilder(256);
6712                } else {
6713                    r.append(' ');
6714                }
6715                r.append(a.info.name);
6716            }
6717        }
6718        if (r != null) {
6719            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6720        }
6721
6722        N = pkg.activities.size();
6723        r = null;
6724        for (i=0; i<N; i++) {
6725            PackageParser.Activity a = pkg.activities.get(i);
6726            mActivities.removeActivity(a, "activity");
6727            if (DEBUG_REMOVE && chatty) {
6728                if (r == null) {
6729                    r = new StringBuilder(256);
6730                } else {
6731                    r.append(' ');
6732                }
6733                r.append(a.info.name);
6734            }
6735        }
6736        if (r != null) {
6737            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6738        }
6739
6740        N = pkg.permissions.size();
6741        r = null;
6742        for (i=0; i<N; i++) {
6743            PackageParser.Permission p = pkg.permissions.get(i);
6744            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6745            if (bp == null) {
6746                bp = mSettings.mPermissionTrees.get(p.info.name);
6747            }
6748            if (bp != null && bp.perm == p) {
6749                bp.perm = null;
6750                if (DEBUG_REMOVE && chatty) {
6751                    if (r == null) {
6752                        r = new StringBuilder(256);
6753                    } else {
6754                        r.append(' ');
6755                    }
6756                    r.append(p.info.name);
6757                }
6758            }
6759            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6760                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6761                if (appOpPerms != null) {
6762                    appOpPerms.remove(pkg.packageName);
6763                }
6764            }
6765        }
6766        if (r != null) {
6767            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6768        }
6769
6770        N = pkg.requestedPermissions.size();
6771        r = null;
6772        for (i=0; i<N; i++) {
6773            String perm = pkg.requestedPermissions.get(i);
6774            BasePermission bp = mSettings.mPermissions.get(perm);
6775            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6776                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6777                if (appOpPerms != null) {
6778                    appOpPerms.remove(pkg.packageName);
6779                    if (appOpPerms.isEmpty()) {
6780                        mAppOpPermissionPackages.remove(perm);
6781                    }
6782                }
6783            }
6784        }
6785        if (r != null) {
6786            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6787        }
6788
6789        N = pkg.instrumentation.size();
6790        r = null;
6791        for (i=0; i<N; i++) {
6792            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6793            mInstrumentation.remove(a.getComponentName());
6794            if (DEBUG_REMOVE && chatty) {
6795                if (r == null) {
6796                    r = new StringBuilder(256);
6797                } else {
6798                    r.append(' ');
6799                }
6800                r.append(a.info.name);
6801            }
6802        }
6803        if (r != null) {
6804            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6805        }
6806
6807        r = null;
6808        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6809            // Only system apps can hold shared libraries.
6810            if (pkg.libraryNames != null) {
6811                for (i=0; i<pkg.libraryNames.size(); i++) {
6812                    String name = pkg.libraryNames.get(i);
6813                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6814                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6815                        mSharedLibraries.remove(name);
6816                        if (DEBUG_REMOVE && chatty) {
6817                            if (r == null) {
6818                                r = new StringBuilder(256);
6819                            } else {
6820                                r.append(' ');
6821                            }
6822                            r.append(name);
6823                        }
6824                    }
6825                }
6826            }
6827        }
6828        if (r != null) {
6829            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6830        }
6831    }
6832
6833    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6834        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6835            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6836                return true;
6837            }
6838        }
6839        return false;
6840    }
6841
6842    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6843    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6844    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6845
6846    private void updatePermissionsLPw(String changingPkg,
6847            PackageParser.Package pkgInfo, int flags) {
6848        // Make sure there are no dangling permission trees.
6849        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6850        while (it.hasNext()) {
6851            final BasePermission bp = it.next();
6852            if (bp.packageSetting == null) {
6853                // We may not yet have parsed the package, so just see if
6854                // we still know about its settings.
6855                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6856            }
6857            if (bp.packageSetting == null) {
6858                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6859                        + " from package " + bp.sourcePackage);
6860                it.remove();
6861            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6862                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6863                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6864                            + " from package " + bp.sourcePackage);
6865                    flags |= UPDATE_PERMISSIONS_ALL;
6866                    it.remove();
6867                }
6868            }
6869        }
6870
6871        // Make sure all dynamic permissions have been assigned to a package,
6872        // and make sure there are no dangling permissions.
6873        it = mSettings.mPermissions.values().iterator();
6874        while (it.hasNext()) {
6875            final BasePermission bp = it.next();
6876            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6877                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6878                        + bp.name + " pkg=" + bp.sourcePackage
6879                        + " info=" + bp.pendingInfo);
6880                if (bp.packageSetting == null && bp.pendingInfo != null) {
6881                    final BasePermission tree = findPermissionTreeLP(bp.name);
6882                    if (tree != null && tree.perm != null) {
6883                        bp.packageSetting = tree.packageSetting;
6884                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6885                                new PermissionInfo(bp.pendingInfo));
6886                        bp.perm.info.packageName = tree.perm.info.packageName;
6887                        bp.perm.info.name = bp.name;
6888                        bp.uid = tree.uid;
6889                    }
6890                }
6891            }
6892            if (bp.packageSetting == null) {
6893                // We may not yet have parsed the package, so just see if
6894                // we still know about its settings.
6895                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6896            }
6897            if (bp.packageSetting == null) {
6898                Slog.w(TAG, "Removing dangling permission: " + bp.name
6899                        + " from package " + bp.sourcePackage);
6900                it.remove();
6901            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6902                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6903                    Slog.i(TAG, "Removing old permission: " + bp.name
6904                            + " from package " + bp.sourcePackage);
6905                    flags |= UPDATE_PERMISSIONS_ALL;
6906                    it.remove();
6907                }
6908            }
6909        }
6910
6911        // Now update the permissions for all packages, in particular
6912        // replace the granted permissions of the system packages.
6913        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6914            for (PackageParser.Package pkg : mPackages.values()) {
6915                if (pkg != pkgInfo) {
6916                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6917                            changingPkg);
6918                }
6919            }
6920        }
6921
6922        if (pkgInfo != null) {
6923            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6924        }
6925    }
6926
6927    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6928            String packageOfInterest) {
6929        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6930        if (ps == null) {
6931            return;
6932        }
6933        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6934        HashSet<String> origPermissions = gp.grantedPermissions;
6935        boolean changedPermission = false;
6936
6937        if (replace) {
6938            ps.permissionsFixed = false;
6939            if (gp == ps) {
6940                origPermissions = new HashSet<String>(gp.grantedPermissions);
6941                gp.grantedPermissions.clear();
6942                gp.gids = mGlobalGids;
6943            }
6944        }
6945
6946        if (gp.gids == null) {
6947            gp.gids = mGlobalGids;
6948        }
6949
6950        final int N = pkg.requestedPermissions.size();
6951        for (int i=0; i<N; i++) {
6952            final String name = pkg.requestedPermissions.get(i);
6953            final boolean required = pkg.requestedPermissionsRequired.get(i);
6954            final BasePermission bp = mSettings.mPermissions.get(name);
6955            if (DEBUG_INSTALL) {
6956                if (gp != ps) {
6957                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6958                }
6959            }
6960
6961            if (bp == null || bp.packageSetting == null) {
6962                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6963                    Slog.w(TAG, "Unknown permission " + name
6964                            + " in package " + pkg.packageName);
6965                }
6966                continue;
6967            }
6968
6969            final String perm = bp.name;
6970            boolean allowed;
6971            boolean allowedSig = false;
6972            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6973                // Keep track of app op permissions.
6974                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6975                if (pkgs == null) {
6976                    pkgs = new ArraySet<>();
6977                    mAppOpPermissionPackages.put(bp.name, pkgs);
6978                }
6979                pkgs.add(pkg.packageName);
6980            }
6981            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6982            if (level == PermissionInfo.PROTECTION_NORMAL
6983                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6984                // We grant a normal or dangerous permission if any of the following
6985                // are true:
6986                // 1) The permission is required
6987                // 2) The permission is optional, but was granted in the past
6988                // 3) The permission is optional, but was requested by an
6989                //    app in /system (not /data)
6990                //
6991                // Otherwise, reject the permission.
6992                allowed = (required || origPermissions.contains(perm)
6993                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6994            } else if (bp.packageSetting == null) {
6995                // This permission is invalid; skip it.
6996                allowed = false;
6997            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6998                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6999                if (allowed) {
7000                    allowedSig = true;
7001                }
7002            } else {
7003                allowed = false;
7004            }
7005            if (DEBUG_INSTALL) {
7006                if (gp != ps) {
7007                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7008                }
7009            }
7010            if (allowed) {
7011                if (!isSystemApp(ps) && ps.permissionsFixed) {
7012                    // If this is an existing, non-system package, then
7013                    // we can't add any new permissions to it.
7014                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7015                        // Except...  if this is a permission that was added
7016                        // to the platform (note: need to only do this when
7017                        // updating the platform).
7018                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7019                    }
7020                }
7021                if (allowed) {
7022                    if (!gp.grantedPermissions.contains(perm)) {
7023                        changedPermission = true;
7024                        gp.grantedPermissions.add(perm);
7025                        gp.gids = appendInts(gp.gids, bp.gids);
7026                    } else if (!ps.haveGids) {
7027                        gp.gids = appendInts(gp.gids, bp.gids);
7028                    }
7029                } else {
7030                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7031                        Slog.w(TAG, "Not granting permission " + perm
7032                                + " to package " + pkg.packageName
7033                                + " because it was previously installed without");
7034                    }
7035                }
7036            } else {
7037                if (gp.grantedPermissions.remove(perm)) {
7038                    changedPermission = true;
7039                    gp.gids = removeInts(gp.gids, bp.gids);
7040                    Slog.i(TAG, "Un-granting permission " + perm
7041                            + " from package " + pkg.packageName
7042                            + " (protectionLevel=" + bp.protectionLevel
7043                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7044                            + ")");
7045                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7046                    // Don't print warning for app op permissions, since it is fine for them
7047                    // not to be granted, there is a UI for the user to decide.
7048                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7049                        Slog.w(TAG, "Not granting permission " + perm
7050                                + " to package " + pkg.packageName
7051                                + " (protectionLevel=" + bp.protectionLevel
7052                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7053                                + ")");
7054                    }
7055                }
7056            }
7057        }
7058
7059        if ((changedPermission || replace) && !ps.permissionsFixed &&
7060                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7061            // This is the first that we have heard about this package, so the
7062            // permissions we have now selected are fixed until explicitly
7063            // changed.
7064            ps.permissionsFixed = true;
7065        }
7066        ps.haveGids = true;
7067    }
7068
7069    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7070        boolean allowed = false;
7071        final int NP = PackageParser.NEW_PERMISSIONS.length;
7072        for (int ip=0; ip<NP; ip++) {
7073            final PackageParser.NewPermissionInfo npi
7074                    = PackageParser.NEW_PERMISSIONS[ip];
7075            if (npi.name.equals(perm)
7076                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7077                allowed = true;
7078                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7079                        + pkg.packageName);
7080                break;
7081            }
7082        }
7083        return allowed;
7084    }
7085
7086    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7087                                          BasePermission bp, HashSet<String> origPermissions) {
7088        boolean allowed;
7089        allowed = (compareSignatures(
7090                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7091                        == PackageManager.SIGNATURE_MATCH)
7092                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7093                        == PackageManager.SIGNATURE_MATCH);
7094        if (!allowed && (bp.protectionLevel
7095                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7096            if (isSystemApp(pkg)) {
7097                // For updated system applications, a system permission
7098                // is granted only if it had been defined by the original application.
7099                if (isUpdatedSystemApp(pkg)) {
7100                    final PackageSetting sysPs = mSettings
7101                            .getDisabledSystemPkgLPr(pkg.packageName);
7102                    final GrantedPermissions origGp = sysPs.sharedUser != null
7103                            ? sysPs.sharedUser : sysPs;
7104
7105                    if (origGp.grantedPermissions.contains(perm)) {
7106                        // If the original was granted this permission, we take
7107                        // that grant decision as read and propagate it to the
7108                        // update.
7109                        allowed = true;
7110                    } else {
7111                        // The system apk may have been updated with an older
7112                        // version of the one on the data partition, but which
7113                        // granted a new system permission that it didn't have
7114                        // before.  In this case we do want to allow the app to
7115                        // now get the new permission if the ancestral apk is
7116                        // privileged to get it.
7117                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7118                            for (int j=0;
7119                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7120                                if (perm.equals(
7121                                        sysPs.pkg.requestedPermissions.get(j))) {
7122                                    allowed = true;
7123                                    break;
7124                                }
7125                            }
7126                        }
7127                    }
7128                } else {
7129                    allowed = isPrivilegedApp(pkg);
7130                }
7131            }
7132        }
7133        if (!allowed && (bp.protectionLevel
7134                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7135            // For development permissions, a development permission
7136            // is granted only if it was already granted.
7137            allowed = origPermissions.contains(perm);
7138        }
7139        return allowed;
7140    }
7141
7142    final class ActivityIntentResolver
7143            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7144        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7145                boolean defaultOnly, int userId) {
7146            if (!sUserManager.exists(userId)) return null;
7147            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7148            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7149        }
7150
7151        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7152                int userId) {
7153            if (!sUserManager.exists(userId)) return null;
7154            mFlags = flags;
7155            return super.queryIntent(intent, resolvedType,
7156                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7157        }
7158
7159        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7160                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7161            if (!sUserManager.exists(userId)) return null;
7162            if (packageActivities == null) {
7163                return null;
7164            }
7165            mFlags = flags;
7166            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7167            final int N = packageActivities.size();
7168            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7169                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7170
7171            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7172            for (int i = 0; i < N; ++i) {
7173                intentFilters = packageActivities.get(i).intents;
7174                if (intentFilters != null && intentFilters.size() > 0) {
7175                    PackageParser.ActivityIntentInfo[] array =
7176                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7177                    intentFilters.toArray(array);
7178                    listCut.add(array);
7179                }
7180            }
7181            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7182        }
7183
7184        public final void addActivity(PackageParser.Activity a, String type) {
7185            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7186            mActivities.put(a.getComponentName(), a);
7187            if (DEBUG_SHOW_INFO)
7188                Log.v(
7189                TAG, "  " + type + " " +
7190                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7191            if (DEBUG_SHOW_INFO)
7192                Log.v(TAG, "    Class=" + a.info.name);
7193            final int NI = a.intents.size();
7194            for (int j=0; j<NI; j++) {
7195                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7196                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7197                    intent.setPriority(0);
7198                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7199                            + a.className + " with priority > 0, forcing to 0");
7200                }
7201                if (DEBUG_SHOW_INFO) {
7202                    Log.v(TAG, "    IntentFilter:");
7203                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7204                }
7205                if (!intent.debugCheck()) {
7206                    Log.w(TAG, "==> For Activity " + a.info.name);
7207                }
7208                addFilter(intent);
7209            }
7210        }
7211
7212        public final void removeActivity(PackageParser.Activity a, String type) {
7213            mActivities.remove(a.getComponentName());
7214            if (DEBUG_SHOW_INFO) {
7215                Log.v(TAG, "  " + type + " "
7216                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7217                                : a.info.name) + ":");
7218                Log.v(TAG, "    Class=" + a.info.name);
7219            }
7220            final int NI = a.intents.size();
7221            for (int j=0; j<NI; j++) {
7222                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7223                if (DEBUG_SHOW_INFO) {
7224                    Log.v(TAG, "    IntentFilter:");
7225                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7226                }
7227                removeFilter(intent);
7228            }
7229        }
7230
7231        @Override
7232        protected boolean allowFilterResult(
7233                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7234            ActivityInfo filterAi = filter.activity.info;
7235            for (int i=dest.size()-1; i>=0; i--) {
7236                ActivityInfo destAi = dest.get(i).activityInfo;
7237                if (destAi.name == filterAi.name
7238                        && destAi.packageName == filterAi.packageName) {
7239                    return false;
7240                }
7241            }
7242            return true;
7243        }
7244
7245        @Override
7246        protected ActivityIntentInfo[] newArray(int size) {
7247            return new ActivityIntentInfo[size];
7248        }
7249
7250        @Override
7251        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7252            if (!sUserManager.exists(userId)) return true;
7253            PackageParser.Package p = filter.activity.owner;
7254            if (p != null) {
7255                PackageSetting ps = (PackageSetting)p.mExtras;
7256                if (ps != null) {
7257                    // System apps are never considered stopped for purposes of
7258                    // filtering, because there may be no way for the user to
7259                    // actually re-launch them.
7260                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7261                            && ps.getStopped(userId);
7262                }
7263            }
7264            return false;
7265        }
7266
7267        @Override
7268        protected boolean isPackageForFilter(String packageName,
7269                PackageParser.ActivityIntentInfo info) {
7270            return packageName.equals(info.activity.owner.packageName);
7271        }
7272
7273        @Override
7274        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7275                int match, int userId) {
7276            if (!sUserManager.exists(userId)) return null;
7277            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7278                return null;
7279            }
7280            final PackageParser.Activity activity = info.activity;
7281            if (mSafeMode && (activity.info.applicationInfo.flags
7282                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7283                return null;
7284            }
7285            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7286            if (ps == null) {
7287                return null;
7288            }
7289            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7290                    ps.readUserState(userId), userId);
7291            if (ai == null) {
7292                return null;
7293            }
7294            final ResolveInfo res = new ResolveInfo();
7295            res.activityInfo = ai;
7296            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7297                res.filter = info;
7298            }
7299            res.priority = info.getPriority();
7300            res.preferredOrder = activity.owner.mPreferredOrder;
7301            //System.out.println("Result: " + res.activityInfo.className +
7302            //                   " = " + res.priority);
7303            res.match = match;
7304            res.isDefault = info.hasDefault;
7305            res.labelRes = info.labelRes;
7306            res.nonLocalizedLabel = info.nonLocalizedLabel;
7307            if (userNeedsBadging(userId)) {
7308                res.noResourceId = true;
7309            } else {
7310                res.icon = info.icon;
7311            }
7312            res.system = isSystemApp(res.activityInfo.applicationInfo);
7313            return res;
7314        }
7315
7316        @Override
7317        protected void sortResults(List<ResolveInfo> results) {
7318            Collections.sort(results, mResolvePrioritySorter);
7319        }
7320
7321        @Override
7322        protected void dumpFilter(PrintWriter out, String prefix,
7323                PackageParser.ActivityIntentInfo filter) {
7324            out.print(prefix); out.print(
7325                    Integer.toHexString(System.identityHashCode(filter.activity)));
7326                    out.print(' ');
7327                    filter.activity.printComponentShortName(out);
7328                    out.print(" filter ");
7329                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7330        }
7331
7332//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7333//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7334//            final List<ResolveInfo> retList = Lists.newArrayList();
7335//            while (i.hasNext()) {
7336//                final ResolveInfo resolveInfo = i.next();
7337//                if (isEnabledLP(resolveInfo.activityInfo)) {
7338//                    retList.add(resolveInfo);
7339//                }
7340//            }
7341//            return retList;
7342//        }
7343
7344        // Keys are String (activity class name), values are Activity.
7345        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7346                = new HashMap<ComponentName, PackageParser.Activity>();
7347        private int mFlags;
7348    }
7349
7350    private final class ServiceIntentResolver
7351            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7352        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7353                boolean defaultOnly, int userId) {
7354            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7355            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7356        }
7357
7358        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7359                int userId) {
7360            if (!sUserManager.exists(userId)) return null;
7361            mFlags = flags;
7362            return super.queryIntent(intent, resolvedType,
7363                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7364        }
7365
7366        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7367                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7368            if (!sUserManager.exists(userId)) return null;
7369            if (packageServices == null) {
7370                return null;
7371            }
7372            mFlags = flags;
7373            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7374            final int N = packageServices.size();
7375            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7376                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7377
7378            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7379            for (int i = 0; i < N; ++i) {
7380                intentFilters = packageServices.get(i).intents;
7381                if (intentFilters != null && intentFilters.size() > 0) {
7382                    PackageParser.ServiceIntentInfo[] array =
7383                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7384                    intentFilters.toArray(array);
7385                    listCut.add(array);
7386                }
7387            }
7388            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7389        }
7390
7391        public final void addService(PackageParser.Service s) {
7392            mServices.put(s.getComponentName(), s);
7393            if (DEBUG_SHOW_INFO) {
7394                Log.v(TAG, "  "
7395                        + (s.info.nonLocalizedLabel != null
7396                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7397                Log.v(TAG, "    Class=" + s.info.name);
7398            }
7399            final int NI = s.intents.size();
7400            int j;
7401            for (j=0; j<NI; j++) {
7402                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7403                if (DEBUG_SHOW_INFO) {
7404                    Log.v(TAG, "    IntentFilter:");
7405                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7406                }
7407                if (!intent.debugCheck()) {
7408                    Log.w(TAG, "==> For Service " + s.info.name);
7409                }
7410                addFilter(intent);
7411            }
7412        }
7413
7414        public final void removeService(PackageParser.Service s) {
7415            mServices.remove(s.getComponentName());
7416            if (DEBUG_SHOW_INFO) {
7417                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7418                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7419                Log.v(TAG, "    Class=" + s.info.name);
7420            }
7421            final int NI = s.intents.size();
7422            int j;
7423            for (j=0; j<NI; j++) {
7424                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7425                if (DEBUG_SHOW_INFO) {
7426                    Log.v(TAG, "    IntentFilter:");
7427                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7428                }
7429                removeFilter(intent);
7430            }
7431        }
7432
7433        @Override
7434        protected boolean allowFilterResult(
7435                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7436            ServiceInfo filterSi = filter.service.info;
7437            for (int i=dest.size()-1; i>=0; i--) {
7438                ServiceInfo destAi = dest.get(i).serviceInfo;
7439                if (destAi.name == filterSi.name
7440                        && destAi.packageName == filterSi.packageName) {
7441                    return false;
7442                }
7443            }
7444            return true;
7445        }
7446
7447        @Override
7448        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7449            return new PackageParser.ServiceIntentInfo[size];
7450        }
7451
7452        @Override
7453        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7454            if (!sUserManager.exists(userId)) return true;
7455            PackageParser.Package p = filter.service.owner;
7456            if (p != null) {
7457                PackageSetting ps = (PackageSetting)p.mExtras;
7458                if (ps != null) {
7459                    // System apps are never considered stopped for purposes of
7460                    // filtering, because there may be no way for the user to
7461                    // actually re-launch them.
7462                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7463                            && ps.getStopped(userId);
7464                }
7465            }
7466            return false;
7467        }
7468
7469        @Override
7470        protected boolean isPackageForFilter(String packageName,
7471                PackageParser.ServiceIntentInfo info) {
7472            return packageName.equals(info.service.owner.packageName);
7473        }
7474
7475        @Override
7476        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7477                int match, int userId) {
7478            if (!sUserManager.exists(userId)) return null;
7479            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7480            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7481                return null;
7482            }
7483            final PackageParser.Service service = info.service;
7484            if (mSafeMode && (service.info.applicationInfo.flags
7485                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7486                return null;
7487            }
7488            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7489            if (ps == null) {
7490                return null;
7491            }
7492            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7493                    ps.readUserState(userId), userId);
7494            if (si == null) {
7495                return null;
7496            }
7497            final ResolveInfo res = new ResolveInfo();
7498            res.serviceInfo = si;
7499            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7500                res.filter = filter;
7501            }
7502            res.priority = info.getPriority();
7503            res.preferredOrder = service.owner.mPreferredOrder;
7504            //System.out.println("Result: " + res.activityInfo.className +
7505            //                   " = " + res.priority);
7506            res.match = match;
7507            res.isDefault = info.hasDefault;
7508            res.labelRes = info.labelRes;
7509            res.nonLocalizedLabel = info.nonLocalizedLabel;
7510            res.icon = info.icon;
7511            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7512            return res;
7513        }
7514
7515        @Override
7516        protected void sortResults(List<ResolveInfo> results) {
7517            Collections.sort(results, mResolvePrioritySorter);
7518        }
7519
7520        @Override
7521        protected void dumpFilter(PrintWriter out, String prefix,
7522                PackageParser.ServiceIntentInfo filter) {
7523            out.print(prefix); out.print(
7524                    Integer.toHexString(System.identityHashCode(filter.service)));
7525                    out.print(' ');
7526                    filter.service.printComponentShortName(out);
7527                    out.print(" filter ");
7528                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7529        }
7530
7531//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7532//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7533//            final List<ResolveInfo> retList = Lists.newArrayList();
7534//            while (i.hasNext()) {
7535//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7536//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7537//                    retList.add(resolveInfo);
7538//                }
7539//            }
7540//            return retList;
7541//        }
7542
7543        // Keys are String (activity class name), values are Activity.
7544        private final HashMap<ComponentName, PackageParser.Service> mServices
7545                = new HashMap<ComponentName, PackageParser.Service>();
7546        private int mFlags;
7547    };
7548
7549    private final class ProviderIntentResolver
7550            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7551        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7552                boolean defaultOnly, int userId) {
7553            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7554            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7555        }
7556
7557        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7558                int userId) {
7559            if (!sUserManager.exists(userId))
7560                return null;
7561            mFlags = flags;
7562            return super.queryIntent(intent, resolvedType,
7563                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7564        }
7565
7566        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7567                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7568            if (!sUserManager.exists(userId))
7569                return null;
7570            if (packageProviders == null) {
7571                return null;
7572            }
7573            mFlags = flags;
7574            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7575            final int N = packageProviders.size();
7576            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7577                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7578
7579            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7580            for (int i = 0; i < N; ++i) {
7581                intentFilters = packageProviders.get(i).intents;
7582                if (intentFilters != null && intentFilters.size() > 0) {
7583                    PackageParser.ProviderIntentInfo[] array =
7584                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7585                    intentFilters.toArray(array);
7586                    listCut.add(array);
7587                }
7588            }
7589            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7590        }
7591
7592        public final void addProvider(PackageParser.Provider p) {
7593            if (mProviders.containsKey(p.getComponentName())) {
7594                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7595                return;
7596            }
7597
7598            mProviders.put(p.getComponentName(), p);
7599            if (DEBUG_SHOW_INFO) {
7600                Log.v(TAG, "  "
7601                        + (p.info.nonLocalizedLabel != null
7602                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7603                Log.v(TAG, "    Class=" + p.info.name);
7604            }
7605            final int NI = p.intents.size();
7606            int j;
7607            for (j = 0; j < NI; j++) {
7608                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7609                if (DEBUG_SHOW_INFO) {
7610                    Log.v(TAG, "    IntentFilter:");
7611                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7612                }
7613                if (!intent.debugCheck()) {
7614                    Log.w(TAG, "==> For Provider " + p.info.name);
7615                }
7616                addFilter(intent);
7617            }
7618        }
7619
7620        public final void removeProvider(PackageParser.Provider p) {
7621            mProviders.remove(p.getComponentName());
7622            if (DEBUG_SHOW_INFO) {
7623                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7624                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7625                Log.v(TAG, "    Class=" + p.info.name);
7626            }
7627            final int NI = p.intents.size();
7628            int j;
7629            for (j = 0; j < NI; j++) {
7630                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7631                if (DEBUG_SHOW_INFO) {
7632                    Log.v(TAG, "    IntentFilter:");
7633                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7634                }
7635                removeFilter(intent);
7636            }
7637        }
7638
7639        @Override
7640        protected boolean allowFilterResult(
7641                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7642            ProviderInfo filterPi = filter.provider.info;
7643            for (int i = dest.size() - 1; i >= 0; i--) {
7644                ProviderInfo destPi = dest.get(i).providerInfo;
7645                if (destPi.name == filterPi.name
7646                        && destPi.packageName == filterPi.packageName) {
7647                    return false;
7648                }
7649            }
7650            return true;
7651        }
7652
7653        @Override
7654        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7655            return new PackageParser.ProviderIntentInfo[size];
7656        }
7657
7658        @Override
7659        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7660            if (!sUserManager.exists(userId))
7661                return true;
7662            PackageParser.Package p = filter.provider.owner;
7663            if (p != null) {
7664                PackageSetting ps = (PackageSetting) p.mExtras;
7665                if (ps != null) {
7666                    // System apps are never considered stopped for purposes of
7667                    // filtering, because there may be no way for the user to
7668                    // actually re-launch them.
7669                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7670                            && ps.getStopped(userId);
7671                }
7672            }
7673            return false;
7674        }
7675
7676        @Override
7677        protected boolean isPackageForFilter(String packageName,
7678                PackageParser.ProviderIntentInfo info) {
7679            return packageName.equals(info.provider.owner.packageName);
7680        }
7681
7682        @Override
7683        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7684                int match, int userId) {
7685            if (!sUserManager.exists(userId))
7686                return null;
7687            final PackageParser.ProviderIntentInfo info = filter;
7688            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7689                return null;
7690            }
7691            final PackageParser.Provider provider = info.provider;
7692            if (mSafeMode && (provider.info.applicationInfo.flags
7693                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7694                return null;
7695            }
7696            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7697            if (ps == null) {
7698                return null;
7699            }
7700            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7701                    ps.readUserState(userId), userId);
7702            if (pi == null) {
7703                return null;
7704            }
7705            final ResolveInfo res = new ResolveInfo();
7706            res.providerInfo = pi;
7707            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7708                res.filter = filter;
7709            }
7710            res.priority = info.getPriority();
7711            res.preferredOrder = provider.owner.mPreferredOrder;
7712            res.match = match;
7713            res.isDefault = info.hasDefault;
7714            res.labelRes = info.labelRes;
7715            res.nonLocalizedLabel = info.nonLocalizedLabel;
7716            res.icon = info.icon;
7717            res.system = isSystemApp(res.providerInfo.applicationInfo);
7718            return res;
7719        }
7720
7721        @Override
7722        protected void sortResults(List<ResolveInfo> results) {
7723            Collections.sort(results, mResolvePrioritySorter);
7724        }
7725
7726        @Override
7727        protected void dumpFilter(PrintWriter out, String prefix,
7728                PackageParser.ProviderIntentInfo filter) {
7729            out.print(prefix);
7730            out.print(
7731                    Integer.toHexString(System.identityHashCode(filter.provider)));
7732            out.print(' ');
7733            filter.provider.printComponentShortName(out);
7734            out.print(" filter ");
7735            out.println(Integer.toHexString(System.identityHashCode(filter)));
7736        }
7737
7738        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7739                = new HashMap<ComponentName, PackageParser.Provider>();
7740        private int mFlags;
7741    };
7742
7743    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7744            new Comparator<ResolveInfo>() {
7745        public int compare(ResolveInfo r1, ResolveInfo r2) {
7746            int v1 = r1.priority;
7747            int v2 = r2.priority;
7748            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7749            if (v1 != v2) {
7750                return (v1 > v2) ? -1 : 1;
7751            }
7752            v1 = r1.preferredOrder;
7753            v2 = r2.preferredOrder;
7754            if (v1 != v2) {
7755                return (v1 > v2) ? -1 : 1;
7756            }
7757            if (r1.isDefault != r2.isDefault) {
7758                return r1.isDefault ? -1 : 1;
7759            }
7760            v1 = r1.match;
7761            v2 = r2.match;
7762            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7763            if (v1 != v2) {
7764                return (v1 > v2) ? -1 : 1;
7765            }
7766            if (r1.system != r2.system) {
7767                return r1.system ? -1 : 1;
7768            }
7769            return 0;
7770        }
7771    };
7772
7773    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7774            new Comparator<ProviderInfo>() {
7775        public int compare(ProviderInfo p1, ProviderInfo p2) {
7776            final int v1 = p1.initOrder;
7777            final int v2 = p2.initOrder;
7778            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7779        }
7780    };
7781
7782    static final void sendPackageBroadcast(String action, String pkg,
7783            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7784            int[] userIds) {
7785        IActivityManager am = ActivityManagerNative.getDefault();
7786        if (am != null) {
7787            try {
7788                if (userIds == null) {
7789                    userIds = am.getRunningUserIds();
7790                }
7791                for (int id : userIds) {
7792                    final Intent intent = new Intent(action,
7793                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7794                    if (extras != null) {
7795                        intent.putExtras(extras);
7796                    }
7797                    if (targetPkg != null) {
7798                        intent.setPackage(targetPkg);
7799                    }
7800                    // Modify the UID when posting to other users
7801                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7802                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7803                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7804                        intent.putExtra(Intent.EXTRA_UID, uid);
7805                    }
7806                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7807                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7808                    if (DEBUG_BROADCASTS) {
7809                        RuntimeException here = new RuntimeException("here");
7810                        here.fillInStackTrace();
7811                        Slog.d(TAG, "Sending to user " + id + ": "
7812                                + intent.toShortString(false, true, false, false)
7813                                + " " + intent.getExtras(), here);
7814                    }
7815                    am.broadcastIntent(null, intent, null, finishedReceiver,
7816                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7817                            finishedReceiver != null, false, id);
7818                }
7819            } catch (RemoteException ex) {
7820            }
7821        }
7822    }
7823
7824    /**
7825     * Check if the external storage media is available. This is true if there
7826     * is a mounted external storage medium or if the external storage is
7827     * emulated.
7828     */
7829    private boolean isExternalMediaAvailable() {
7830        return mMediaMounted || Environment.isExternalStorageEmulated();
7831    }
7832
7833    @Override
7834    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7835        // writer
7836        synchronized (mPackages) {
7837            if (!isExternalMediaAvailable()) {
7838                // If the external storage is no longer mounted at this point,
7839                // the caller may not have been able to delete all of this
7840                // packages files and can not delete any more.  Bail.
7841                return null;
7842            }
7843            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7844            if (lastPackage != null) {
7845                pkgs.remove(lastPackage);
7846            }
7847            if (pkgs.size() > 0) {
7848                return pkgs.get(0);
7849            }
7850        }
7851        return null;
7852    }
7853
7854    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7855        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7856                userId, andCode ? 1 : 0, packageName);
7857        if (mSystemReady) {
7858            msg.sendToTarget();
7859        } else {
7860            if (mPostSystemReadyMessages == null) {
7861                mPostSystemReadyMessages = new ArrayList<>();
7862            }
7863            mPostSystemReadyMessages.add(msg);
7864        }
7865    }
7866
7867    void startCleaningPackages() {
7868        // reader
7869        synchronized (mPackages) {
7870            if (!isExternalMediaAvailable()) {
7871                return;
7872            }
7873            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7874                return;
7875            }
7876        }
7877        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7878        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7879        IActivityManager am = ActivityManagerNative.getDefault();
7880        if (am != null) {
7881            try {
7882                am.startService(null, intent, null, UserHandle.USER_OWNER);
7883            } catch (RemoteException e) {
7884            }
7885        }
7886    }
7887
7888    @Override
7889    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7890            int installFlags, String installerPackageName, VerificationParams verificationParams,
7891            String packageAbiOverride) {
7892        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7893                packageAbiOverride, UserHandle.getCallingUserId());
7894    }
7895
7896    @Override
7897    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7898            int installFlags, String installerPackageName, VerificationParams verificationParams,
7899            String packageAbiOverride, int userId) {
7900        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7901
7902        final int callingUid = Binder.getCallingUid();
7903        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7904
7905        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7906            try {
7907                if (observer != null) {
7908                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7909                }
7910            } catch (RemoteException re) {
7911            }
7912            return;
7913        }
7914
7915        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7916            installFlags |= PackageManager.INSTALL_FROM_ADB;
7917
7918        } else {
7919            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7920            // about installerPackageName.
7921
7922            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7923            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7924        }
7925
7926        UserHandle user;
7927        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7928            user = UserHandle.ALL;
7929        } else {
7930            user = new UserHandle(userId);
7931        }
7932
7933        verificationParams.setInstallerUid(callingUid);
7934
7935        final File originFile = new File(originPath);
7936        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7937
7938        final Message msg = mHandler.obtainMessage(INIT_COPY);
7939        msg.obj = new InstallParams(origin, observer, installFlags,
7940                installerPackageName, verificationParams, user, packageAbiOverride);
7941        mHandler.sendMessage(msg);
7942    }
7943
7944    void installStage(String packageName, File stagedDir, String stagedCid,
7945            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7946            String installerPackageName, int installerUid, UserHandle user) {
7947        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7948                params.referrerUri, installerUid, null);
7949
7950        final OriginInfo origin;
7951        if (stagedDir != null) {
7952            origin = OriginInfo.fromStagedFile(stagedDir);
7953        } else {
7954            origin = OriginInfo.fromStagedContainer(stagedCid);
7955        }
7956
7957        final Message msg = mHandler.obtainMessage(INIT_COPY);
7958        msg.obj = new InstallParams(origin, observer, params.installFlags,
7959                installerPackageName, verifParams, user, params.abiOverride);
7960        mHandler.sendMessage(msg);
7961    }
7962
7963    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7964        Bundle extras = new Bundle(1);
7965        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7966
7967        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7968                packageName, extras, null, null, new int[] {userId});
7969        try {
7970            IActivityManager am = ActivityManagerNative.getDefault();
7971            final boolean isSystem =
7972                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7973            if (isSystem && am.isUserRunning(userId, false)) {
7974                // The just-installed/enabled app is bundled on the system, so presumed
7975                // to be able to run automatically without needing an explicit launch.
7976                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7977                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7978                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7979                        .setPackage(packageName);
7980                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7981                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7982            }
7983        } catch (RemoteException e) {
7984            // shouldn't happen
7985            Slog.w(TAG, "Unable to bootstrap installed package", e);
7986        }
7987    }
7988
7989    @Override
7990    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7991            int userId) {
7992        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7993        PackageSetting pkgSetting;
7994        final int uid = Binder.getCallingUid();
7995        enforceCrossUserPermission(uid, userId, true, true,
7996                "setApplicationHiddenSetting for user " + userId);
7997
7998        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7999            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8000            return false;
8001        }
8002
8003        long callingId = Binder.clearCallingIdentity();
8004        try {
8005            boolean sendAdded = false;
8006            boolean sendRemoved = false;
8007            // writer
8008            synchronized (mPackages) {
8009                pkgSetting = mSettings.mPackages.get(packageName);
8010                if (pkgSetting == null) {
8011                    return false;
8012                }
8013                if (pkgSetting.getHidden(userId) != hidden) {
8014                    pkgSetting.setHidden(hidden, userId);
8015                    mSettings.writePackageRestrictionsLPr(userId);
8016                    if (hidden) {
8017                        sendRemoved = true;
8018                    } else {
8019                        sendAdded = true;
8020                    }
8021                }
8022            }
8023            if (sendAdded) {
8024                sendPackageAddedForUser(packageName, pkgSetting, userId);
8025                return true;
8026            }
8027            if (sendRemoved) {
8028                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8029                        "hiding pkg");
8030                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8031            }
8032        } finally {
8033            Binder.restoreCallingIdentity(callingId);
8034        }
8035        return false;
8036    }
8037
8038    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8039            int userId) {
8040        final PackageRemovedInfo info = new PackageRemovedInfo();
8041        info.removedPackage = packageName;
8042        info.removedUsers = new int[] {userId};
8043        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8044        info.sendBroadcast(false, false, false);
8045    }
8046
8047    /**
8048     * Returns true if application is not found or there was an error. Otherwise it returns
8049     * the hidden state of the package for the given user.
8050     */
8051    @Override
8052    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8053        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8054        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8055                false, "getApplicationHidden for user " + userId);
8056        PackageSetting pkgSetting;
8057        long callingId = Binder.clearCallingIdentity();
8058        try {
8059            // writer
8060            synchronized (mPackages) {
8061                pkgSetting = mSettings.mPackages.get(packageName);
8062                if (pkgSetting == null) {
8063                    return true;
8064                }
8065                return pkgSetting.getHidden(userId);
8066            }
8067        } finally {
8068            Binder.restoreCallingIdentity(callingId);
8069        }
8070    }
8071
8072    /**
8073     * @hide
8074     */
8075    @Override
8076    public int installExistingPackageAsUser(String packageName, int userId) {
8077        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8078                null);
8079        PackageSetting pkgSetting;
8080        final int uid = Binder.getCallingUid();
8081        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8082                + userId);
8083        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8084            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8085        }
8086
8087        long callingId = Binder.clearCallingIdentity();
8088        try {
8089            boolean sendAdded = false;
8090            Bundle extras = new Bundle(1);
8091
8092            // writer
8093            synchronized (mPackages) {
8094                pkgSetting = mSettings.mPackages.get(packageName);
8095                if (pkgSetting == null) {
8096                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8097                }
8098                if (!pkgSetting.getInstalled(userId)) {
8099                    pkgSetting.setInstalled(true, userId);
8100                    pkgSetting.setHidden(false, userId);
8101                    mSettings.writePackageRestrictionsLPr(userId);
8102                    sendAdded = true;
8103                }
8104            }
8105
8106            if (sendAdded) {
8107                sendPackageAddedForUser(packageName, pkgSetting, userId);
8108            }
8109        } finally {
8110            Binder.restoreCallingIdentity(callingId);
8111        }
8112
8113        return PackageManager.INSTALL_SUCCEEDED;
8114    }
8115
8116    boolean isUserRestricted(int userId, String restrictionKey) {
8117        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8118        if (restrictions.getBoolean(restrictionKey, false)) {
8119            Log.w(TAG, "User is restricted: " + restrictionKey);
8120            return true;
8121        }
8122        return false;
8123    }
8124
8125    @Override
8126    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8127        mContext.enforceCallingOrSelfPermission(
8128                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8129                "Only package verification agents can verify applications");
8130
8131        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8132        final PackageVerificationResponse response = new PackageVerificationResponse(
8133                verificationCode, Binder.getCallingUid());
8134        msg.arg1 = id;
8135        msg.obj = response;
8136        mHandler.sendMessage(msg);
8137    }
8138
8139    @Override
8140    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8141            long millisecondsToDelay) {
8142        mContext.enforceCallingOrSelfPermission(
8143                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8144                "Only package verification agents can extend verification timeouts");
8145
8146        final PackageVerificationState state = mPendingVerification.get(id);
8147        final PackageVerificationResponse response = new PackageVerificationResponse(
8148                verificationCodeAtTimeout, Binder.getCallingUid());
8149
8150        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8151            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8152        }
8153        if (millisecondsToDelay < 0) {
8154            millisecondsToDelay = 0;
8155        }
8156        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8157                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8158            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8159        }
8160
8161        if ((state != null) && !state.timeoutExtended()) {
8162            state.extendTimeout();
8163
8164            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8165            msg.arg1 = id;
8166            msg.obj = response;
8167            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8168        }
8169    }
8170
8171    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8172            int verificationCode, UserHandle user) {
8173        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8174        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8175        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8176        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8177        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8178
8179        mContext.sendBroadcastAsUser(intent, user,
8180                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8181    }
8182
8183    private ComponentName matchComponentForVerifier(String packageName,
8184            List<ResolveInfo> receivers) {
8185        ActivityInfo targetReceiver = null;
8186
8187        final int NR = receivers.size();
8188        for (int i = 0; i < NR; i++) {
8189            final ResolveInfo info = receivers.get(i);
8190            if (info.activityInfo == null) {
8191                continue;
8192            }
8193
8194            if (packageName.equals(info.activityInfo.packageName)) {
8195                targetReceiver = info.activityInfo;
8196                break;
8197            }
8198        }
8199
8200        if (targetReceiver == null) {
8201            return null;
8202        }
8203
8204        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8205    }
8206
8207    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8208            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8209        if (pkgInfo.verifiers.length == 0) {
8210            return null;
8211        }
8212
8213        final int N = pkgInfo.verifiers.length;
8214        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8215        for (int i = 0; i < N; i++) {
8216            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8217
8218            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8219                    receivers);
8220            if (comp == null) {
8221                continue;
8222            }
8223
8224            final int verifierUid = getUidForVerifier(verifierInfo);
8225            if (verifierUid == -1) {
8226                continue;
8227            }
8228
8229            if (DEBUG_VERIFY) {
8230                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8231                        + " with the correct signature");
8232            }
8233            sufficientVerifiers.add(comp);
8234            verificationState.addSufficientVerifier(verifierUid);
8235        }
8236
8237        return sufficientVerifiers;
8238    }
8239
8240    private int getUidForVerifier(VerifierInfo verifierInfo) {
8241        synchronized (mPackages) {
8242            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8243            if (pkg == null) {
8244                return -1;
8245            } else if (pkg.mSignatures.length != 1) {
8246                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8247                        + " has more than one signature; ignoring");
8248                return -1;
8249            }
8250
8251            /*
8252             * If the public key of the package's signature does not match
8253             * our expected public key, then this is a different package and
8254             * we should skip.
8255             */
8256
8257            final byte[] expectedPublicKey;
8258            try {
8259                final Signature verifierSig = pkg.mSignatures[0];
8260                final PublicKey publicKey = verifierSig.getPublicKey();
8261                expectedPublicKey = publicKey.getEncoded();
8262            } catch (CertificateException e) {
8263                return -1;
8264            }
8265
8266            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8267
8268            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8269                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8270                        + " does not have the expected public key; ignoring");
8271                return -1;
8272            }
8273
8274            return pkg.applicationInfo.uid;
8275        }
8276    }
8277
8278    @Override
8279    public void finishPackageInstall(int token) {
8280        enforceSystemOrRoot("Only the system is allowed to finish installs");
8281
8282        if (DEBUG_INSTALL) {
8283            Slog.v(TAG, "BM finishing package install for " + token);
8284        }
8285
8286        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8287        mHandler.sendMessage(msg);
8288    }
8289
8290    /**
8291     * Get the verification agent timeout.
8292     *
8293     * @return verification timeout in milliseconds
8294     */
8295    private long getVerificationTimeout() {
8296        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8297                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8298                DEFAULT_VERIFICATION_TIMEOUT);
8299    }
8300
8301    /**
8302     * Get the default verification agent response code.
8303     *
8304     * @return default verification response code
8305     */
8306    private int getDefaultVerificationResponse() {
8307        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8308                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8309                DEFAULT_VERIFICATION_RESPONSE);
8310    }
8311
8312    /**
8313     * Check whether or not package verification has been enabled.
8314     *
8315     * @return true if verification should be performed
8316     */
8317    private boolean isVerificationEnabled(int userId, int installFlags) {
8318        if (!DEFAULT_VERIFY_ENABLE) {
8319            return false;
8320        }
8321
8322        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8323
8324        // Check if installing from ADB
8325        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8326            // Do not run verification in a test harness environment
8327            if (ActivityManager.isRunningInTestHarness()) {
8328                return false;
8329            }
8330            if (ensureVerifyAppsEnabled) {
8331                return true;
8332            }
8333            // Check if the developer does not want package verification for ADB installs
8334            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8335                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8336                return false;
8337            }
8338        }
8339
8340        if (ensureVerifyAppsEnabled) {
8341            return true;
8342        }
8343
8344        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8345                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8346    }
8347
8348    /**
8349     * Get the "allow unknown sources" setting.
8350     *
8351     * @return the current "allow unknown sources" setting
8352     */
8353    private int getUnknownSourcesSettings() {
8354        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8355                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8356                -1);
8357    }
8358
8359    @Override
8360    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8361        final int uid = Binder.getCallingUid();
8362        // writer
8363        synchronized (mPackages) {
8364            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8365            if (targetPackageSetting == null) {
8366                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8367            }
8368
8369            PackageSetting installerPackageSetting;
8370            if (installerPackageName != null) {
8371                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8372                if (installerPackageSetting == null) {
8373                    throw new IllegalArgumentException("Unknown installer package: "
8374                            + installerPackageName);
8375                }
8376            } else {
8377                installerPackageSetting = null;
8378            }
8379
8380            Signature[] callerSignature;
8381            Object obj = mSettings.getUserIdLPr(uid);
8382            if (obj != null) {
8383                if (obj instanceof SharedUserSetting) {
8384                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8385                } else if (obj instanceof PackageSetting) {
8386                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8387                } else {
8388                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8389                }
8390            } else {
8391                throw new SecurityException("Unknown calling uid " + uid);
8392            }
8393
8394            // Verify: can't set installerPackageName to a package that is
8395            // not signed with the same cert as the caller.
8396            if (installerPackageSetting != null) {
8397                if (compareSignatures(callerSignature,
8398                        installerPackageSetting.signatures.mSignatures)
8399                        != PackageManager.SIGNATURE_MATCH) {
8400                    throw new SecurityException(
8401                            "Caller does not have same cert as new installer package "
8402                            + installerPackageName);
8403                }
8404            }
8405
8406            // Verify: if target already has an installer package, it must
8407            // be signed with the same cert as the caller.
8408            if (targetPackageSetting.installerPackageName != null) {
8409                PackageSetting setting = mSettings.mPackages.get(
8410                        targetPackageSetting.installerPackageName);
8411                // If the currently set package isn't valid, then it's always
8412                // okay to change it.
8413                if (setting != null) {
8414                    if (compareSignatures(callerSignature,
8415                            setting.signatures.mSignatures)
8416                            != PackageManager.SIGNATURE_MATCH) {
8417                        throw new SecurityException(
8418                                "Caller does not have same cert as old installer package "
8419                                + targetPackageSetting.installerPackageName);
8420                    }
8421                }
8422            }
8423
8424            // Okay!
8425            targetPackageSetting.installerPackageName = installerPackageName;
8426            scheduleWriteSettingsLocked();
8427        }
8428    }
8429
8430    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8431        // Queue up an async operation since the package installation may take a little while.
8432        mHandler.post(new Runnable() {
8433            public void run() {
8434                mHandler.removeCallbacks(this);
8435                 // Result object to be returned
8436                PackageInstalledInfo res = new PackageInstalledInfo();
8437                res.returnCode = currentStatus;
8438                res.uid = -1;
8439                res.pkg = null;
8440                res.removedInfo = new PackageRemovedInfo();
8441                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8442                    args.doPreInstall(res.returnCode);
8443                    synchronized (mInstallLock) {
8444                        installPackageLI(args, res);
8445                    }
8446                    args.doPostInstall(res.returnCode, res.uid);
8447                }
8448
8449                // A restore should be performed at this point if (a) the install
8450                // succeeded, (b) the operation is not an update, and (c) the new
8451                // package has not opted out of backup participation.
8452                final boolean update = res.removedInfo.removedPackage != null;
8453                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8454                boolean doRestore = !update
8455                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8456
8457                // Set up the post-install work request bookkeeping.  This will be used
8458                // and cleaned up by the post-install event handling regardless of whether
8459                // there's a restore pass performed.  Token values are >= 1.
8460                int token;
8461                if (mNextInstallToken < 0) mNextInstallToken = 1;
8462                token = mNextInstallToken++;
8463
8464                PostInstallData data = new PostInstallData(args, res);
8465                mRunningInstalls.put(token, data);
8466                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8467
8468                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8469                    // Pass responsibility to the Backup Manager.  It will perform a
8470                    // restore if appropriate, then pass responsibility back to the
8471                    // Package Manager to run the post-install observer callbacks
8472                    // and broadcasts.
8473                    IBackupManager bm = IBackupManager.Stub.asInterface(
8474                            ServiceManager.getService(Context.BACKUP_SERVICE));
8475                    if (bm != null) {
8476                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8477                                + " to BM for possible restore");
8478                        try {
8479                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8480                        } catch (RemoteException e) {
8481                            // can't happen; the backup manager is local
8482                        } catch (Exception e) {
8483                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8484                            doRestore = false;
8485                        }
8486                    } else {
8487                        Slog.e(TAG, "Backup Manager not found!");
8488                        doRestore = false;
8489                    }
8490                }
8491
8492                if (!doRestore) {
8493                    // No restore possible, or the Backup Manager was mysteriously not
8494                    // available -- just fire the post-install work request directly.
8495                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8496                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8497                    mHandler.sendMessage(msg);
8498                }
8499            }
8500        });
8501    }
8502
8503    private abstract class HandlerParams {
8504        private static final int MAX_RETRIES = 4;
8505
8506        /**
8507         * Number of times startCopy() has been attempted and had a non-fatal
8508         * error.
8509         */
8510        private int mRetries = 0;
8511
8512        /** User handle for the user requesting the information or installation. */
8513        private final UserHandle mUser;
8514
8515        HandlerParams(UserHandle user) {
8516            mUser = user;
8517        }
8518
8519        UserHandle getUser() {
8520            return mUser;
8521        }
8522
8523        final boolean startCopy() {
8524            boolean res;
8525            try {
8526                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8527
8528                if (++mRetries > MAX_RETRIES) {
8529                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8530                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8531                    handleServiceError();
8532                    return false;
8533                } else {
8534                    handleStartCopy();
8535                    res = true;
8536                }
8537            } catch (RemoteException e) {
8538                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8539                mHandler.sendEmptyMessage(MCS_RECONNECT);
8540                res = false;
8541            }
8542            handleReturnCode();
8543            return res;
8544        }
8545
8546        final void serviceError() {
8547            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8548            handleServiceError();
8549            handleReturnCode();
8550        }
8551
8552        abstract void handleStartCopy() throws RemoteException;
8553        abstract void handleServiceError();
8554        abstract void handleReturnCode();
8555    }
8556
8557    class MeasureParams extends HandlerParams {
8558        private final PackageStats mStats;
8559        private boolean mSuccess;
8560
8561        private final IPackageStatsObserver mObserver;
8562
8563        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8564            super(new UserHandle(stats.userHandle));
8565            mObserver = observer;
8566            mStats = stats;
8567        }
8568
8569        @Override
8570        public String toString() {
8571            return "MeasureParams{"
8572                + Integer.toHexString(System.identityHashCode(this))
8573                + " " + mStats.packageName + "}";
8574        }
8575
8576        @Override
8577        void handleStartCopy() throws RemoteException {
8578            synchronized (mInstallLock) {
8579                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8580            }
8581
8582            if (mSuccess) {
8583                final boolean mounted;
8584                if (Environment.isExternalStorageEmulated()) {
8585                    mounted = true;
8586                } else {
8587                    final String status = Environment.getExternalStorageState();
8588                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8589                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8590                }
8591
8592                if (mounted) {
8593                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8594
8595                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8596                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8597
8598                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8599                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8600
8601                    // Always subtract cache size, since it's a subdirectory
8602                    mStats.externalDataSize -= mStats.externalCacheSize;
8603
8604                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8605                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8606
8607                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8608                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8609                }
8610            }
8611        }
8612
8613        @Override
8614        void handleReturnCode() {
8615            if (mObserver != null) {
8616                try {
8617                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8618                } catch (RemoteException e) {
8619                    Slog.i(TAG, "Observer no longer exists.");
8620                }
8621            }
8622        }
8623
8624        @Override
8625        void handleServiceError() {
8626            Slog.e(TAG, "Could not measure application " + mStats.packageName
8627                            + " external storage");
8628        }
8629    }
8630
8631    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8632            throws RemoteException {
8633        long result = 0;
8634        for (File path : paths) {
8635            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8636        }
8637        return result;
8638    }
8639
8640    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8641        for (File path : paths) {
8642            try {
8643                mcs.clearDirectory(path.getAbsolutePath());
8644            } catch (RemoteException e) {
8645            }
8646        }
8647    }
8648
8649    static class OriginInfo {
8650        /**
8651         * Location where install is coming from, before it has been
8652         * copied/renamed into place. This could be a single monolithic APK
8653         * file, or a cluster directory. This location may be untrusted.
8654         */
8655        final File file;
8656        final String cid;
8657
8658        /**
8659         * Flag indicating that {@link #file} or {@link #cid} has already been
8660         * staged, meaning downstream users don't need to defensively copy the
8661         * contents.
8662         */
8663        final boolean staged;
8664
8665        /**
8666         * Flag indicating that {@link #file} or {@link #cid} is an already
8667         * installed app that is being moved.
8668         */
8669        final boolean existing;
8670
8671        final String resolvedPath;
8672        final File resolvedFile;
8673
8674        static OriginInfo fromNothing() {
8675            return new OriginInfo(null, null, false, false);
8676        }
8677
8678        static OriginInfo fromUntrustedFile(File file) {
8679            return new OriginInfo(file, null, false, false);
8680        }
8681
8682        static OriginInfo fromExistingFile(File file) {
8683            return new OriginInfo(file, null, false, true);
8684        }
8685
8686        static OriginInfo fromStagedFile(File file) {
8687            return new OriginInfo(file, null, true, false);
8688        }
8689
8690        static OriginInfo fromStagedContainer(String cid) {
8691            return new OriginInfo(null, cid, true, false);
8692        }
8693
8694        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8695            this.file = file;
8696            this.cid = cid;
8697            this.staged = staged;
8698            this.existing = existing;
8699
8700            if (cid != null) {
8701                resolvedPath = PackageHelper.getSdDir(cid);
8702                resolvedFile = new File(resolvedPath);
8703            } else if (file != null) {
8704                resolvedPath = file.getAbsolutePath();
8705                resolvedFile = file;
8706            } else {
8707                resolvedPath = null;
8708                resolvedFile = null;
8709            }
8710        }
8711    }
8712
8713    class InstallParams extends HandlerParams {
8714        final OriginInfo origin;
8715        final IPackageInstallObserver2 observer;
8716        int installFlags;
8717        final String installerPackageName;
8718        final VerificationParams verificationParams;
8719        private InstallArgs mArgs;
8720        private int mRet;
8721        final String packageAbiOverride;
8722
8723        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8724                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8725                String packageAbiOverride) {
8726            super(user);
8727            this.origin = origin;
8728            this.observer = observer;
8729            this.installFlags = installFlags;
8730            this.installerPackageName = installerPackageName;
8731            this.verificationParams = verificationParams;
8732            this.packageAbiOverride = packageAbiOverride;
8733        }
8734
8735        @Override
8736        public String toString() {
8737            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8738                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8739        }
8740
8741        public ManifestDigest getManifestDigest() {
8742            if (verificationParams == null) {
8743                return null;
8744            }
8745            return verificationParams.getManifestDigest();
8746        }
8747
8748        private int installLocationPolicy(PackageInfoLite pkgLite) {
8749            String packageName = pkgLite.packageName;
8750            int installLocation = pkgLite.installLocation;
8751            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8752            // reader
8753            synchronized (mPackages) {
8754                PackageParser.Package pkg = mPackages.get(packageName);
8755                if (pkg != null) {
8756                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8757                        // Check for downgrading.
8758                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8759                            if (pkgLite.versionCode < pkg.mVersionCode) {
8760                                Slog.w(TAG, "Can't install update of " + packageName
8761                                        + " update version " + pkgLite.versionCode
8762                                        + " is older than installed version "
8763                                        + pkg.mVersionCode);
8764                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8765                            }
8766                        }
8767                        // Check for updated system application.
8768                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8769                            if (onSd) {
8770                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8771                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8772                            }
8773                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8774                        } else {
8775                            if (onSd) {
8776                                // Install flag overrides everything.
8777                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8778                            }
8779                            // If current upgrade specifies particular preference
8780                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8781                                // Application explicitly specified internal.
8782                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8783                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8784                                // App explictly prefers external. Let policy decide
8785                            } else {
8786                                // Prefer previous location
8787                                if (isExternal(pkg)) {
8788                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8789                                }
8790                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8791                            }
8792                        }
8793                    } else {
8794                        // Invalid install. Return error code
8795                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8796                    }
8797                }
8798            }
8799            // All the special cases have been taken care of.
8800            // Return result based on recommended install location.
8801            if (onSd) {
8802                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8803            }
8804            return pkgLite.recommendedInstallLocation;
8805        }
8806
8807        /*
8808         * Invoke remote method to get package information and install
8809         * location values. Override install location based on default
8810         * policy if needed and then create install arguments based
8811         * on the install location.
8812         */
8813        public void handleStartCopy() throws RemoteException {
8814            int ret = PackageManager.INSTALL_SUCCEEDED;
8815
8816            // If we're already staged, we've firmly committed to an install location
8817            if (origin.staged) {
8818                if (origin.file != null) {
8819                    installFlags |= PackageManager.INSTALL_INTERNAL;
8820                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8821                } else if (origin.cid != null) {
8822                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8823                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8824                } else {
8825                    throw new IllegalStateException("Invalid stage location");
8826                }
8827            }
8828
8829            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8830            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8831
8832            PackageInfoLite pkgLite = null;
8833
8834            if (onInt && onSd) {
8835                // Check if both bits are set.
8836                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8837                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8838            } else {
8839                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8840                        packageAbiOverride);
8841
8842                /*
8843                 * If we have too little free space, try to free cache
8844                 * before giving up.
8845                 */
8846                if (!origin.staged && pkgLite.recommendedInstallLocation
8847                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8848                    // TODO: focus freeing disk space on the target device
8849                    final StorageManager storage = StorageManager.from(mContext);
8850                    final long lowThreshold = storage.getStorageLowBytes(
8851                            Environment.getDataDirectory());
8852
8853                    final long sizeBytes = mContainerService.calculateInstalledSize(
8854                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8855
8856                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8857                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8858                                installFlags, packageAbiOverride);
8859                    }
8860
8861                    /*
8862                     * The cache free must have deleted the file we
8863                     * downloaded to install.
8864                     *
8865                     * TODO: fix the "freeCache" call to not delete
8866                     *       the file we care about.
8867                     */
8868                    if (pkgLite.recommendedInstallLocation
8869                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8870                        pkgLite.recommendedInstallLocation
8871                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8872                    }
8873                }
8874            }
8875
8876            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8877                int loc = pkgLite.recommendedInstallLocation;
8878                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8879                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8880                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8881                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8882                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8883                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8884                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8885                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8886                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8887                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8888                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8889                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8890                } else {
8891                    // Override with defaults if needed.
8892                    loc = installLocationPolicy(pkgLite);
8893                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8894                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8895                    } else if (!onSd && !onInt) {
8896                        // Override install location with flags
8897                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8898                            // Set the flag to install on external media.
8899                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8900                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8901                        } else {
8902                            // Make sure the flag for installing on external
8903                            // media is unset
8904                            installFlags |= PackageManager.INSTALL_INTERNAL;
8905                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8906                        }
8907                    }
8908                }
8909            }
8910
8911            final InstallArgs args = createInstallArgs(this);
8912            mArgs = args;
8913
8914            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8915                 /*
8916                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8917                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8918                 */
8919                int userIdentifier = getUser().getIdentifier();
8920                if (userIdentifier == UserHandle.USER_ALL
8921                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8922                    userIdentifier = UserHandle.USER_OWNER;
8923                }
8924
8925                /*
8926                 * Determine if we have any installed package verifiers. If we
8927                 * do, then we'll defer to them to verify the packages.
8928                 */
8929                final int requiredUid = mRequiredVerifierPackage == null ? -1
8930                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8931                if (!origin.existing && requiredUid != -1
8932                        && isVerificationEnabled(userIdentifier, installFlags)) {
8933                    final Intent verification = new Intent(
8934                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8935                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8936                            PACKAGE_MIME_TYPE);
8937                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8938
8939                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8940                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8941                            0 /* TODO: Which userId? */);
8942
8943                    if (DEBUG_VERIFY) {
8944                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8945                                + verification.toString() + " with " + pkgLite.verifiers.length
8946                                + " optional verifiers");
8947                    }
8948
8949                    final int verificationId = mPendingVerificationToken++;
8950
8951                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8952
8953                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8954                            installerPackageName);
8955
8956                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8957                            installFlags);
8958
8959                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8960                            pkgLite.packageName);
8961
8962                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8963                            pkgLite.versionCode);
8964
8965                    if (verificationParams != null) {
8966                        if (verificationParams.getVerificationURI() != null) {
8967                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8968                                 verificationParams.getVerificationURI());
8969                        }
8970                        if (verificationParams.getOriginatingURI() != null) {
8971                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8972                                  verificationParams.getOriginatingURI());
8973                        }
8974                        if (verificationParams.getReferrer() != null) {
8975                            verification.putExtra(Intent.EXTRA_REFERRER,
8976                                  verificationParams.getReferrer());
8977                        }
8978                        if (verificationParams.getOriginatingUid() >= 0) {
8979                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8980                                  verificationParams.getOriginatingUid());
8981                        }
8982                        if (verificationParams.getInstallerUid() >= 0) {
8983                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8984                                  verificationParams.getInstallerUid());
8985                        }
8986                    }
8987
8988                    final PackageVerificationState verificationState = new PackageVerificationState(
8989                            requiredUid, args);
8990
8991                    mPendingVerification.append(verificationId, verificationState);
8992
8993                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8994                            receivers, verificationState);
8995
8996                    /*
8997                     * If any sufficient verifiers were listed in the package
8998                     * manifest, attempt to ask them.
8999                     */
9000                    if (sufficientVerifiers != null) {
9001                        final int N = sufficientVerifiers.size();
9002                        if (N == 0) {
9003                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9004                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9005                        } else {
9006                            for (int i = 0; i < N; i++) {
9007                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9008
9009                                final Intent sufficientIntent = new Intent(verification);
9010                                sufficientIntent.setComponent(verifierComponent);
9011
9012                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9013                            }
9014                        }
9015                    }
9016
9017                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9018                            mRequiredVerifierPackage, receivers);
9019                    if (ret == PackageManager.INSTALL_SUCCEEDED
9020                            && mRequiredVerifierPackage != null) {
9021                        /*
9022                         * Send the intent to the required verification agent,
9023                         * but only start the verification timeout after the
9024                         * target BroadcastReceivers have run.
9025                         */
9026                        verification.setComponent(requiredVerifierComponent);
9027                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9028                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9029                                new BroadcastReceiver() {
9030                                    @Override
9031                                    public void onReceive(Context context, Intent intent) {
9032                                        final Message msg = mHandler
9033                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9034                                        msg.arg1 = verificationId;
9035                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9036                                    }
9037                                }, null, 0, null, null);
9038
9039                        /*
9040                         * We don't want the copy to proceed until verification
9041                         * succeeds, so null out this field.
9042                         */
9043                        mArgs = null;
9044                    }
9045                } else {
9046                    /*
9047                     * No package verification is enabled, so immediately start
9048                     * the remote call to initiate copy using temporary file.
9049                     */
9050                    ret = args.copyApk(mContainerService, true);
9051                }
9052            }
9053
9054            mRet = ret;
9055        }
9056
9057        @Override
9058        void handleReturnCode() {
9059            // If mArgs is null, then MCS couldn't be reached. When it
9060            // reconnects, it will try again to install. At that point, this
9061            // will succeed.
9062            if (mArgs != null) {
9063                processPendingInstall(mArgs, mRet);
9064            }
9065        }
9066
9067        @Override
9068        void handleServiceError() {
9069            mArgs = createInstallArgs(this);
9070            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9071        }
9072
9073        public boolean isForwardLocked() {
9074            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9075        }
9076    }
9077
9078    /**
9079     * Used during creation of InstallArgs
9080     *
9081     * @param installFlags package installation flags
9082     * @return true if should be installed on external storage
9083     */
9084    private static boolean installOnSd(int installFlags) {
9085        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9086            return false;
9087        }
9088        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9089            return true;
9090        }
9091        return false;
9092    }
9093
9094    /**
9095     * Used during creation of InstallArgs
9096     *
9097     * @param installFlags package installation flags
9098     * @return true if should be installed as forward locked
9099     */
9100    private static boolean installForwardLocked(int installFlags) {
9101        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9102    }
9103
9104    private InstallArgs createInstallArgs(InstallParams params) {
9105        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9106            return new AsecInstallArgs(params);
9107        } else {
9108            return new FileInstallArgs(params);
9109        }
9110    }
9111
9112    /**
9113     * Create args that describe an existing installed package. Typically used
9114     * when cleaning up old installs, or used as a move source.
9115     */
9116    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9117            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9118        final boolean isInAsec;
9119        if (installOnSd(installFlags)) {
9120            /* Apps on SD card are always in ASEC containers. */
9121            isInAsec = true;
9122        } else if (installForwardLocked(installFlags)
9123                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9124            /*
9125             * Forward-locked apps are only in ASEC containers if they're the
9126             * new style
9127             */
9128            isInAsec = true;
9129        } else {
9130            isInAsec = false;
9131        }
9132
9133        if (isInAsec) {
9134            return new AsecInstallArgs(codePath, instructionSets,
9135                    installOnSd(installFlags), installForwardLocked(installFlags));
9136        } else {
9137            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9138                    instructionSets);
9139        }
9140    }
9141
9142    static abstract class InstallArgs {
9143        /** @see InstallParams#origin */
9144        final OriginInfo origin;
9145
9146        final IPackageInstallObserver2 observer;
9147        // Always refers to PackageManager flags only
9148        final int installFlags;
9149        final String installerPackageName;
9150        final ManifestDigest manifestDigest;
9151        final UserHandle user;
9152        final String abiOverride;
9153
9154        // The list of instruction sets supported by this app. This is currently
9155        // only used during the rmdex() phase to clean up resources. We can get rid of this
9156        // if we move dex files under the common app path.
9157        /* nullable */ String[] instructionSets;
9158
9159        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9160                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9161                String[] instructionSets, String abiOverride) {
9162            this.origin = origin;
9163            this.installFlags = installFlags;
9164            this.observer = observer;
9165            this.installerPackageName = installerPackageName;
9166            this.manifestDigest = manifestDigest;
9167            this.user = user;
9168            this.instructionSets = instructionSets;
9169            this.abiOverride = abiOverride;
9170        }
9171
9172        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9173        abstract int doPreInstall(int status);
9174
9175        /**
9176         * Rename package into final resting place. All paths on the given
9177         * scanned package should be updated to reflect the rename.
9178         */
9179        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9180        abstract int doPostInstall(int status, int uid);
9181
9182        /** @see PackageSettingBase#codePathString */
9183        abstract String getCodePath();
9184        /** @see PackageSettingBase#resourcePathString */
9185        abstract String getResourcePath();
9186        abstract String getLegacyNativeLibraryPath();
9187
9188        // Need installer lock especially for dex file removal.
9189        abstract void cleanUpResourcesLI();
9190        abstract boolean doPostDeleteLI(boolean delete);
9191        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9192
9193        /**
9194         * Called before the source arguments are copied. This is used mostly
9195         * for MoveParams when it needs to read the source file to put it in the
9196         * destination.
9197         */
9198        int doPreCopy() {
9199            return PackageManager.INSTALL_SUCCEEDED;
9200        }
9201
9202        /**
9203         * Called after the source arguments are copied. This is used mostly for
9204         * MoveParams when it needs to read the source file to put it in the
9205         * destination.
9206         *
9207         * @return
9208         */
9209        int doPostCopy(int uid) {
9210            return PackageManager.INSTALL_SUCCEEDED;
9211        }
9212
9213        protected boolean isFwdLocked() {
9214            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9215        }
9216
9217        protected boolean isExternal() {
9218            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9219        }
9220
9221        UserHandle getUser() {
9222            return user;
9223        }
9224    }
9225
9226    /**
9227     * Logic to handle installation of non-ASEC applications, including copying
9228     * and renaming logic.
9229     */
9230    class FileInstallArgs extends InstallArgs {
9231        private File codeFile;
9232        private File resourceFile;
9233        private File legacyNativeLibraryPath;
9234
9235        // Example topology:
9236        // /data/app/com.example/base.apk
9237        // /data/app/com.example/split_foo.apk
9238        // /data/app/com.example/lib/arm/libfoo.so
9239        // /data/app/com.example/lib/arm64/libfoo.so
9240        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9241
9242        /** New install */
9243        FileInstallArgs(InstallParams params) {
9244            super(params.origin, params.observer, params.installFlags,
9245                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9246                    null /* instruction sets */, params.packageAbiOverride);
9247            if (isFwdLocked()) {
9248                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9249            }
9250        }
9251
9252        /** Existing install */
9253        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9254                String[] instructionSets) {
9255            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9256            this.codeFile = (codePath != null) ? new File(codePath) : null;
9257            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9258            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9259                    new File(legacyNativeLibraryPath) : null;
9260        }
9261
9262        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9263            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9264                    isFwdLocked(), abiOverride);
9265
9266            final StorageManager storage = StorageManager.from(mContext);
9267            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9268        }
9269
9270        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9271            if (origin.staged) {
9272                Slog.d(TAG, origin.file + " already staged; skipping copy");
9273                codeFile = origin.file;
9274                resourceFile = origin.file;
9275                return PackageManager.INSTALL_SUCCEEDED;
9276            }
9277
9278            try {
9279                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9280                codeFile = tempDir;
9281                resourceFile = tempDir;
9282            } catch (IOException e) {
9283                Slog.w(TAG, "Failed to create copy file: " + e);
9284                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9285            }
9286
9287            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9288                @Override
9289                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9290                    if (!FileUtils.isValidExtFilename(name)) {
9291                        throw new IllegalArgumentException("Invalid filename: " + name);
9292                    }
9293                    try {
9294                        final File file = new File(codeFile, name);
9295                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9296                                O_RDWR | O_CREAT, 0644);
9297                        Os.chmod(file.getAbsolutePath(), 0644);
9298                        return new ParcelFileDescriptor(fd);
9299                    } catch (ErrnoException e) {
9300                        throw new RemoteException("Failed to open: " + e.getMessage());
9301                    }
9302                }
9303            };
9304
9305            int ret = PackageManager.INSTALL_SUCCEEDED;
9306            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9307            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9308                Slog.e(TAG, "Failed to copy package");
9309                return ret;
9310            }
9311
9312            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9313            NativeLibraryHelper.Handle handle = null;
9314            try {
9315                handle = NativeLibraryHelper.Handle.create(codeFile);
9316                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9317                        abiOverride);
9318            } catch (IOException e) {
9319                Slog.e(TAG, "Copying native libraries failed", e);
9320                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9321            } finally {
9322                IoUtils.closeQuietly(handle);
9323            }
9324
9325            return ret;
9326        }
9327
9328        int doPreInstall(int status) {
9329            if (status != PackageManager.INSTALL_SUCCEEDED) {
9330                cleanUp();
9331            }
9332            return status;
9333        }
9334
9335        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9336            if (status != PackageManager.INSTALL_SUCCEEDED) {
9337                cleanUp();
9338                return false;
9339            } else {
9340                final File beforeCodeFile = codeFile;
9341                final File afterCodeFile = getNextCodePath(pkg.packageName);
9342
9343                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9344                try {
9345                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9346                } catch (ErrnoException e) {
9347                    Slog.d(TAG, "Failed to rename", e);
9348                    return false;
9349                }
9350
9351                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9352                    Slog.d(TAG, "Failed to restorecon");
9353                    return false;
9354                }
9355
9356                // Reflect the rename internally
9357                codeFile = afterCodeFile;
9358                resourceFile = afterCodeFile;
9359
9360                // Reflect the rename in scanned details
9361                pkg.codePath = afterCodeFile.getAbsolutePath();
9362                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9363                        pkg.baseCodePath);
9364                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9365                        pkg.splitCodePaths);
9366
9367                // Reflect the rename in app info
9368                pkg.applicationInfo.setCodePath(pkg.codePath);
9369                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9370                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9371                pkg.applicationInfo.setResourcePath(pkg.codePath);
9372                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9373                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9374
9375                return true;
9376            }
9377        }
9378
9379        int doPostInstall(int status, int uid) {
9380            if (status != PackageManager.INSTALL_SUCCEEDED) {
9381                cleanUp();
9382            }
9383            return status;
9384        }
9385
9386        @Override
9387        String getCodePath() {
9388            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9389        }
9390
9391        @Override
9392        String getResourcePath() {
9393            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9394        }
9395
9396        @Override
9397        String getLegacyNativeLibraryPath() {
9398            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9399        }
9400
9401        private boolean cleanUp() {
9402            if (codeFile == null || !codeFile.exists()) {
9403                return false;
9404            }
9405
9406            if (codeFile.isDirectory()) {
9407                FileUtils.deleteContents(codeFile);
9408            }
9409            codeFile.delete();
9410
9411            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9412                resourceFile.delete();
9413            }
9414
9415            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9416                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9417                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9418                }
9419                legacyNativeLibraryPath.delete();
9420            }
9421
9422            return true;
9423        }
9424
9425        void cleanUpResourcesLI() {
9426            // Try enumerating all code paths before deleting
9427            List<String> allCodePaths = Collections.EMPTY_LIST;
9428            if (codeFile != null && codeFile.exists()) {
9429                try {
9430                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9431                    allCodePaths = pkg.getAllCodePaths();
9432                } catch (PackageParserException e) {
9433                    // Ignored; we tried our best
9434                }
9435            }
9436
9437            cleanUp();
9438
9439            if (!allCodePaths.isEmpty()) {
9440                if (instructionSets == null) {
9441                    throw new IllegalStateException("instructionSet == null");
9442                }
9443                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9444                for (String codePath : allCodePaths) {
9445                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9446                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9447                        if (retCode < 0) {
9448                            Slog.w(TAG, "Couldn't remove dex file for package: "
9449                                    + " at location " + codePath + ", retcode=" + retCode);
9450                            // we don't consider this to be a failure of the core package deletion
9451                        }
9452                    }
9453                }
9454            }
9455        }
9456
9457        boolean doPostDeleteLI(boolean delete) {
9458            // XXX err, shouldn't we respect the delete flag?
9459            cleanUpResourcesLI();
9460            return true;
9461        }
9462    }
9463
9464    private boolean isAsecExternal(String cid) {
9465        final String asecPath = PackageHelper.getSdFilesystem(cid);
9466        return !asecPath.startsWith(mAsecInternalPath);
9467    }
9468
9469    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9470            PackageManagerException {
9471        if (copyRet < 0) {
9472            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9473                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9474                throw new PackageManagerException(copyRet, message);
9475            }
9476        }
9477    }
9478
9479    /**
9480     * Extract the MountService "container ID" from the full code path of an
9481     * .apk.
9482     */
9483    static String cidFromCodePath(String fullCodePath) {
9484        int eidx = fullCodePath.lastIndexOf("/");
9485        String subStr1 = fullCodePath.substring(0, eidx);
9486        int sidx = subStr1.lastIndexOf("/");
9487        return subStr1.substring(sidx+1, eidx);
9488    }
9489
9490    /**
9491     * Logic to handle installation of ASEC applications, including copying and
9492     * renaming logic.
9493     */
9494    class AsecInstallArgs extends InstallArgs {
9495        static final String RES_FILE_NAME = "pkg.apk";
9496        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9497
9498        String cid;
9499        String packagePath;
9500        String resourcePath;
9501        String legacyNativeLibraryDir;
9502
9503        /** New install */
9504        AsecInstallArgs(InstallParams params) {
9505            super(params.origin, params.observer, params.installFlags,
9506                    params.installerPackageName, params.getManifestDigest(),
9507                    params.getUser(), null /* instruction sets */,
9508                    params.packageAbiOverride);
9509        }
9510
9511        /** Existing install */
9512        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9513                        boolean isExternal, boolean isForwardLocked) {
9514            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9515                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9516                    instructionSets, null);
9517            // Hackily pretend we're still looking at a full code path
9518            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9519                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9520            }
9521
9522            // Extract cid from fullCodePath
9523            int eidx = fullCodePath.lastIndexOf("/");
9524            String subStr1 = fullCodePath.substring(0, eidx);
9525            int sidx = subStr1.lastIndexOf("/");
9526            cid = subStr1.substring(sidx+1, eidx);
9527            setMountPath(subStr1);
9528        }
9529
9530        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9531            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9532                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9533                    instructionSets, null);
9534            this.cid = cid;
9535            setMountPath(PackageHelper.getSdDir(cid));
9536        }
9537
9538        void createCopyFile() {
9539            cid = mInstallerService.allocateExternalStageCidLegacy();
9540        }
9541
9542        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9543            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9544                    abiOverride);
9545
9546            final File target;
9547            if (isExternal()) {
9548                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9549            } else {
9550                target = Environment.getDataDirectory();
9551            }
9552
9553            final StorageManager storage = StorageManager.from(mContext);
9554            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9555        }
9556
9557        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9558            if (origin.staged) {
9559                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9560                cid = origin.cid;
9561                setMountPath(PackageHelper.getSdDir(cid));
9562                return PackageManager.INSTALL_SUCCEEDED;
9563            }
9564
9565            if (temp) {
9566                createCopyFile();
9567            } else {
9568                /*
9569                 * Pre-emptively destroy the container since it's destroyed if
9570                 * copying fails due to it existing anyway.
9571                 */
9572                PackageHelper.destroySdDir(cid);
9573            }
9574
9575            final String newMountPath = imcs.copyPackageToContainer(
9576                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9577                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9578
9579            if (newMountPath != null) {
9580                setMountPath(newMountPath);
9581                return PackageManager.INSTALL_SUCCEEDED;
9582            } else {
9583                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9584            }
9585        }
9586
9587        @Override
9588        String getCodePath() {
9589            return packagePath;
9590        }
9591
9592        @Override
9593        String getResourcePath() {
9594            return resourcePath;
9595        }
9596
9597        @Override
9598        String getLegacyNativeLibraryPath() {
9599            return legacyNativeLibraryDir;
9600        }
9601
9602        int doPreInstall(int status) {
9603            if (status != PackageManager.INSTALL_SUCCEEDED) {
9604                // Destroy container
9605                PackageHelper.destroySdDir(cid);
9606            } else {
9607                boolean mounted = PackageHelper.isContainerMounted(cid);
9608                if (!mounted) {
9609                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9610                            Process.SYSTEM_UID);
9611                    if (newMountPath != null) {
9612                        setMountPath(newMountPath);
9613                    } else {
9614                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9615                    }
9616                }
9617            }
9618            return status;
9619        }
9620
9621        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9622            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9623            String newMountPath = null;
9624            if (PackageHelper.isContainerMounted(cid)) {
9625                // Unmount the container
9626                if (!PackageHelper.unMountSdDir(cid)) {
9627                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9628                    return false;
9629                }
9630            }
9631            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9632                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9633                        " which might be stale. Will try to clean up.");
9634                // Clean up the stale container and proceed to recreate.
9635                if (!PackageHelper.destroySdDir(newCacheId)) {
9636                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9637                    return false;
9638                }
9639                // Successfully cleaned up stale container. Try to rename again.
9640                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9641                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9642                            + " inspite of cleaning it up.");
9643                    return false;
9644                }
9645            }
9646            if (!PackageHelper.isContainerMounted(newCacheId)) {
9647                Slog.w(TAG, "Mounting container " + newCacheId);
9648                newMountPath = PackageHelper.mountSdDir(newCacheId,
9649                        getEncryptKey(), Process.SYSTEM_UID);
9650            } else {
9651                newMountPath = PackageHelper.getSdDir(newCacheId);
9652            }
9653            if (newMountPath == null) {
9654                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9655                return false;
9656            }
9657            Log.i(TAG, "Succesfully renamed " + cid +
9658                    " to " + newCacheId +
9659                    " at new path: " + newMountPath);
9660            cid = newCacheId;
9661
9662            final File beforeCodeFile = new File(packagePath);
9663            setMountPath(newMountPath);
9664            final File afterCodeFile = new File(packagePath);
9665
9666            // Reflect the rename in scanned details
9667            pkg.codePath = afterCodeFile.getAbsolutePath();
9668            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9669                    pkg.baseCodePath);
9670            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9671                    pkg.splitCodePaths);
9672
9673            // Reflect the rename in app info
9674            pkg.applicationInfo.setCodePath(pkg.codePath);
9675            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9676            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9677            pkg.applicationInfo.setResourcePath(pkg.codePath);
9678            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9679            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9680
9681            return true;
9682        }
9683
9684        private void setMountPath(String mountPath) {
9685            final File mountFile = new File(mountPath);
9686
9687            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9688            if (monolithicFile.exists()) {
9689                packagePath = monolithicFile.getAbsolutePath();
9690                if (isFwdLocked()) {
9691                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9692                } else {
9693                    resourcePath = packagePath;
9694                }
9695            } else {
9696                packagePath = mountFile.getAbsolutePath();
9697                resourcePath = packagePath;
9698            }
9699
9700            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9701        }
9702
9703        int doPostInstall(int status, int uid) {
9704            if (status != PackageManager.INSTALL_SUCCEEDED) {
9705                cleanUp();
9706            } else {
9707                final int groupOwner;
9708                final String protectedFile;
9709                if (isFwdLocked()) {
9710                    groupOwner = UserHandle.getSharedAppGid(uid);
9711                    protectedFile = RES_FILE_NAME;
9712                } else {
9713                    groupOwner = -1;
9714                    protectedFile = null;
9715                }
9716
9717                if (uid < Process.FIRST_APPLICATION_UID
9718                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9719                    Slog.e(TAG, "Failed to finalize " + cid);
9720                    PackageHelper.destroySdDir(cid);
9721                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9722                }
9723
9724                boolean mounted = PackageHelper.isContainerMounted(cid);
9725                if (!mounted) {
9726                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9727                }
9728            }
9729            return status;
9730        }
9731
9732        private void cleanUp() {
9733            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9734
9735            // Destroy secure container
9736            PackageHelper.destroySdDir(cid);
9737        }
9738
9739        private List<String> getAllCodePaths() {
9740            final File codeFile = new File(getCodePath());
9741            if (codeFile != null && codeFile.exists()) {
9742                try {
9743                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9744                    return pkg.getAllCodePaths();
9745                } catch (PackageParserException e) {
9746                    // Ignored; we tried our best
9747                }
9748            }
9749            return Collections.EMPTY_LIST;
9750        }
9751
9752        void cleanUpResourcesLI() {
9753            // Enumerate all code paths before deleting
9754            cleanUpResourcesLI(getAllCodePaths());
9755        }
9756
9757        private void cleanUpResourcesLI(List<String> allCodePaths) {
9758            cleanUp();
9759
9760            if (!allCodePaths.isEmpty()) {
9761                if (instructionSets == null) {
9762                    throw new IllegalStateException("instructionSet == null");
9763                }
9764                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9765                for (String codePath : allCodePaths) {
9766                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9767                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9768                        if (retCode < 0) {
9769                            Slog.w(TAG, "Couldn't remove dex file for package: "
9770                                    + " at location " + codePath + ", retcode=" + retCode);
9771                            // we don't consider this to be a failure of the core package deletion
9772                        }
9773                    }
9774                }
9775            }
9776        }
9777
9778        boolean matchContainer(String app) {
9779            if (cid.startsWith(app)) {
9780                return true;
9781            }
9782            return false;
9783        }
9784
9785        String getPackageName() {
9786            return getAsecPackageName(cid);
9787        }
9788
9789        boolean doPostDeleteLI(boolean delete) {
9790            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9791            final List<String> allCodePaths = getAllCodePaths();
9792            boolean mounted = PackageHelper.isContainerMounted(cid);
9793            if (mounted) {
9794                // Unmount first
9795                if (PackageHelper.unMountSdDir(cid)) {
9796                    mounted = false;
9797                }
9798            }
9799            if (!mounted && delete) {
9800                cleanUpResourcesLI(allCodePaths);
9801            }
9802            return !mounted;
9803        }
9804
9805        @Override
9806        int doPreCopy() {
9807            if (isFwdLocked()) {
9808                if (!PackageHelper.fixSdPermissions(cid,
9809                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9810                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9811                }
9812            }
9813
9814            return PackageManager.INSTALL_SUCCEEDED;
9815        }
9816
9817        @Override
9818        int doPostCopy(int uid) {
9819            if (isFwdLocked()) {
9820                if (uid < Process.FIRST_APPLICATION_UID
9821                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9822                                RES_FILE_NAME)) {
9823                    Slog.e(TAG, "Failed to finalize " + cid);
9824                    PackageHelper.destroySdDir(cid);
9825                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9826                }
9827            }
9828
9829            return PackageManager.INSTALL_SUCCEEDED;
9830        }
9831    }
9832
9833    static String getAsecPackageName(String packageCid) {
9834        int idx = packageCid.lastIndexOf("-");
9835        if (idx == -1) {
9836            return packageCid;
9837        }
9838        return packageCid.substring(0, idx);
9839    }
9840
9841    // Utility method used to create code paths based on package name and available index.
9842    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9843        String idxStr = "";
9844        int idx = 1;
9845        // Fall back to default value of idx=1 if prefix is not
9846        // part of oldCodePath
9847        if (oldCodePath != null) {
9848            String subStr = oldCodePath;
9849            // Drop the suffix right away
9850            if (suffix != null && subStr.endsWith(suffix)) {
9851                subStr = subStr.substring(0, subStr.length() - suffix.length());
9852            }
9853            // If oldCodePath already contains prefix find out the
9854            // ending index to either increment or decrement.
9855            int sidx = subStr.lastIndexOf(prefix);
9856            if (sidx != -1) {
9857                subStr = subStr.substring(sidx + prefix.length());
9858                if (subStr != null) {
9859                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9860                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9861                    }
9862                    try {
9863                        idx = Integer.parseInt(subStr);
9864                        if (idx <= 1) {
9865                            idx++;
9866                        } else {
9867                            idx--;
9868                        }
9869                    } catch(NumberFormatException e) {
9870                    }
9871                }
9872            }
9873        }
9874        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9875        return prefix + idxStr;
9876    }
9877
9878    private File getNextCodePath(String packageName) {
9879        int suffix = 1;
9880        File result;
9881        do {
9882            result = new File(mAppInstallDir, packageName + "-" + suffix);
9883            suffix++;
9884        } while (result.exists());
9885        return result;
9886    }
9887
9888    // Utility method used to ignore ADD/REMOVE events
9889    // by directory observer.
9890    private static boolean ignoreCodePath(String fullPathStr) {
9891        String apkName = deriveCodePathName(fullPathStr);
9892        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9893        if (idx != -1 && ((idx+1) < apkName.length())) {
9894            // Make sure the package ends with a numeral
9895            String version = apkName.substring(idx+1);
9896            try {
9897                Integer.parseInt(version);
9898                return true;
9899            } catch (NumberFormatException e) {}
9900        }
9901        return false;
9902    }
9903
9904    // Utility method that returns the relative package path with respect
9905    // to the installation directory. Like say for /data/data/com.test-1.apk
9906    // string com.test-1 is returned.
9907    static String deriveCodePathName(String codePath) {
9908        if (codePath == null) {
9909            return null;
9910        }
9911        final File codeFile = new File(codePath);
9912        final String name = codeFile.getName();
9913        if (codeFile.isDirectory()) {
9914            return name;
9915        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9916            final int lastDot = name.lastIndexOf('.');
9917            return name.substring(0, lastDot);
9918        } else {
9919            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9920            return null;
9921        }
9922    }
9923
9924    class PackageInstalledInfo {
9925        String name;
9926        int uid;
9927        // The set of users that originally had this package installed.
9928        int[] origUsers;
9929        // The set of users that now have this package installed.
9930        int[] newUsers;
9931        PackageParser.Package pkg;
9932        int returnCode;
9933        String returnMsg;
9934        PackageRemovedInfo removedInfo;
9935
9936        public void setError(int code, String msg) {
9937            returnCode = code;
9938            returnMsg = msg;
9939            Slog.w(TAG, msg);
9940        }
9941
9942        public void setError(String msg, PackageParserException e) {
9943            returnCode = e.error;
9944            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9945            Slog.w(TAG, msg, e);
9946        }
9947
9948        public void setError(String msg, PackageManagerException e) {
9949            returnCode = e.error;
9950            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9951            Slog.w(TAG, msg, e);
9952        }
9953
9954        // In some error cases we want to convey more info back to the observer
9955        String origPackage;
9956        String origPermission;
9957    }
9958
9959    /*
9960     * Install a non-existing package.
9961     */
9962    private void installNewPackageLI(PackageParser.Package pkg,
9963            int parseFlags, int scanFlags, UserHandle user,
9964            String installerPackageName, PackageInstalledInfo res) {
9965        // Remember this for later, in case we need to rollback this install
9966        String pkgName = pkg.packageName;
9967
9968        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9969        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9970        synchronized(mPackages) {
9971            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9972                // A package with the same name is already installed, though
9973                // it has been renamed to an older name.  The package we
9974                // are trying to install should be installed as an update to
9975                // the existing one, but that has not been requested, so bail.
9976                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9977                        + " without first uninstalling package running as "
9978                        + mSettings.mRenamedPackages.get(pkgName));
9979                return;
9980            }
9981            if (mPackages.containsKey(pkgName)) {
9982                // Don't allow installation over an existing package with the same name.
9983                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9984                        + " without first uninstalling.");
9985                return;
9986            }
9987        }
9988
9989        try {
9990            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9991                    System.currentTimeMillis(), user);
9992
9993            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9994            // delete the partially installed application. the data directory will have to be
9995            // restored if it was already existing
9996            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9997                // remove package from internal structures.  Note that we want deletePackageX to
9998                // delete the package data and cache directories that it created in
9999                // scanPackageLocked, unless those directories existed before we even tried to
10000                // install.
10001                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10002                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10003                                res.removedInfo, true);
10004            }
10005
10006        } catch (PackageManagerException e) {
10007            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10008        }
10009    }
10010
10011    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10012        // Upgrade keysets are being used.  Determine if new package has a superset of the
10013        // required keys.
10014        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10015        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10016        for (int i = 0; i < upgradeKeySets.length; i++) {
10017            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10018            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10019                return true;
10020            }
10021        }
10022        return false;
10023    }
10024
10025    private void replacePackageLI(PackageParser.Package pkg,
10026            int parseFlags, int scanFlags, UserHandle user,
10027            String installerPackageName, PackageInstalledInfo res) {
10028        PackageParser.Package oldPackage;
10029        String pkgName = pkg.packageName;
10030        int[] allUsers;
10031        boolean[] perUserInstalled;
10032
10033        // First find the old package info and check signatures
10034        synchronized(mPackages) {
10035            oldPackage = mPackages.get(pkgName);
10036            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10037            PackageSetting ps = mSettings.mPackages.get(pkgName);
10038            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10039                // default to original signature matching
10040                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10041                    != PackageManager.SIGNATURE_MATCH) {
10042                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10043                            "New package has a different signature: " + pkgName);
10044                    return;
10045                }
10046            } else {
10047                if(!checkUpgradeKeySetLP(ps, pkg)) {
10048                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10049                            "New package not signed by keys specified by upgrade-keysets: "
10050                            + pkgName);
10051                    return;
10052                }
10053            }
10054
10055            // In case of rollback, remember per-user/profile install state
10056            allUsers = sUserManager.getUserIds();
10057            perUserInstalled = new boolean[allUsers.length];
10058            for (int i = 0; i < allUsers.length; i++) {
10059                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10060            }
10061        }
10062
10063        boolean sysPkg = (isSystemApp(oldPackage));
10064        if (sysPkg) {
10065            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10066                    user, allUsers, perUserInstalled, installerPackageName, res);
10067        } else {
10068            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10069                    user, allUsers, perUserInstalled, installerPackageName, res);
10070        }
10071    }
10072
10073    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10074            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10075            int[] allUsers, boolean[] perUserInstalled,
10076            String installerPackageName, PackageInstalledInfo res) {
10077        String pkgName = deletedPackage.packageName;
10078        boolean deletedPkg = true;
10079        boolean updatedSettings = false;
10080
10081        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10082                + deletedPackage);
10083        long origUpdateTime;
10084        if (pkg.mExtras != null) {
10085            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10086        } else {
10087            origUpdateTime = 0;
10088        }
10089
10090        // First delete the existing package while retaining the data directory
10091        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10092                res.removedInfo, true)) {
10093            // If the existing package wasn't successfully deleted
10094            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10095            deletedPkg = false;
10096        } else {
10097            // Successfully deleted the old package; proceed with replace.
10098
10099            // If deleted package lived in a container, give users a chance to
10100            // relinquish resources before killing.
10101            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10102                if (DEBUG_INSTALL) {
10103                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10104                }
10105                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10106                final ArrayList<String> pkgList = new ArrayList<String>(1);
10107                pkgList.add(deletedPackage.applicationInfo.packageName);
10108                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10109            }
10110
10111            deleteCodeCacheDirsLI(pkgName);
10112            try {
10113                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10114                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10115                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10116                updatedSettings = true;
10117            } catch (PackageManagerException e) {
10118                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10119            }
10120        }
10121
10122        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10123            // remove package from internal structures.  Note that we want deletePackageX to
10124            // delete the package data and cache directories that it created in
10125            // scanPackageLocked, unless those directories existed before we even tried to
10126            // install.
10127            if(updatedSettings) {
10128                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10129                deletePackageLI(
10130                        pkgName, null, true, allUsers, perUserInstalled,
10131                        PackageManager.DELETE_KEEP_DATA,
10132                                res.removedInfo, true);
10133            }
10134            // Since we failed to install the new package we need to restore the old
10135            // package that we deleted.
10136            if (deletedPkg) {
10137                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10138                File restoreFile = new File(deletedPackage.codePath);
10139                // Parse old package
10140                boolean oldOnSd = isExternal(deletedPackage);
10141                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10142                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10143                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10144                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10145                try {
10146                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10147                } catch (PackageManagerException e) {
10148                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10149                            + e.getMessage());
10150                    return;
10151                }
10152                // Restore of old package succeeded. Update permissions.
10153                // writer
10154                synchronized (mPackages) {
10155                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10156                            UPDATE_PERMISSIONS_ALL);
10157                    // can downgrade to reader
10158                    mSettings.writeLPr();
10159                }
10160                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10161            }
10162        }
10163    }
10164
10165    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10166            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10167            int[] allUsers, boolean[] perUserInstalled,
10168            String installerPackageName, PackageInstalledInfo res) {
10169        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10170                + ", old=" + deletedPackage);
10171        boolean disabledSystem = false;
10172        boolean updatedSettings = false;
10173        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10174        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10175            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10176        }
10177        String packageName = deletedPackage.packageName;
10178        if (packageName == null) {
10179            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10180                    "Attempt to delete null packageName.");
10181            return;
10182        }
10183        PackageParser.Package oldPkg;
10184        PackageSetting oldPkgSetting;
10185        // reader
10186        synchronized (mPackages) {
10187            oldPkg = mPackages.get(packageName);
10188            oldPkgSetting = mSettings.mPackages.get(packageName);
10189            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10190                    (oldPkgSetting == null)) {
10191                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10192                        "Couldn't find package:" + packageName + " information");
10193                return;
10194            }
10195        }
10196
10197        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10198
10199        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10200        res.removedInfo.removedPackage = packageName;
10201        // Remove existing system package
10202        removePackageLI(oldPkgSetting, true);
10203        // writer
10204        synchronized (mPackages) {
10205            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10206            if (!disabledSystem && deletedPackage != null) {
10207                // We didn't need to disable the .apk as a current system package,
10208                // which means we are replacing another update that is already
10209                // installed.  We need to make sure to delete the older one's .apk.
10210                res.removedInfo.args = createInstallArgsForExisting(0,
10211                        deletedPackage.applicationInfo.getCodePath(),
10212                        deletedPackage.applicationInfo.getResourcePath(),
10213                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10214                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10215            } else {
10216                res.removedInfo.args = null;
10217            }
10218        }
10219
10220        // Successfully disabled the old package. Now proceed with re-installation
10221        deleteCodeCacheDirsLI(packageName);
10222
10223        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10224        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10225
10226        PackageParser.Package newPackage = null;
10227        try {
10228            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10229            if (newPackage.mExtras != null) {
10230                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10231                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10232                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10233
10234                // is the update attempting to change shared user? that isn't going to work...
10235                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10236                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10237                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10238                            + " to " + newPkgSetting.sharedUser);
10239                    updatedSettings = true;
10240                }
10241            }
10242
10243            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10244                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10245                updatedSettings = true;
10246            }
10247
10248        } catch (PackageManagerException e) {
10249            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10250        }
10251
10252        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10253            // Re installation failed. Restore old information
10254            // Remove new pkg information
10255            if (newPackage != null) {
10256                removeInstalledPackageLI(newPackage, true);
10257            }
10258            // Add back the old system package
10259            try {
10260                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10261            } catch (PackageManagerException e) {
10262                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10263            }
10264            // Restore the old system information in Settings
10265            synchronized (mPackages) {
10266                if (disabledSystem) {
10267                    mSettings.enableSystemPackageLPw(packageName);
10268                }
10269                if (updatedSettings) {
10270                    mSettings.setInstallerPackageName(packageName,
10271                            oldPkgSetting.installerPackageName);
10272                }
10273                mSettings.writeLPr();
10274            }
10275        }
10276    }
10277
10278    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10279            int[] allUsers, boolean[] perUserInstalled,
10280            PackageInstalledInfo res) {
10281        String pkgName = newPackage.packageName;
10282        synchronized (mPackages) {
10283            //write settings. the installStatus will be incomplete at this stage.
10284            //note that the new package setting would have already been
10285            //added to mPackages. It hasn't been persisted yet.
10286            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10287            mSettings.writeLPr();
10288        }
10289
10290        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10291
10292        synchronized (mPackages) {
10293            updatePermissionsLPw(newPackage.packageName, newPackage,
10294                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10295                            ? UPDATE_PERMISSIONS_ALL : 0));
10296            // For system-bundled packages, we assume that installing an upgraded version
10297            // of the package implies that the user actually wants to run that new code,
10298            // so we enable the package.
10299            if (isSystemApp(newPackage)) {
10300                // NB: implicit assumption that system package upgrades apply to all users
10301                if (DEBUG_INSTALL) {
10302                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10303                }
10304                PackageSetting ps = mSettings.mPackages.get(pkgName);
10305                if (ps != null) {
10306                    if (res.origUsers != null) {
10307                        for (int userHandle : res.origUsers) {
10308                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10309                                    userHandle, installerPackageName);
10310                        }
10311                    }
10312                    // Also convey the prior install/uninstall state
10313                    if (allUsers != null && perUserInstalled != null) {
10314                        for (int i = 0; i < allUsers.length; i++) {
10315                            if (DEBUG_INSTALL) {
10316                                Slog.d(TAG, "    user " + allUsers[i]
10317                                        + " => " + perUserInstalled[i]);
10318                            }
10319                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10320                        }
10321                        // these install state changes will be persisted in the
10322                        // upcoming call to mSettings.writeLPr().
10323                    }
10324                }
10325            }
10326            res.name = pkgName;
10327            res.uid = newPackage.applicationInfo.uid;
10328            res.pkg = newPackage;
10329            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10330            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10331            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10332            //to update install status
10333            mSettings.writeLPr();
10334        }
10335    }
10336
10337    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10338        final int installFlags = args.installFlags;
10339        String installerPackageName = args.installerPackageName;
10340        File tmpPackageFile = new File(args.getCodePath());
10341        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10342        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10343        boolean replace = false;
10344        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10345        // Result object to be returned
10346        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10347
10348        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10349        // Retrieve PackageSettings and parse package
10350        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10351                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10352                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10353        PackageParser pp = new PackageParser();
10354        pp.setSeparateProcesses(mSeparateProcesses);
10355        pp.setDisplayMetrics(mMetrics);
10356
10357        final PackageParser.Package pkg;
10358        try {
10359            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10360        } catch (PackageParserException e) {
10361            res.setError("Failed parse during installPackageLI", e);
10362            return;
10363        }
10364
10365        // Mark that we have an install time CPU ABI override.
10366        pkg.cpuAbiOverride = args.abiOverride;
10367
10368        String pkgName = res.name = pkg.packageName;
10369        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10370            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10371                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10372                return;
10373            }
10374        }
10375
10376        try {
10377            pp.collectCertificates(pkg, parseFlags);
10378            pp.collectManifestDigest(pkg);
10379        } catch (PackageParserException e) {
10380            res.setError("Failed collect during installPackageLI", e);
10381            return;
10382        }
10383
10384        /* If the installer passed in a manifest digest, compare it now. */
10385        if (args.manifestDigest != null) {
10386            if (DEBUG_INSTALL) {
10387                final String parsedManifest = pkg.manifestDigest == null ? "null"
10388                        : pkg.manifestDigest.toString();
10389                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10390                        + parsedManifest);
10391            }
10392
10393            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10394                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10395                return;
10396            }
10397        } else if (DEBUG_INSTALL) {
10398            final String parsedManifest = pkg.manifestDigest == null
10399                    ? "null" : pkg.manifestDigest.toString();
10400            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10401        }
10402
10403        // Get rid of all references to package scan path via parser.
10404        pp = null;
10405        String oldCodePath = null;
10406        boolean systemApp = false;
10407        synchronized (mPackages) {
10408            // Check whether the newly-scanned package wants to define an already-defined perm
10409            int N = pkg.permissions.size();
10410            for (int i = N-1; i >= 0; i--) {
10411                PackageParser.Permission perm = pkg.permissions.get(i);
10412                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10413                if (bp != null) {
10414                    // If the defining package is signed with our cert, it's okay.  This
10415                    // also includes the "updating the same package" case, of course.
10416                    // "updating same package" could also involve key-rotation.
10417                    final boolean sigsOk;
10418                    if (!bp.sourcePackage.equals(pkg.packageName)
10419                            || !(bp.packageSetting instanceof PackageSetting)
10420                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10421                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10422                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10423                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10424                    } else {
10425                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10426                    }
10427                    if (!sigsOk) {
10428                        // If the owning package is the system itself, we log but allow
10429                        // install to proceed; we fail the install on all other permission
10430                        // redefinitions.
10431                        if (!bp.sourcePackage.equals("android")) {
10432                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10433                                    + pkg.packageName + " attempting to redeclare permission "
10434                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10435                            res.origPermission = perm.info.name;
10436                            res.origPackage = bp.sourcePackage;
10437                            return;
10438                        } else {
10439                            Slog.w(TAG, "Package " + pkg.packageName
10440                                    + " attempting to redeclare system permission "
10441                                    + perm.info.name + "; ignoring new declaration");
10442                            pkg.permissions.remove(i);
10443                        }
10444                    }
10445                }
10446            }
10447
10448            // Check if installing already existing package
10449            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10450                String oldName = mSettings.mRenamedPackages.get(pkgName);
10451                if (pkg.mOriginalPackages != null
10452                        && pkg.mOriginalPackages.contains(oldName)
10453                        && mPackages.containsKey(oldName)) {
10454                    // This package is derived from an original package,
10455                    // and this device has been updating from that original
10456                    // name.  We must continue using the original name, so
10457                    // rename the new package here.
10458                    pkg.setPackageName(oldName);
10459                    pkgName = pkg.packageName;
10460                    replace = true;
10461                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10462                            + oldName + " pkgName=" + pkgName);
10463                } else if (mPackages.containsKey(pkgName)) {
10464                    // This package, under its official name, already exists
10465                    // on the device; we should replace it.
10466                    replace = true;
10467                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10468                }
10469            }
10470            PackageSetting ps = mSettings.mPackages.get(pkgName);
10471            if (ps != null) {
10472                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10473                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10474                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10475                    systemApp = (ps.pkg.applicationInfo.flags &
10476                            ApplicationInfo.FLAG_SYSTEM) != 0;
10477                }
10478                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10479            }
10480        }
10481
10482        if (systemApp && onSd) {
10483            // Disable updates to system apps on sdcard
10484            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10485                    "Cannot install updates to system apps on sdcard");
10486            return;
10487        }
10488
10489        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10490            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10491            return;
10492        }
10493
10494        if (replace) {
10495            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10496                    installerPackageName, res);
10497        } else {
10498            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10499                    args.user, installerPackageName, res);
10500        }
10501        synchronized (mPackages) {
10502            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10503            if (ps != null) {
10504                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10505            }
10506        }
10507    }
10508
10509    private static boolean isForwardLocked(PackageParser.Package pkg) {
10510        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10511    }
10512
10513    private static boolean isForwardLocked(ApplicationInfo info) {
10514        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10515    }
10516
10517    private boolean isForwardLocked(PackageSetting ps) {
10518        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10519    }
10520
10521    private static boolean isMultiArch(PackageSetting ps) {
10522        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10523    }
10524
10525    private static boolean isMultiArch(ApplicationInfo info) {
10526        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10527    }
10528
10529    private static boolean isExternal(PackageParser.Package pkg) {
10530        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10531    }
10532
10533    private static boolean isExternal(PackageSetting ps) {
10534        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10535    }
10536
10537    private static boolean isExternal(ApplicationInfo info) {
10538        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10539    }
10540
10541    private static boolean isSystemApp(PackageParser.Package pkg) {
10542        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10543    }
10544
10545    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10546        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10547    }
10548
10549    private static boolean isSystemApp(ApplicationInfo info) {
10550        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10551    }
10552
10553    private static boolean isSystemApp(PackageSetting ps) {
10554        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10555    }
10556
10557    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10558        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10559    }
10560
10561    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10562        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10563    }
10564
10565    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10566        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10567    }
10568
10569    private int packageFlagsToInstallFlags(PackageSetting ps) {
10570        int installFlags = 0;
10571        if (isExternal(ps)) {
10572            installFlags |= PackageManager.INSTALL_EXTERNAL;
10573        }
10574        if (isForwardLocked(ps)) {
10575            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10576        }
10577        return installFlags;
10578    }
10579
10580    private void deleteTempPackageFiles() {
10581        final FilenameFilter filter = new FilenameFilter() {
10582            public boolean accept(File dir, String name) {
10583                return name.startsWith("vmdl") && name.endsWith(".tmp");
10584            }
10585        };
10586        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10587            file.delete();
10588        }
10589    }
10590
10591    @Override
10592    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10593            int flags) {
10594        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10595                flags);
10596    }
10597
10598    @Override
10599    public void deletePackage(final String packageName,
10600            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10601        mContext.enforceCallingOrSelfPermission(
10602                android.Manifest.permission.DELETE_PACKAGES, null);
10603        final int uid = Binder.getCallingUid();
10604        if (UserHandle.getUserId(uid) != userId) {
10605            mContext.enforceCallingPermission(
10606                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10607                    "deletePackage for user " + userId);
10608        }
10609        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10610            try {
10611                observer.onPackageDeleted(packageName,
10612                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10613            } catch (RemoteException re) {
10614            }
10615            return;
10616        }
10617
10618        boolean uninstallBlocked = false;
10619        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10620            int[] users = sUserManager.getUserIds();
10621            for (int i = 0; i < users.length; ++i) {
10622                if (getBlockUninstallForUser(packageName, users[i])) {
10623                    uninstallBlocked = true;
10624                    break;
10625                }
10626            }
10627        } else {
10628            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10629        }
10630        if (uninstallBlocked) {
10631            try {
10632                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10633                        null);
10634            } catch (RemoteException re) {
10635            }
10636            return;
10637        }
10638
10639        if (DEBUG_REMOVE) {
10640            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10641        }
10642        // Queue up an async operation since the package deletion may take a little while.
10643        mHandler.post(new Runnable() {
10644            public void run() {
10645                mHandler.removeCallbacks(this);
10646                final int returnCode = deletePackageX(packageName, userId, flags);
10647                if (observer != null) {
10648                    try {
10649                        observer.onPackageDeleted(packageName, returnCode, null);
10650                    } catch (RemoteException e) {
10651                        Log.i(TAG, "Observer no longer exists.");
10652                    } //end catch
10653                } //end if
10654            } //end run
10655        });
10656    }
10657
10658    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10659        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10660                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10661        try {
10662            if (dpm != null) {
10663                if (dpm.isDeviceOwner(packageName)) {
10664                    return true;
10665                }
10666                int[] users;
10667                if (userId == UserHandle.USER_ALL) {
10668                    users = sUserManager.getUserIds();
10669                } else {
10670                    users = new int[]{userId};
10671                }
10672                for (int i = 0; i < users.length; ++i) {
10673                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10674                        return true;
10675                    }
10676                }
10677            }
10678        } catch (RemoteException e) {
10679        }
10680        return false;
10681    }
10682
10683    /**
10684     *  This method is an internal method that could be get invoked either
10685     *  to delete an installed package or to clean up a failed installation.
10686     *  After deleting an installed package, a broadcast is sent to notify any
10687     *  listeners that the package has been installed. For cleaning up a failed
10688     *  installation, the broadcast is not necessary since the package's
10689     *  installation wouldn't have sent the initial broadcast either
10690     *  The key steps in deleting a package are
10691     *  deleting the package information in internal structures like mPackages,
10692     *  deleting the packages base directories through installd
10693     *  updating mSettings to reflect current status
10694     *  persisting settings for later use
10695     *  sending a broadcast if necessary
10696     */
10697    private int deletePackageX(String packageName, int userId, int flags) {
10698        final PackageRemovedInfo info = new PackageRemovedInfo();
10699        final boolean res;
10700
10701        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10702                ? UserHandle.ALL : new UserHandle(userId);
10703
10704        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10705            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10706            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10707        }
10708
10709        boolean removedForAllUsers = false;
10710        boolean systemUpdate = false;
10711
10712        // for the uninstall-updates case and restricted profiles, remember the per-
10713        // userhandle installed state
10714        int[] allUsers;
10715        boolean[] perUserInstalled;
10716        synchronized (mPackages) {
10717            PackageSetting ps = mSettings.mPackages.get(packageName);
10718            allUsers = sUserManager.getUserIds();
10719            perUserInstalled = new boolean[allUsers.length];
10720            for (int i = 0; i < allUsers.length; i++) {
10721                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10722            }
10723        }
10724
10725        synchronized (mInstallLock) {
10726            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10727            res = deletePackageLI(packageName, removeForUser,
10728                    true, allUsers, perUserInstalled,
10729                    flags | REMOVE_CHATTY, info, true);
10730            systemUpdate = info.isRemovedPackageSystemUpdate;
10731            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10732                removedForAllUsers = true;
10733            }
10734            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10735                    + " removedForAllUsers=" + removedForAllUsers);
10736        }
10737
10738        if (res) {
10739            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10740
10741            // If the removed package was a system update, the old system package
10742            // was re-enabled; we need to broadcast this information
10743            if (systemUpdate) {
10744                Bundle extras = new Bundle(1);
10745                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10746                        ? info.removedAppId : info.uid);
10747                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10748
10749                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10750                        extras, null, null, null);
10751                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10752                        extras, null, null, null);
10753                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10754                        null, packageName, null, null);
10755            }
10756        }
10757        // Force a gc here.
10758        Runtime.getRuntime().gc();
10759        // Delete the resources here after sending the broadcast to let
10760        // other processes clean up before deleting resources.
10761        if (info.args != null) {
10762            synchronized (mInstallLock) {
10763                info.args.doPostDeleteLI(true);
10764            }
10765        }
10766
10767        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10768    }
10769
10770    static class PackageRemovedInfo {
10771        String removedPackage;
10772        int uid = -1;
10773        int removedAppId = -1;
10774        int[] removedUsers = null;
10775        boolean isRemovedPackageSystemUpdate = false;
10776        // Clean up resources deleted packages.
10777        InstallArgs args = null;
10778
10779        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10780            Bundle extras = new Bundle(1);
10781            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10782            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10783            if (replacing) {
10784                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10785            }
10786            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10787            if (removedPackage != null) {
10788                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10789                        extras, null, null, removedUsers);
10790                if (fullRemove && !replacing) {
10791                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10792                            extras, null, null, removedUsers);
10793                }
10794            }
10795            if (removedAppId >= 0) {
10796                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10797                        removedUsers);
10798            }
10799        }
10800    }
10801
10802    /*
10803     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10804     * flag is not set, the data directory is removed as well.
10805     * make sure this flag is set for partially installed apps. If not its meaningless to
10806     * delete a partially installed application.
10807     */
10808    private void removePackageDataLI(PackageSetting ps,
10809            int[] allUserHandles, boolean[] perUserInstalled,
10810            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10811        String packageName = ps.name;
10812        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10813        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10814        // Retrieve object to delete permissions for shared user later on
10815        final PackageSetting deletedPs;
10816        // reader
10817        synchronized (mPackages) {
10818            deletedPs = mSettings.mPackages.get(packageName);
10819            if (outInfo != null) {
10820                outInfo.removedPackage = packageName;
10821                outInfo.removedUsers = deletedPs != null
10822                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10823                        : null;
10824            }
10825        }
10826        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10827            removeDataDirsLI(packageName);
10828            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10829        }
10830        // writer
10831        synchronized (mPackages) {
10832            if (deletedPs != null) {
10833                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10834                    if (outInfo != null) {
10835                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10836                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10837                    }
10838                    if (deletedPs != null) {
10839                        updatePermissionsLPw(deletedPs.name, null, 0);
10840                        if (deletedPs.sharedUser != null) {
10841                            // remove permissions associated with package
10842                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10843                        }
10844                    }
10845                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10846                }
10847                // make sure to preserve per-user disabled state if this removal was just
10848                // a downgrade of a system app to the factory package
10849                if (allUserHandles != null && perUserInstalled != null) {
10850                    if (DEBUG_REMOVE) {
10851                        Slog.d(TAG, "Propagating install state across downgrade");
10852                    }
10853                    for (int i = 0; i < allUserHandles.length; i++) {
10854                        if (DEBUG_REMOVE) {
10855                            Slog.d(TAG, "    user " + allUserHandles[i]
10856                                    + " => " + perUserInstalled[i]);
10857                        }
10858                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10859                    }
10860                }
10861            }
10862            // can downgrade to reader
10863            if (writeSettings) {
10864                // Save settings now
10865                mSettings.writeLPr();
10866            }
10867        }
10868        if (outInfo != null) {
10869            // A user ID was deleted here. Go through all users and remove it
10870            // from KeyStore.
10871            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10872        }
10873    }
10874
10875    static boolean locationIsPrivileged(File path) {
10876        try {
10877            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10878                    .getCanonicalPath();
10879            return path.getCanonicalPath().startsWith(privilegedAppDir);
10880        } catch (IOException e) {
10881            Slog.e(TAG, "Unable to access code path " + path);
10882        }
10883        return false;
10884    }
10885
10886    /*
10887     * Tries to delete system package.
10888     */
10889    private boolean deleteSystemPackageLI(PackageSetting newPs,
10890            int[] allUserHandles, boolean[] perUserInstalled,
10891            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10892        final boolean applyUserRestrictions
10893                = (allUserHandles != null) && (perUserInstalled != null);
10894        PackageSetting disabledPs = null;
10895        // Confirm if the system package has been updated
10896        // An updated system app can be deleted. This will also have to restore
10897        // the system pkg from system partition
10898        // reader
10899        synchronized (mPackages) {
10900            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10901        }
10902        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10903                + " disabledPs=" + disabledPs);
10904        if (disabledPs == null) {
10905            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10906            return false;
10907        } else if (DEBUG_REMOVE) {
10908            Slog.d(TAG, "Deleting system pkg from data partition");
10909        }
10910        if (DEBUG_REMOVE) {
10911            if (applyUserRestrictions) {
10912                Slog.d(TAG, "Remembering install states:");
10913                for (int i = 0; i < allUserHandles.length; i++) {
10914                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10915                }
10916            }
10917        }
10918        // Delete the updated package
10919        outInfo.isRemovedPackageSystemUpdate = true;
10920        if (disabledPs.versionCode < newPs.versionCode) {
10921            // Delete data for downgrades
10922            flags &= ~PackageManager.DELETE_KEEP_DATA;
10923        } else {
10924            // Preserve data by setting flag
10925            flags |= PackageManager.DELETE_KEEP_DATA;
10926        }
10927        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10928                allUserHandles, perUserInstalled, outInfo, writeSettings);
10929        if (!ret) {
10930            return false;
10931        }
10932        // writer
10933        synchronized (mPackages) {
10934            // Reinstate the old system package
10935            mSettings.enableSystemPackageLPw(newPs.name);
10936            // Remove any native libraries from the upgraded package.
10937            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10938        }
10939        // Install the system package
10940        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10941        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10942        if (locationIsPrivileged(disabledPs.codePath)) {
10943            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10944        }
10945
10946        final PackageParser.Package newPkg;
10947        try {
10948            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10949        } catch (PackageManagerException e) {
10950            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10951            return false;
10952        }
10953
10954        // writer
10955        synchronized (mPackages) {
10956            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10957            updatePermissionsLPw(newPkg.packageName, newPkg,
10958                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10959            if (applyUserRestrictions) {
10960                if (DEBUG_REMOVE) {
10961                    Slog.d(TAG, "Propagating install state across reinstall");
10962                }
10963                for (int i = 0; i < allUserHandles.length; i++) {
10964                    if (DEBUG_REMOVE) {
10965                        Slog.d(TAG, "    user " + allUserHandles[i]
10966                                + " => " + perUserInstalled[i]);
10967                    }
10968                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10969                }
10970                // Regardless of writeSettings we need to ensure that this restriction
10971                // state propagation is persisted
10972                mSettings.writeAllUsersPackageRestrictionsLPr();
10973            }
10974            // can downgrade to reader here
10975            if (writeSettings) {
10976                mSettings.writeLPr();
10977            }
10978        }
10979        return true;
10980    }
10981
10982    private boolean deleteInstalledPackageLI(PackageSetting ps,
10983            boolean deleteCodeAndResources, int flags,
10984            int[] allUserHandles, boolean[] perUserInstalled,
10985            PackageRemovedInfo outInfo, boolean writeSettings) {
10986        if (outInfo != null) {
10987            outInfo.uid = ps.appId;
10988        }
10989
10990        // Delete package data from internal structures and also remove data if flag is set
10991        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10992
10993        // Delete application code and resources
10994        if (deleteCodeAndResources && (outInfo != null)) {
10995            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10996                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10997                    getAppDexInstructionSets(ps));
10998            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10999        }
11000        return true;
11001    }
11002
11003    @Override
11004    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11005            int userId) {
11006        mContext.enforceCallingOrSelfPermission(
11007                android.Manifest.permission.DELETE_PACKAGES, null);
11008        synchronized (mPackages) {
11009            PackageSetting ps = mSettings.mPackages.get(packageName);
11010            if (ps == null) {
11011                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11012                return false;
11013            }
11014            if (!ps.getInstalled(userId)) {
11015                // Can't block uninstall for an app that is not installed or enabled.
11016                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11017                return false;
11018            }
11019            ps.setBlockUninstall(blockUninstall, userId);
11020            mSettings.writePackageRestrictionsLPr(userId);
11021        }
11022        return true;
11023    }
11024
11025    @Override
11026    public boolean getBlockUninstallForUser(String packageName, int userId) {
11027        synchronized (mPackages) {
11028            PackageSetting ps = mSettings.mPackages.get(packageName);
11029            if (ps == null) {
11030                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11031                return false;
11032            }
11033            return ps.getBlockUninstall(userId);
11034        }
11035    }
11036
11037    /*
11038     * This method handles package deletion in general
11039     */
11040    private boolean deletePackageLI(String packageName, UserHandle user,
11041            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11042            int flags, PackageRemovedInfo outInfo,
11043            boolean writeSettings) {
11044        if (packageName == null) {
11045            Slog.w(TAG, "Attempt to delete null packageName.");
11046            return false;
11047        }
11048        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11049        PackageSetting ps;
11050        boolean dataOnly = false;
11051        int removeUser = -1;
11052        int appId = -1;
11053        synchronized (mPackages) {
11054            ps = mSettings.mPackages.get(packageName);
11055            if (ps == null) {
11056                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11057                return false;
11058            }
11059            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11060                    && user.getIdentifier() != UserHandle.USER_ALL) {
11061                // The caller is asking that the package only be deleted for a single
11062                // user.  To do this, we just mark its uninstalled state and delete
11063                // its data.  If this is a system app, we only allow this to happen if
11064                // they have set the special DELETE_SYSTEM_APP which requests different
11065                // semantics than normal for uninstalling system apps.
11066                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11067                ps.setUserState(user.getIdentifier(),
11068                        COMPONENT_ENABLED_STATE_DEFAULT,
11069                        false, //installed
11070                        true,  //stopped
11071                        true,  //notLaunched
11072                        false, //hidden
11073                        null, null, null,
11074                        false // blockUninstall
11075                        );
11076                if (!isSystemApp(ps)) {
11077                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11078                        // Other user still have this package installed, so all
11079                        // we need to do is clear this user's data and save that
11080                        // it is uninstalled.
11081                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11082                        removeUser = user.getIdentifier();
11083                        appId = ps.appId;
11084                        mSettings.writePackageRestrictionsLPr(removeUser);
11085                    } else {
11086                        // We need to set it back to 'installed' so the uninstall
11087                        // broadcasts will be sent correctly.
11088                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11089                        ps.setInstalled(true, user.getIdentifier());
11090                    }
11091                } else {
11092                    // This is a system app, so we assume that the
11093                    // other users still have this package installed, so all
11094                    // we need to do is clear this user's data and save that
11095                    // it is uninstalled.
11096                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11097                    removeUser = user.getIdentifier();
11098                    appId = ps.appId;
11099                    mSettings.writePackageRestrictionsLPr(removeUser);
11100                }
11101            }
11102        }
11103
11104        if (removeUser >= 0) {
11105            // From above, we determined that we are deleting this only
11106            // for a single user.  Continue the work here.
11107            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11108            if (outInfo != null) {
11109                outInfo.removedPackage = packageName;
11110                outInfo.removedAppId = appId;
11111                outInfo.removedUsers = new int[] {removeUser};
11112            }
11113            mInstaller.clearUserData(packageName, removeUser);
11114            removeKeystoreDataIfNeeded(removeUser, appId);
11115            schedulePackageCleaning(packageName, removeUser, false);
11116            return true;
11117        }
11118
11119        if (dataOnly) {
11120            // Delete application data first
11121            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11122            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11123            return true;
11124        }
11125
11126        boolean ret = false;
11127        if (isSystemApp(ps)) {
11128            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11129            // When an updated system application is deleted we delete the existing resources as well and
11130            // fall back to existing code in system partition
11131            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11132                    flags, outInfo, writeSettings);
11133        } else {
11134            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11135            // Kill application pre-emptively especially for apps on sd.
11136            killApplication(packageName, ps.appId, "uninstall pkg");
11137            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11138                    allUserHandles, perUserInstalled,
11139                    outInfo, writeSettings);
11140        }
11141
11142        return ret;
11143    }
11144
11145    private final class ClearStorageConnection implements ServiceConnection {
11146        IMediaContainerService mContainerService;
11147
11148        @Override
11149        public void onServiceConnected(ComponentName name, IBinder service) {
11150            synchronized (this) {
11151                mContainerService = IMediaContainerService.Stub.asInterface(service);
11152                notifyAll();
11153            }
11154        }
11155
11156        @Override
11157        public void onServiceDisconnected(ComponentName name) {
11158        }
11159    }
11160
11161    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11162        final boolean mounted;
11163        if (Environment.isExternalStorageEmulated()) {
11164            mounted = true;
11165        } else {
11166            final String status = Environment.getExternalStorageState();
11167
11168            mounted = status.equals(Environment.MEDIA_MOUNTED)
11169                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11170        }
11171
11172        if (!mounted) {
11173            return;
11174        }
11175
11176        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11177        int[] users;
11178        if (userId == UserHandle.USER_ALL) {
11179            users = sUserManager.getUserIds();
11180        } else {
11181            users = new int[] { userId };
11182        }
11183        final ClearStorageConnection conn = new ClearStorageConnection();
11184        if (mContext.bindServiceAsUser(
11185                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11186            try {
11187                for (int curUser : users) {
11188                    long timeout = SystemClock.uptimeMillis() + 5000;
11189                    synchronized (conn) {
11190                        long now = SystemClock.uptimeMillis();
11191                        while (conn.mContainerService == null && now < timeout) {
11192                            try {
11193                                conn.wait(timeout - now);
11194                            } catch (InterruptedException e) {
11195                            }
11196                        }
11197                    }
11198                    if (conn.mContainerService == null) {
11199                        return;
11200                    }
11201
11202                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11203                    clearDirectory(conn.mContainerService,
11204                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11205                    if (allData) {
11206                        clearDirectory(conn.mContainerService,
11207                                userEnv.buildExternalStorageAppDataDirs(packageName));
11208                        clearDirectory(conn.mContainerService,
11209                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11210                    }
11211                }
11212            } finally {
11213                mContext.unbindService(conn);
11214            }
11215        }
11216    }
11217
11218    @Override
11219    public void clearApplicationUserData(final String packageName,
11220            final IPackageDataObserver observer, final int userId) {
11221        mContext.enforceCallingOrSelfPermission(
11222                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11223        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11224        // Queue up an async operation since the package deletion may take a little while.
11225        mHandler.post(new Runnable() {
11226            public void run() {
11227                mHandler.removeCallbacks(this);
11228                final boolean succeeded;
11229                synchronized (mInstallLock) {
11230                    succeeded = clearApplicationUserDataLI(packageName, userId);
11231                }
11232                clearExternalStorageDataSync(packageName, userId, true);
11233                if (succeeded) {
11234                    // invoke DeviceStorageMonitor's update method to clear any notifications
11235                    DeviceStorageMonitorInternal
11236                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11237                    if (dsm != null) {
11238                        dsm.checkMemory();
11239                    }
11240                }
11241                if(observer != null) {
11242                    try {
11243                        observer.onRemoveCompleted(packageName, succeeded);
11244                    } catch (RemoteException e) {
11245                        Log.i(TAG, "Observer no longer exists.");
11246                    }
11247                } //end if observer
11248            } //end run
11249        });
11250    }
11251
11252    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11253        if (packageName == null) {
11254            Slog.w(TAG, "Attempt to delete null packageName.");
11255            return false;
11256        }
11257
11258        // Try finding details about the requested package
11259        PackageParser.Package pkg;
11260        synchronized (mPackages) {
11261            pkg = mPackages.get(packageName);
11262            if (pkg == null) {
11263                final PackageSetting ps = mSettings.mPackages.get(packageName);
11264                if (ps != null) {
11265                    pkg = ps.pkg;
11266                }
11267            }
11268        }
11269
11270        if (pkg == null) {
11271            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11272        }
11273
11274        // Always delete data directories for package, even if we found no other
11275        // record of app. This helps users recover from UID mismatches without
11276        // resorting to a full data wipe.
11277        int retCode = mInstaller.clearUserData(packageName, userId);
11278        if (retCode < 0) {
11279            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11280            return false;
11281        }
11282
11283        if (pkg == null) {
11284            return false;
11285        }
11286
11287        if (pkg != null && pkg.applicationInfo != null) {
11288            final int appId = pkg.applicationInfo.uid;
11289            removeKeystoreDataIfNeeded(userId, appId);
11290        }
11291
11292        // Create a native library symlink only if we have native libraries
11293        // and if the native libraries are 32 bit libraries. We do not provide
11294        // this symlink for 64 bit libraries.
11295        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11296                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11297            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11298            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11299                Slog.w(TAG, "Failed linking native library dir");
11300                return false;
11301            }
11302        }
11303
11304        return true;
11305    }
11306
11307    /**
11308     * Remove entries from the keystore daemon. Will only remove it if the
11309     * {@code appId} is valid.
11310     */
11311    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11312        if (appId < 0) {
11313            return;
11314        }
11315
11316        final KeyStore keyStore = KeyStore.getInstance();
11317        if (keyStore != null) {
11318            if (userId == UserHandle.USER_ALL) {
11319                for (final int individual : sUserManager.getUserIds()) {
11320                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11321                }
11322            } else {
11323                keyStore.clearUid(UserHandle.getUid(userId, appId));
11324            }
11325        } else {
11326            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11327        }
11328    }
11329
11330    @Override
11331    public void deleteApplicationCacheFiles(final String packageName,
11332            final IPackageDataObserver observer) {
11333        mContext.enforceCallingOrSelfPermission(
11334                android.Manifest.permission.DELETE_CACHE_FILES, null);
11335        // Queue up an async operation since the package deletion may take a little while.
11336        final int userId = UserHandle.getCallingUserId();
11337        mHandler.post(new Runnable() {
11338            public void run() {
11339                mHandler.removeCallbacks(this);
11340                final boolean succeded;
11341                synchronized (mInstallLock) {
11342                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11343                }
11344                clearExternalStorageDataSync(packageName, userId, false);
11345                if(observer != null) {
11346                    try {
11347                        observer.onRemoveCompleted(packageName, succeded);
11348                    } catch (RemoteException e) {
11349                        Log.i(TAG, "Observer no longer exists.");
11350                    }
11351                } //end if observer
11352            } //end run
11353        });
11354    }
11355
11356    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11357        if (packageName == null) {
11358            Slog.w(TAG, "Attempt to delete null packageName.");
11359            return false;
11360        }
11361        PackageParser.Package p;
11362        synchronized (mPackages) {
11363            p = mPackages.get(packageName);
11364        }
11365        if (p == null) {
11366            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11367            return false;
11368        }
11369        final ApplicationInfo applicationInfo = p.applicationInfo;
11370        if (applicationInfo == null) {
11371            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11372            return false;
11373        }
11374        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11375        if (retCode < 0) {
11376            Slog.w(TAG, "Couldn't remove cache files for package: "
11377                       + packageName + " u" + userId);
11378            return false;
11379        }
11380        return true;
11381    }
11382
11383    @Override
11384    public void getPackageSizeInfo(final String packageName, int userHandle,
11385            final IPackageStatsObserver observer) {
11386        mContext.enforceCallingOrSelfPermission(
11387                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11388        if (packageName == null) {
11389            throw new IllegalArgumentException("Attempt to get size of null packageName");
11390        }
11391
11392        PackageStats stats = new PackageStats(packageName, userHandle);
11393
11394        /*
11395         * Queue up an async operation since the package measurement may take a
11396         * little while.
11397         */
11398        Message msg = mHandler.obtainMessage(INIT_COPY);
11399        msg.obj = new MeasureParams(stats, observer);
11400        mHandler.sendMessage(msg);
11401    }
11402
11403    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11404            PackageStats pStats) {
11405        if (packageName == null) {
11406            Slog.w(TAG, "Attempt to get size of null packageName.");
11407            return false;
11408        }
11409        PackageParser.Package p;
11410        boolean dataOnly = false;
11411        String libDirRoot = null;
11412        String asecPath = null;
11413        PackageSetting ps = null;
11414        synchronized (mPackages) {
11415            p = mPackages.get(packageName);
11416            ps = mSettings.mPackages.get(packageName);
11417            if(p == null) {
11418                dataOnly = true;
11419                if((ps == null) || (ps.pkg == null)) {
11420                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11421                    return false;
11422                }
11423                p = ps.pkg;
11424            }
11425            if (ps != null) {
11426                libDirRoot = ps.legacyNativeLibraryPathString;
11427            }
11428            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11429                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11430                if (secureContainerId != null) {
11431                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11432                }
11433            }
11434        }
11435        String publicSrcDir = null;
11436        if(!dataOnly) {
11437            final ApplicationInfo applicationInfo = p.applicationInfo;
11438            if (applicationInfo == null) {
11439                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11440                return false;
11441            }
11442            if (isForwardLocked(p)) {
11443                publicSrcDir = applicationInfo.getBaseResourcePath();
11444            }
11445        }
11446        // TODO: extend to measure size of split APKs
11447        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11448        // not just the first level.
11449        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11450        // just the primary.
11451        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11452        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11453                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11454        if (res < 0) {
11455            return false;
11456        }
11457
11458        // Fix-up for forward-locked applications in ASEC containers.
11459        if (!isExternal(p)) {
11460            pStats.codeSize += pStats.externalCodeSize;
11461            pStats.externalCodeSize = 0L;
11462        }
11463
11464        return true;
11465    }
11466
11467
11468    @Override
11469    public void addPackageToPreferred(String packageName) {
11470        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11471    }
11472
11473    @Override
11474    public void removePackageFromPreferred(String packageName) {
11475        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11476    }
11477
11478    @Override
11479    public List<PackageInfo> getPreferredPackages(int flags) {
11480        return new ArrayList<PackageInfo>();
11481    }
11482
11483    private int getUidTargetSdkVersionLockedLPr(int uid) {
11484        Object obj = mSettings.getUserIdLPr(uid);
11485        if (obj instanceof SharedUserSetting) {
11486            final SharedUserSetting sus = (SharedUserSetting) obj;
11487            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11488            final Iterator<PackageSetting> it = sus.packages.iterator();
11489            while (it.hasNext()) {
11490                final PackageSetting ps = it.next();
11491                if (ps.pkg != null) {
11492                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11493                    if (v < vers) vers = v;
11494                }
11495            }
11496            return vers;
11497        } else if (obj instanceof PackageSetting) {
11498            final PackageSetting ps = (PackageSetting) obj;
11499            if (ps.pkg != null) {
11500                return ps.pkg.applicationInfo.targetSdkVersion;
11501            }
11502        }
11503        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11504    }
11505
11506    @Override
11507    public void addPreferredActivity(IntentFilter filter, int match,
11508            ComponentName[] set, ComponentName activity, int userId) {
11509        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11510                "Adding preferred");
11511    }
11512
11513    private void addPreferredActivityInternal(IntentFilter filter, int match,
11514            ComponentName[] set, ComponentName activity, boolean always, int userId,
11515            String opname) {
11516        // writer
11517        int callingUid = Binder.getCallingUid();
11518        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11519        if (filter.countActions() == 0) {
11520            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11521            return;
11522        }
11523        synchronized (mPackages) {
11524            if (mContext.checkCallingOrSelfPermission(
11525                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11526                    != PackageManager.PERMISSION_GRANTED) {
11527                if (getUidTargetSdkVersionLockedLPr(callingUid)
11528                        < Build.VERSION_CODES.FROYO) {
11529                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11530                            + callingUid);
11531                    return;
11532                }
11533                mContext.enforceCallingOrSelfPermission(
11534                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11535            }
11536
11537            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11538            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11539                    + userId + ":");
11540            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11541            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11542            mSettings.writePackageRestrictionsLPr(userId);
11543        }
11544    }
11545
11546    @Override
11547    public void replacePreferredActivity(IntentFilter filter, int match,
11548            ComponentName[] set, ComponentName activity, int userId) {
11549        if (filter.countActions() != 1) {
11550            throw new IllegalArgumentException(
11551                    "replacePreferredActivity expects filter to have only 1 action.");
11552        }
11553        if (filter.countDataAuthorities() != 0
11554                || filter.countDataPaths() != 0
11555                || filter.countDataSchemes() > 1
11556                || filter.countDataTypes() != 0) {
11557            throw new IllegalArgumentException(
11558                    "replacePreferredActivity expects filter to have no data authorities, " +
11559                    "paths, or types; and at most one scheme.");
11560        }
11561
11562        final int callingUid = Binder.getCallingUid();
11563        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11564        synchronized (mPackages) {
11565            if (mContext.checkCallingOrSelfPermission(
11566                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11567                    != PackageManager.PERMISSION_GRANTED) {
11568                if (getUidTargetSdkVersionLockedLPr(callingUid)
11569                        < Build.VERSION_CODES.FROYO) {
11570                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11571                            + Binder.getCallingUid());
11572                    return;
11573                }
11574                mContext.enforceCallingOrSelfPermission(
11575                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11576            }
11577
11578            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11579            if (pir != null) {
11580                // Get all of the existing entries that exactly match this filter.
11581                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11582                if (existing != null && existing.size() == 1) {
11583                    PreferredActivity cur = existing.get(0);
11584                    if (DEBUG_PREFERRED) {
11585                        Slog.i(TAG, "Checking replace of preferred:");
11586                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11587                        if (!cur.mPref.mAlways) {
11588                            Slog.i(TAG, "  -- CUR; not mAlways!");
11589                        } else {
11590                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11591                            Slog.i(TAG, "  -- CUR: mSet="
11592                                    + Arrays.toString(cur.mPref.mSetComponents));
11593                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11594                            Slog.i(TAG, "  -- NEW: mMatch="
11595                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11596                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11597                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11598                        }
11599                    }
11600                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11601                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11602                            && cur.mPref.sameSet(set)) {
11603                        // Setting the preferred activity to what it happens to be already
11604                        if (DEBUG_PREFERRED) {
11605                            Slog.i(TAG, "Replacing with same preferred activity "
11606                                    + cur.mPref.mShortComponent + " for user "
11607                                    + userId + ":");
11608                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11609                        }
11610                        return;
11611                    }
11612                }
11613
11614                if (existing != null) {
11615                    if (DEBUG_PREFERRED) {
11616                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11617                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11618                    }
11619                    for (int i = 0; i < existing.size(); i++) {
11620                        PreferredActivity pa = existing.get(i);
11621                        if (DEBUG_PREFERRED) {
11622                            Slog.i(TAG, "Removing existing preferred activity "
11623                                    + pa.mPref.mComponent + ":");
11624                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11625                        }
11626                        pir.removeFilter(pa);
11627                    }
11628                }
11629            }
11630            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11631                    "Replacing preferred");
11632        }
11633    }
11634
11635    @Override
11636    public void clearPackagePreferredActivities(String packageName) {
11637        final int uid = Binder.getCallingUid();
11638        // writer
11639        synchronized (mPackages) {
11640            PackageParser.Package pkg = mPackages.get(packageName);
11641            if (pkg == null || pkg.applicationInfo.uid != uid) {
11642                if (mContext.checkCallingOrSelfPermission(
11643                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11644                        != PackageManager.PERMISSION_GRANTED) {
11645                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11646                            < Build.VERSION_CODES.FROYO) {
11647                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11648                                + Binder.getCallingUid());
11649                        return;
11650                    }
11651                    mContext.enforceCallingOrSelfPermission(
11652                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11653                }
11654            }
11655
11656            int user = UserHandle.getCallingUserId();
11657            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11658                mSettings.writePackageRestrictionsLPr(user);
11659                scheduleWriteSettingsLocked();
11660            }
11661        }
11662    }
11663
11664    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11665    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11666        ArrayList<PreferredActivity> removed = null;
11667        boolean changed = false;
11668        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11669            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11670            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11671            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11672                continue;
11673            }
11674            Iterator<PreferredActivity> it = pir.filterIterator();
11675            while (it.hasNext()) {
11676                PreferredActivity pa = it.next();
11677                // Mark entry for removal only if it matches the package name
11678                // and the entry is of type "always".
11679                if (packageName == null ||
11680                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11681                                && pa.mPref.mAlways)) {
11682                    if (removed == null) {
11683                        removed = new ArrayList<PreferredActivity>();
11684                    }
11685                    removed.add(pa);
11686                }
11687            }
11688            if (removed != null) {
11689                for (int j=0; j<removed.size(); j++) {
11690                    PreferredActivity pa = removed.get(j);
11691                    pir.removeFilter(pa);
11692                }
11693                changed = true;
11694            }
11695        }
11696        return changed;
11697    }
11698
11699    @Override
11700    public void resetPreferredActivities(int userId) {
11701        /* TODO: Actually use userId. Why is it being passed in? */
11702        mContext.enforceCallingOrSelfPermission(
11703                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11704        // writer
11705        synchronized (mPackages) {
11706            int user = UserHandle.getCallingUserId();
11707            clearPackagePreferredActivitiesLPw(null, user);
11708            mSettings.readDefaultPreferredAppsLPw(this, user);
11709            mSettings.writePackageRestrictionsLPr(user);
11710            scheduleWriteSettingsLocked();
11711        }
11712    }
11713
11714    @Override
11715    public int getPreferredActivities(List<IntentFilter> outFilters,
11716            List<ComponentName> outActivities, String packageName) {
11717
11718        int num = 0;
11719        final int userId = UserHandle.getCallingUserId();
11720        // reader
11721        synchronized (mPackages) {
11722            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11723            if (pir != null) {
11724                final Iterator<PreferredActivity> it = pir.filterIterator();
11725                while (it.hasNext()) {
11726                    final PreferredActivity pa = it.next();
11727                    if (packageName == null
11728                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11729                                    && pa.mPref.mAlways)) {
11730                        if (outFilters != null) {
11731                            outFilters.add(new IntentFilter(pa));
11732                        }
11733                        if (outActivities != null) {
11734                            outActivities.add(pa.mPref.mComponent);
11735                        }
11736                    }
11737                }
11738            }
11739        }
11740
11741        return num;
11742    }
11743
11744    @Override
11745    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11746            int userId) {
11747        int callingUid = Binder.getCallingUid();
11748        if (callingUid != Process.SYSTEM_UID) {
11749            throw new SecurityException(
11750                    "addPersistentPreferredActivity can only be run by the system");
11751        }
11752        if (filter.countActions() == 0) {
11753            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11754            return;
11755        }
11756        synchronized (mPackages) {
11757            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11758                    " :");
11759            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11760            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11761                    new PersistentPreferredActivity(filter, activity));
11762            mSettings.writePackageRestrictionsLPr(userId);
11763        }
11764    }
11765
11766    @Override
11767    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11768        int callingUid = Binder.getCallingUid();
11769        if (callingUid != Process.SYSTEM_UID) {
11770            throw new SecurityException(
11771                    "clearPackagePersistentPreferredActivities can only be run by the system");
11772        }
11773        ArrayList<PersistentPreferredActivity> removed = null;
11774        boolean changed = false;
11775        synchronized (mPackages) {
11776            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11777                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11778                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11779                        .valueAt(i);
11780                if (userId != thisUserId) {
11781                    continue;
11782                }
11783                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11784                while (it.hasNext()) {
11785                    PersistentPreferredActivity ppa = it.next();
11786                    // Mark entry for removal only if it matches the package name.
11787                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11788                        if (removed == null) {
11789                            removed = new ArrayList<PersistentPreferredActivity>();
11790                        }
11791                        removed.add(ppa);
11792                    }
11793                }
11794                if (removed != null) {
11795                    for (int j=0; j<removed.size(); j++) {
11796                        PersistentPreferredActivity ppa = removed.get(j);
11797                        ppir.removeFilter(ppa);
11798                    }
11799                    changed = true;
11800                }
11801            }
11802
11803            if (changed) {
11804                mSettings.writePackageRestrictionsLPr(userId);
11805            }
11806        }
11807    }
11808
11809    @Override
11810    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11811            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11812        mContext.enforceCallingOrSelfPermission(
11813                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11814        int callingUid = Binder.getCallingUid();
11815        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11816        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11817        if (intentFilter.countActions() == 0) {
11818            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11819            return;
11820        }
11821        synchronized (mPackages) {
11822            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11823                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11824            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11825            mSettings.writePackageRestrictionsLPr(sourceUserId);
11826        }
11827    }
11828
11829    @Override
11830    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11831            int ownerUserId) {
11832        mContext.enforceCallingOrSelfPermission(
11833                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11834        int callingUid = Binder.getCallingUid();
11835        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11836        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11837        int callingUserId = UserHandle.getUserId(callingUid);
11838        synchronized (mPackages) {
11839            CrossProfileIntentResolver resolver =
11840                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11841            HashSet<CrossProfileIntentFilter> set =
11842                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11843            for (CrossProfileIntentFilter filter : set) {
11844                if (filter.getOwnerPackage().equals(ownerPackage)
11845                        && filter.getOwnerUserId() == callingUserId) {
11846                    resolver.removeFilter(filter);
11847                }
11848            }
11849            mSettings.writePackageRestrictionsLPr(sourceUserId);
11850        }
11851    }
11852
11853    // Enforcing that callingUid is owning pkg on userId
11854    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11855        // The system owns everything.
11856        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11857            return;
11858        }
11859        int callingUserId = UserHandle.getUserId(callingUid);
11860        if (callingUserId != userId) {
11861            throw new SecurityException("calling uid " + callingUid
11862                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11863                    + callingUserId);
11864        }
11865        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11866        if (pi == null) {
11867            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11868                    + callingUserId);
11869        }
11870        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11871            throw new SecurityException("Calling uid " + callingUid
11872                    + " does not own package " + pkg);
11873        }
11874    }
11875
11876    @Override
11877    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11878        Intent intent = new Intent(Intent.ACTION_MAIN);
11879        intent.addCategory(Intent.CATEGORY_HOME);
11880
11881        final int callingUserId = UserHandle.getCallingUserId();
11882        List<ResolveInfo> list = queryIntentActivities(intent, null,
11883                PackageManager.GET_META_DATA, callingUserId);
11884        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11885                true, false, false, callingUserId);
11886
11887        allHomeCandidates.clear();
11888        if (list != null) {
11889            for (ResolveInfo ri : list) {
11890                allHomeCandidates.add(ri);
11891            }
11892        }
11893        return (preferred == null || preferred.activityInfo == null)
11894                ? null
11895                : new ComponentName(preferred.activityInfo.packageName,
11896                        preferred.activityInfo.name);
11897    }
11898
11899    @Override
11900    public void setApplicationEnabledSetting(String appPackageName,
11901            int newState, int flags, int userId, String callingPackage) {
11902        if (!sUserManager.exists(userId)) return;
11903        if (callingPackage == null) {
11904            callingPackage = Integer.toString(Binder.getCallingUid());
11905        }
11906        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11907    }
11908
11909    @Override
11910    public void setComponentEnabledSetting(ComponentName componentName,
11911            int newState, int flags, int userId) {
11912        if (!sUserManager.exists(userId)) return;
11913        setEnabledSetting(componentName.getPackageName(),
11914                componentName.getClassName(), newState, flags, userId, null);
11915    }
11916
11917    private void setEnabledSetting(final String packageName, String className, int newState,
11918            final int flags, int userId, String callingPackage) {
11919        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11920              || newState == COMPONENT_ENABLED_STATE_ENABLED
11921              || newState == COMPONENT_ENABLED_STATE_DISABLED
11922              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11923              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11924            throw new IllegalArgumentException("Invalid new component state: "
11925                    + newState);
11926        }
11927        PackageSetting pkgSetting;
11928        final int uid = Binder.getCallingUid();
11929        final int permission = mContext.checkCallingOrSelfPermission(
11930                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11931        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11932        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11933        boolean sendNow = false;
11934        boolean isApp = (className == null);
11935        String componentName = isApp ? packageName : className;
11936        int packageUid = -1;
11937        ArrayList<String> components;
11938
11939        // writer
11940        synchronized (mPackages) {
11941            pkgSetting = mSettings.mPackages.get(packageName);
11942            if (pkgSetting == null) {
11943                if (className == null) {
11944                    throw new IllegalArgumentException(
11945                            "Unknown package: " + packageName);
11946                }
11947                throw new IllegalArgumentException(
11948                        "Unknown component: " + packageName
11949                        + "/" + className);
11950            }
11951            // Allow root and verify that userId is not being specified by a different user
11952            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11953                throw new SecurityException(
11954                        "Permission Denial: attempt to change component state from pid="
11955                        + Binder.getCallingPid()
11956                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11957            }
11958            if (className == null) {
11959                // We're dealing with an application/package level state change
11960                if (pkgSetting.getEnabled(userId) == newState) {
11961                    // Nothing to do
11962                    return;
11963                }
11964                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11965                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11966                    // Don't care about who enables an app.
11967                    callingPackage = null;
11968                }
11969                pkgSetting.setEnabled(newState, userId, callingPackage);
11970                // pkgSetting.pkg.mSetEnabled = newState;
11971            } else {
11972                // We're dealing with a component level state change
11973                // First, verify that this is a valid class name.
11974                PackageParser.Package pkg = pkgSetting.pkg;
11975                if (pkg == null || !pkg.hasComponentClassName(className)) {
11976                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11977                        throw new IllegalArgumentException("Component class " + className
11978                                + " does not exist in " + packageName);
11979                    } else {
11980                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11981                                + className + " does not exist in " + packageName);
11982                    }
11983                }
11984                switch (newState) {
11985                case COMPONENT_ENABLED_STATE_ENABLED:
11986                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11987                        return;
11988                    }
11989                    break;
11990                case COMPONENT_ENABLED_STATE_DISABLED:
11991                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11992                        return;
11993                    }
11994                    break;
11995                case COMPONENT_ENABLED_STATE_DEFAULT:
11996                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11997                        return;
11998                    }
11999                    break;
12000                default:
12001                    Slog.e(TAG, "Invalid new component state: " + newState);
12002                    return;
12003                }
12004            }
12005            mSettings.writePackageRestrictionsLPr(userId);
12006            components = mPendingBroadcasts.get(userId, packageName);
12007            final boolean newPackage = components == null;
12008            if (newPackage) {
12009                components = new ArrayList<String>();
12010            }
12011            if (!components.contains(componentName)) {
12012                components.add(componentName);
12013            }
12014            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12015                sendNow = true;
12016                // Purge entry from pending broadcast list if another one exists already
12017                // since we are sending one right away.
12018                mPendingBroadcasts.remove(userId, packageName);
12019            } else {
12020                if (newPackage) {
12021                    mPendingBroadcasts.put(userId, packageName, components);
12022                }
12023                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12024                    // Schedule a message
12025                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12026                }
12027            }
12028        }
12029
12030        long callingId = Binder.clearCallingIdentity();
12031        try {
12032            if (sendNow) {
12033                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12034                sendPackageChangedBroadcast(packageName,
12035                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12036            }
12037        } finally {
12038            Binder.restoreCallingIdentity(callingId);
12039        }
12040    }
12041
12042    private void sendPackageChangedBroadcast(String packageName,
12043            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12044        if (DEBUG_INSTALL)
12045            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12046                    + componentNames);
12047        Bundle extras = new Bundle(4);
12048        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12049        String nameList[] = new String[componentNames.size()];
12050        componentNames.toArray(nameList);
12051        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12052        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12053        extras.putInt(Intent.EXTRA_UID, packageUid);
12054        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12055                new int[] {UserHandle.getUserId(packageUid)});
12056    }
12057
12058    @Override
12059    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12060        if (!sUserManager.exists(userId)) return;
12061        final int uid = Binder.getCallingUid();
12062        final int permission = mContext.checkCallingOrSelfPermission(
12063                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12064        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12065        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12066        // writer
12067        synchronized (mPackages) {
12068            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12069                    uid, userId)) {
12070                scheduleWritePackageRestrictionsLocked(userId);
12071            }
12072        }
12073    }
12074
12075    @Override
12076    public String getInstallerPackageName(String packageName) {
12077        // reader
12078        synchronized (mPackages) {
12079            return mSettings.getInstallerPackageNameLPr(packageName);
12080        }
12081    }
12082
12083    @Override
12084    public int getApplicationEnabledSetting(String packageName, int userId) {
12085        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12086        int uid = Binder.getCallingUid();
12087        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12088        // reader
12089        synchronized (mPackages) {
12090            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12091        }
12092    }
12093
12094    @Override
12095    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12096        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12097        int uid = Binder.getCallingUid();
12098        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12099        // reader
12100        synchronized (mPackages) {
12101            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12102        }
12103    }
12104
12105    @Override
12106    public void enterSafeMode() {
12107        enforceSystemOrRoot("Only the system can request entering safe mode");
12108
12109        if (!mSystemReady) {
12110            mSafeMode = true;
12111        }
12112    }
12113
12114    @Override
12115    public void systemReady() {
12116        mSystemReady = true;
12117
12118        // Read the compatibilty setting when the system is ready.
12119        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12120                mContext.getContentResolver(),
12121                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12122        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12123        if (DEBUG_SETTINGS) {
12124            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12125        }
12126
12127        synchronized (mPackages) {
12128            // Verify that all of the preferred activity components actually
12129            // exist.  It is possible for applications to be updated and at
12130            // that point remove a previously declared activity component that
12131            // had been set as a preferred activity.  We try to clean this up
12132            // the next time we encounter that preferred activity, but it is
12133            // possible for the user flow to never be able to return to that
12134            // situation so here we do a sanity check to make sure we haven't
12135            // left any junk around.
12136            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12137            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12138                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12139                removed.clear();
12140                for (PreferredActivity pa : pir.filterSet()) {
12141                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12142                        removed.add(pa);
12143                    }
12144                }
12145                if (removed.size() > 0) {
12146                    for (int r=0; r<removed.size(); r++) {
12147                        PreferredActivity pa = removed.get(r);
12148                        Slog.w(TAG, "Removing dangling preferred activity: "
12149                                + pa.mPref.mComponent);
12150                        pir.removeFilter(pa);
12151                    }
12152                    mSettings.writePackageRestrictionsLPr(
12153                            mSettings.mPreferredActivities.keyAt(i));
12154                }
12155            }
12156        }
12157        sUserManager.systemReady();
12158
12159        // Kick off any messages waiting for system ready
12160        if (mPostSystemReadyMessages != null) {
12161            for (Message msg : mPostSystemReadyMessages) {
12162                msg.sendToTarget();
12163            }
12164            mPostSystemReadyMessages = null;
12165        }
12166    }
12167
12168    @Override
12169    public boolean isSafeMode() {
12170        return mSafeMode;
12171    }
12172
12173    @Override
12174    public boolean hasSystemUidErrors() {
12175        return mHasSystemUidErrors;
12176    }
12177
12178    static String arrayToString(int[] array) {
12179        StringBuffer buf = new StringBuffer(128);
12180        buf.append('[');
12181        if (array != null) {
12182            for (int i=0; i<array.length; i++) {
12183                if (i > 0) buf.append(", ");
12184                buf.append(array[i]);
12185            }
12186        }
12187        buf.append(']');
12188        return buf.toString();
12189    }
12190
12191    static class DumpState {
12192        public static final int DUMP_LIBS = 1 << 0;
12193        public static final int DUMP_FEATURES = 1 << 1;
12194        public static final int DUMP_RESOLVERS = 1 << 2;
12195        public static final int DUMP_PERMISSIONS = 1 << 3;
12196        public static final int DUMP_PACKAGES = 1 << 4;
12197        public static final int DUMP_SHARED_USERS = 1 << 5;
12198        public static final int DUMP_MESSAGES = 1 << 6;
12199        public static final int DUMP_PROVIDERS = 1 << 7;
12200        public static final int DUMP_VERIFIERS = 1 << 8;
12201        public static final int DUMP_PREFERRED = 1 << 9;
12202        public static final int DUMP_PREFERRED_XML = 1 << 10;
12203        public static final int DUMP_KEYSETS = 1 << 11;
12204        public static final int DUMP_VERSION = 1 << 12;
12205        public static final int DUMP_INSTALLS = 1 << 13;
12206
12207        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12208
12209        private int mTypes;
12210
12211        private int mOptions;
12212
12213        private boolean mTitlePrinted;
12214
12215        private SharedUserSetting mSharedUser;
12216
12217        public boolean isDumping(int type) {
12218            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12219                return true;
12220            }
12221
12222            return (mTypes & type) != 0;
12223        }
12224
12225        public void setDump(int type) {
12226            mTypes |= type;
12227        }
12228
12229        public boolean isOptionEnabled(int option) {
12230            return (mOptions & option) != 0;
12231        }
12232
12233        public void setOptionEnabled(int option) {
12234            mOptions |= option;
12235        }
12236
12237        public boolean onTitlePrinted() {
12238            final boolean printed = mTitlePrinted;
12239            mTitlePrinted = true;
12240            return printed;
12241        }
12242
12243        public boolean getTitlePrinted() {
12244            return mTitlePrinted;
12245        }
12246
12247        public void setTitlePrinted(boolean enabled) {
12248            mTitlePrinted = enabled;
12249        }
12250
12251        public SharedUserSetting getSharedUser() {
12252            return mSharedUser;
12253        }
12254
12255        public void setSharedUser(SharedUserSetting user) {
12256            mSharedUser = user;
12257        }
12258    }
12259
12260    @Override
12261    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12262        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12263                != PackageManager.PERMISSION_GRANTED) {
12264            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12265                    + Binder.getCallingPid()
12266                    + ", uid=" + Binder.getCallingUid()
12267                    + " without permission "
12268                    + android.Manifest.permission.DUMP);
12269            return;
12270        }
12271
12272        DumpState dumpState = new DumpState();
12273        boolean fullPreferred = false;
12274        boolean checkin = false;
12275
12276        String packageName = null;
12277
12278        int opti = 0;
12279        while (opti < args.length) {
12280            String opt = args[opti];
12281            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12282                break;
12283            }
12284            opti++;
12285
12286            if ("-a".equals(opt)) {
12287                // Right now we only know how to print all.
12288            } else if ("-h".equals(opt)) {
12289                pw.println("Package manager dump options:");
12290                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12291                pw.println("    --checkin: dump for a checkin");
12292                pw.println("    -f: print details of intent filters");
12293                pw.println("    -h: print this help");
12294                pw.println("  cmd may be one of:");
12295                pw.println("    l[ibraries]: list known shared libraries");
12296                pw.println("    f[ibraries]: list device features");
12297                pw.println("    k[eysets]: print known keysets");
12298                pw.println("    r[esolvers]: dump intent resolvers");
12299                pw.println("    perm[issions]: dump permissions");
12300                pw.println("    pref[erred]: print preferred package settings");
12301                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12302                pw.println("    prov[iders]: dump content providers");
12303                pw.println("    p[ackages]: dump installed packages");
12304                pw.println("    s[hared-users]: dump shared user IDs");
12305                pw.println("    m[essages]: print collected runtime messages");
12306                pw.println("    v[erifiers]: print package verifier info");
12307                pw.println("    version: print database version info");
12308                pw.println("    write: write current settings now");
12309                pw.println("    <package.name>: info about given package");
12310                pw.println("    installs: details about install sessions");
12311                return;
12312            } else if ("--checkin".equals(opt)) {
12313                checkin = true;
12314            } else if ("-f".equals(opt)) {
12315                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12316            } else {
12317                pw.println("Unknown argument: " + opt + "; use -h for help");
12318            }
12319        }
12320
12321        // Is the caller requesting to dump a particular piece of data?
12322        if (opti < args.length) {
12323            String cmd = args[opti];
12324            opti++;
12325            // Is this a package name?
12326            if ("android".equals(cmd) || cmd.contains(".")) {
12327                packageName = cmd;
12328                // When dumping a single package, we always dump all of its
12329                // filter information since the amount of data will be reasonable.
12330                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12331            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12332                dumpState.setDump(DumpState.DUMP_LIBS);
12333            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12334                dumpState.setDump(DumpState.DUMP_FEATURES);
12335            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12336                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12337            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12338                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12339            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12340                dumpState.setDump(DumpState.DUMP_PREFERRED);
12341            } else if ("preferred-xml".equals(cmd)) {
12342                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12343                if (opti < args.length && "--full".equals(args[opti])) {
12344                    fullPreferred = true;
12345                    opti++;
12346                }
12347            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12348                dumpState.setDump(DumpState.DUMP_PACKAGES);
12349            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12350                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12351            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12352                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12353            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12354                dumpState.setDump(DumpState.DUMP_MESSAGES);
12355            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12356                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12357            } else if ("version".equals(cmd)) {
12358                dumpState.setDump(DumpState.DUMP_VERSION);
12359            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12360                dumpState.setDump(DumpState.DUMP_KEYSETS);
12361            } else if ("installs".equals(cmd)) {
12362                dumpState.setDump(DumpState.DUMP_INSTALLS);
12363            } else if ("write".equals(cmd)) {
12364                synchronized (mPackages) {
12365                    mSettings.writeLPr();
12366                    pw.println("Settings written.");
12367                    return;
12368                }
12369            }
12370        }
12371
12372        if (checkin) {
12373            pw.println("vers,1");
12374        }
12375
12376        // reader
12377        synchronized (mPackages) {
12378            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12379                if (!checkin) {
12380                    if (dumpState.onTitlePrinted())
12381                        pw.println();
12382                    pw.println("Database versions:");
12383                    pw.print("  SDK Version:");
12384                    pw.print(" internal=");
12385                    pw.print(mSettings.mInternalSdkPlatform);
12386                    pw.print(" external=");
12387                    pw.println(mSettings.mExternalSdkPlatform);
12388                    pw.print("  DB Version:");
12389                    pw.print(" internal=");
12390                    pw.print(mSettings.mInternalDatabaseVersion);
12391                    pw.print(" external=");
12392                    pw.println(mSettings.mExternalDatabaseVersion);
12393                }
12394            }
12395
12396            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12397                if (!checkin) {
12398                    if (dumpState.onTitlePrinted())
12399                        pw.println();
12400                    pw.println("Verifiers:");
12401                    pw.print("  Required: ");
12402                    pw.print(mRequiredVerifierPackage);
12403                    pw.print(" (uid=");
12404                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12405                    pw.println(")");
12406                } else if (mRequiredVerifierPackage != null) {
12407                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12408                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12409                }
12410            }
12411
12412            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12413                boolean printedHeader = false;
12414                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12415                while (it.hasNext()) {
12416                    String name = it.next();
12417                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12418                    if (!checkin) {
12419                        if (!printedHeader) {
12420                            if (dumpState.onTitlePrinted())
12421                                pw.println();
12422                            pw.println("Libraries:");
12423                            printedHeader = true;
12424                        }
12425                        pw.print("  ");
12426                    } else {
12427                        pw.print("lib,");
12428                    }
12429                    pw.print(name);
12430                    if (!checkin) {
12431                        pw.print(" -> ");
12432                    }
12433                    if (ent.path != null) {
12434                        if (!checkin) {
12435                            pw.print("(jar) ");
12436                            pw.print(ent.path);
12437                        } else {
12438                            pw.print(",jar,");
12439                            pw.print(ent.path);
12440                        }
12441                    } else {
12442                        if (!checkin) {
12443                            pw.print("(apk) ");
12444                            pw.print(ent.apk);
12445                        } else {
12446                            pw.print(",apk,");
12447                            pw.print(ent.apk);
12448                        }
12449                    }
12450                    pw.println();
12451                }
12452            }
12453
12454            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12455                if (dumpState.onTitlePrinted())
12456                    pw.println();
12457                if (!checkin) {
12458                    pw.println("Features:");
12459                }
12460                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12461                while (it.hasNext()) {
12462                    String name = it.next();
12463                    if (!checkin) {
12464                        pw.print("  ");
12465                    } else {
12466                        pw.print("feat,");
12467                    }
12468                    pw.println(name);
12469                }
12470            }
12471
12472            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12473                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12474                        : "Activity Resolver Table:", "  ", packageName,
12475                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12476                    dumpState.setTitlePrinted(true);
12477                }
12478                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12479                        : "Receiver Resolver Table:", "  ", packageName,
12480                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12481                    dumpState.setTitlePrinted(true);
12482                }
12483                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12484                        : "Service Resolver Table:", "  ", packageName,
12485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12486                    dumpState.setTitlePrinted(true);
12487                }
12488                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12489                        : "Provider Resolver Table:", "  ", packageName,
12490                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12491                    dumpState.setTitlePrinted(true);
12492                }
12493            }
12494
12495            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12496                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12497                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12498                    int user = mSettings.mPreferredActivities.keyAt(i);
12499                    if (pir.dump(pw,
12500                            dumpState.getTitlePrinted()
12501                                ? "\nPreferred Activities User " + user + ":"
12502                                : "Preferred Activities User " + user + ":", "  ",
12503                            packageName, true)) {
12504                        dumpState.setTitlePrinted(true);
12505                    }
12506                }
12507            }
12508
12509            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12510                pw.flush();
12511                FileOutputStream fout = new FileOutputStream(fd);
12512                BufferedOutputStream str = new BufferedOutputStream(fout);
12513                XmlSerializer serializer = new FastXmlSerializer();
12514                try {
12515                    serializer.setOutput(str, "utf-8");
12516                    serializer.startDocument(null, true);
12517                    serializer.setFeature(
12518                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12519                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12520                    serializer.endDocument();
12521                    serializer.flush();
12522                } catch (IllegalArgumentException e) {
12523                    pw.println("Failed writing: " + e);
12524                } catch (IllegalStateException e) {
12525                    pw.println("Failed writing: " + e);
12526                } catch (IOException e) {
12527                    pw.println("Failed writing: " + e);
12528                }
12529            }
12530
12531            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12532                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12533                if (packageName == null) {
12534                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12535                        if (iperm == 0) {
12536                            if (dumpState.onTitlePrinted())
12537                                pw.println();
12538                            pw.println("AppOp Permissions:");
12539                        }
12540                        pw.print("  AppOp Permission ");
12541                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12542                        pw.println(":");
12543                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12544                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12545                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12546                        }
12547                    }
12548                }
12549            }
12550
12551            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12552                boolean printedSomething = false;
12553                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12554                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12555                        continue;
12556                    }
12557                    if (!printedSomething) {
12558                        if (dumpState.onTitlePrinted())
12559                            pw.println();
12560                        pw.println("Registered ContentProviders:");
12561                        printedSomething = true;
12562                    }
12563                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12564                    pw.print("    "); pw.println(p.toString());
12565                }
12566                printedSomething = false;
12567                for (Map.Entry<String, PackageParser.Provider> entry :
12568                        mProvidersByAuthority.entrySet()) {
12569                    PackageParser.Provider p = entry.getValue();
12570                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12571                        continue;
12572                    }
12573                    if (!printedSomething) {
12574                        if (dumpState.onTitlePrinted())
12575                            pw.println();
12576                        pw.println("ContentProvider Authorities:");
12577                        printedSomething = true;
12578                    }
12579                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12580                    pw.print("    "); pw.println(p.toString());
12581                    if (p.info != null && p.info.applicationInfo != null) {
12582                        final String appInfo = p.info.applicationInfo.toString();
12583                        pw.print("      applicationInfo="); pw.println(appInfo);
12584                    }
12585                }
12586            }
12587
12588            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12589                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12590            }
12591
12592            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12593                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12594            }
12595
12596            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12597                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12598            }
12599
12600            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12601                // XXX should handle packageName != null by dumping only install data that
12602                // the given package is involved with.
12603                if (dumpState.onTitlePrinted()) pw.println();
12604                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12605            }
12606
12607            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12608                if (dumpState.onTitlePrinted()) pw.println();
12609                mSettings.dumpReadMessagesLPr(pw, dumpState);
12610
12611                pw.println();
12612                pw.println("Package warning messages:");
12613                final File fname = getSettingsProblemFile();
12614                FileInputStream in = null;
12615                try {
12616                    in = new FileInputStream(fname);
12617                    final int avail = in.available();
12618                    final byte[] data = new byte[avail];
12619                    in.read(data);
12620                    pw.print(new String(data));
12621                } catch (FileNotFoundException e) {
12622                } catch (IOException e) {
12623                } finally {
12624                    if (in != null) {
12625                        try {
12626                            in.close();
12627                        } catch (IOException e) {
12628                        }
12629                    }
12630                }
12631            }
12632
12633            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12634                BufferedReader in = null;
12635                String line = null;
12636                try {
12637                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12638                    while ((line = in.readLine()) != null) {
12639                        pw.print("msg,");
12640                        pw.println(line);
12641                    }
12642                } catch (IOException ignored) {
12643                } finally {
12644                    IoUtils.closeQuietly(in);
12645                }
12646            }
12647        }
12648    }
12649
12650    // ------- apps on sdcard specific code -------
12651    static final boolean DEBUG_SD_INSTALL = false;
12652
12653    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12654
12655    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12656
12657    private boolean mMediaMounted = false;
12658
12659    static String getEncryptKey() {
12660        try {
12661            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12662                    SD_ENCRYPTION_KEYSTORE_NAME);
12663            if (sdEncKey == null) {
12664                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12665                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12666                if (sdEncKey == null) {
12667                    Slog.e(TAG, "Failed to create encryption keys");
12668                    return null;
12669                }
12670            }
12671            return sdEncKey;
12672        } catch (NoSuchAlgorithmException nsae) {
12673            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12674            return null;
12675        } catch (IOException ioe) {
12676            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12677            return null;
12678        }
12679    }
12680
12681    /*
12682     * Update media status on PackageManager.
12683     */
12684    @Override
12685    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12686        int callingUid = Binder.getCallingUid();
12687        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12688            throw new SecurityException("Media status can only be updated by the system");
12689        }
12690        // reader; this apparently protects mMediaMounted, but should probably
12691        // be a different lock in that case.
12692        synchronized (mPackages) {
12693            Log.i(TAG, "Updating external media status from "
12694                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12695                    + (mediaStatus ? "mounted" : "unmounted"));
12696            if (DEBUG_SD_INSTALL)
12697                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12698                        + ", mMediaMounted=" + mMediaMounted);
12699            if (mediaStatus == mMediaMounted) {
12700                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12701                        : 0, -1);
12702                mHandler.sendMessage(msg);
12703                return;
12704            }
12705            mMediaMounted = mediaStatus;
12706        }
12707        // Queue up an async operation since the package installation may take a
12708        // little while.
12709        mHandler.post(new Runnable() {
12710            public void run() {
12711                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12712            }
12713        });
12714    }
12715
12716    /**
12717     * Called by MountService when the initial ASECs to scan are available.
12718     * Should block until all the ASEC containers are finished being scanned.
12719     */
12720    public void scanAvailableAsecs() {
12721        updateExternalMediaStatusInner(true, false, false);
12722        if (mShouldRestoreconData) {
12723            SELinuxMMAC.setRestoreconDone();
12724            mShouldRestoreconData = false;
12725        }
12726    }
12727
12728    /*
12729     * Collect information of applications on external media, map them against
12730     * existing containers and update information based on current mount status.
12731     * Please note that we always have to report status if reportStatus has been
12732     * set to true especially when unloading packages.
12733     */
12734    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12735            boolean externalStorage) {
12736        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12737        int[] uidArr = EmptyArray.INT;
12738
12739        final String[] list = PackageHelper.getSecureContainerList();
12740        if (ArrayUtils.isEmpty(list)) {
12741            Log.i(TAG, "No secure containers found");
12742        } else {
12743            // Process list of secure containers and categorize them
12744            // as active or stale based on their package internal state.
12745
12746            // reader
12747            synchronized (mPackages) {
12748                for (String cid : list) {
12749                    // Leave stages untouched for now; installer service owns them
12750                    if (PackageInstallerService.isStageName(cid)) continue;
12751
12752                    if (DEBUG_SD_INSTALL)
12753                        Log.i(TAG, "Processing container " + cid);
12754                    String pkgName = getAsecPackageName(cid);
12755                    if (pkgName == null) {
12756                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12757                        continue;
12758                    }
12759                    if (DEBUG_SD_INSTALL)
12760                        Log.i(TAG, "Looking for pkg : " + pkgName);
12761
12762                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12763                    if (ps == null) {
12764                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12765                        continue;
12766                    }
12767
12768                    /*
12769                     * Skip packages that are not external if we're unmounting
12770                     * external storage.
12771                     */
12772                    if (externalStorage && !isMounted && !isExternal(ps)) {
12773                        continue;
12774                    }
12775
12776                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12777                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12778                    // The package status is changed only if the code path
12779                    // matches between settings and the container id.
12780                    if (ps.codePathString != null
12781                            && ps.codePathString.startsWith(args.getCodePath())) {
12782                        if (DEBUG_SD_INSTALL) {
12783                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12784                                    + " at code path: " + ps.codePathString);
12785                        }
12786
12787                        // We do have a valid package installed on sdcard
12788                        processCids.put(args, ps.codePathString);
12789                        final int uid = ps.appId;
12790                        if (uid != -1) {
12791                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12792                        }
12793                    } else {
12794                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12795                                + ps.codePathString);
12796                    }
12797                }
12798            }
12799
12800            Arrays.sort(uidArr);
12801        }
12802
12803        // Process packages with valid entries.
12804        if (isMounted) {
12805            if (DEBUG_SD_INSTALL)
12806                Log.i(TAG, "Loading packages");
12807            loadMediaPackages(processCids, uidArr);
12808            startCleaningPackages();
12809            mInstallerService.onSecureContainersAvailable();
12810        } else {
12811            if (DEBUG_SD_INSTALL)
12812                Log.i(TAG, "Unloading packages");
12813            unloadMediaPackages(processCids, uidArr, reportStatus);
12814        }
12815    }
12816
12817    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12818            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12819        int size = pkgList.size();
12820        if (size > 0) {
12821            // Send broadcasts here
12822            Bundle extras = new Bundle();
12823            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12824                    .toArray(new String[size]));
12825            if (uidArr != null) {
12826                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12827            }
12828            if (replacing) {
12829                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12830            }
12831            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12832                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12833            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12834        }
12835    }
12836
12837   /*
12838     * Look at potentially valid container ids from processCids If package
12839     * information doesn't match the one on record or package scanning fails,
12840     * the cid is added to list of removeCids. We currently don't delete stale
12841     * containers.
12842     */
12843    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12844        ArrayList<String> pkgList = new ArrayList<String>();
12845        Set<AsecInstallArgs> keys = processCids.keySet();
12846
12847        for (AsecInstallArgs args : keys) {
12848            String codePath = processCids.get(args);
12849            if (DEBUG_SD_INSTALL)
12850                Log.i(TAG, "Loading container : " + args.cid);
12851            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12852            try {
12853                // Make sure there are no container errors first.
12854                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12855                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12856                            + " when installing from sdcard");
12857                    continue;
12858                }
12859                // Check code path here.
12860                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12861                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12862                            + " does not match one in settings " + codePath);
12863                    continue;
12864                }
12865                // Parse package
12866                int parseFlags = mDefParseFlags;
12867                if (args.isExternal()) {
12868                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12869                }
12870                if (args.isFwdLocked()) {
12871                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12872                }
12873
12874                synchronized (mInstallLock) {
12875                    PackageParser.Package pkg = null;
12876                    try {
12877                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12878                    } catch (PackageManagerException e) {
12879                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12880                    }
12881                    // Scan the package
12882                    if (pkg != null) {
12883                        /*
12884                         * TODO why is the lock being held? doPostInstall is
12885                         * called in other places without the lock. This needs
12886                         * to be straightened out.
12887                         */
12888                        // writer
12889                        synchronized (mPackages) {
12890                            retCode = PackageManager.INSTALL_SUCCEEDED;
12891                            pkgList.add(pkg.packageName);
12892                            // Post process args
12893                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12894                                    pkg.applicationInfo.uid);
12895                        }
12896                    } else {
12897                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12898                    }
12899                }
12900
12901            } finally {
12902                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12903                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12904                }
12905            }
12906        }
12907        // writer
12908        synchronized (mPackages) {
12909            // If the platform SDK has changed since the last time we booted,
12910            // we need to re-grant app permission to catch any new ones that
12911            // appear. This is really a hack, and means that apps can in some
12912            // cases get permissions that the user didn't initially explicitly
12913            // allow... it would be nice to have some better way to handle
12914            // this situation.
12915            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12916            if (regrantPermissions)
12917                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12918                        + mSdkVersion + "; regranting permissions for external storage");
12919            mSettings.mExternalSdkPlatform = mSdkVersion;
12920
12921            // Make sure group IDs have been assigned, and any permission
12922            // changes in other apps are accounted for
12923            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12924                    | (regrantPermissions
12925                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12926                            : 0));
12927
12928            mSettings.updateExternalDatabaseVersion();
12929
12930            // can downgrade to reader
12931            // Persist settings
12932            mSettings.writeLPr();
12933        }
12934        // Send a broadcast to let everyone know we are done processing
12935        if (pkgList.size() > 0) {
12936            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12937        }
12938    }
12939
12940   /*
12941     * Utility method to unload a list of specified containers
12942     */
12943    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12944        // Just unmount all valid containers.
12945        for (AsecInstallArgs arg : cidArgs) {
12946            synchronized (mInstallLock) {
12947                arg.doPostDeleteLI(false);
12948           }
12949       }
12950   }
12951
12952    /*
12953     * Unload packages mounted on external media. This involves deleting package
12954     * data from internal structures, sending broadcasts about diabled packages,
12955     * gc'ing to free up references, unmounting all secure containers
12956     * corresponding to packages on external media, and posting a
12957     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12958     * that we always have to post this message if status has been requested no
12959     * matter what.
12960     */
12961    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12962            final boolean reportStatus) {
12963        if (DEBUG_SD_INSTALL)
12964            Log.i(TAG, "unloading media packages");
12965        ArrayList<String> pkgList = new ArrayList<String>();
12966        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12967        final Set<AsecInstallArgs> keys = processCids.keySet();
12968        for (AsecInstallArgs args : keys) {
12969            String pkgName = args.getPackageName();
12970            if (DEBUG_SD_INSTALL)
12971                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12972            // Delete package internally
12973            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12974            synchronized (mInstallLock) {
12975                boolean res = deletePackageLI(pkgName, null, false, null, null,
12976                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12977                if (res) {
12978                    pkgList.add(pkgName);
12979                } else {
12980                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12981                    failedList.add(args);
12982                }
12983            }
12984        }
12985
12986        // reader
12987        synchronized (mPackages) {
12988            // We didn't update the settings after removing each package;
12989            // write them now for all packages.
12990            mSettings.writeLPr();
12991        }
12992
12993        // We have to absolutely send UPDATED_MEDIA_STATUS only
12994        // after confirming that all the receivers processed the ordered
12995        // broadcast when packages get disabled, force a gc to clean things up.
12996        // and unload all the containers.
12997        if (pkgList.size() > 0) {
12998            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12999                    new IIntentReceiver.Stub() {
13000                public void performReceive(Intent intent, int resultCode, String data,
13001                        Bundle extras, boolean ordered, boolean sticky,
13002                        int sendingUser) throws RemoteException {
13003                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13004                            reportStatus ? 1 : 0, 1, keys);
13005                    mHandler.sendMessage(msg);
13006                }
13007            });
13008        } else {
13009            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13010                    keys);
13011            mHandler.sendMessage(msg);
13012        }
13013    }
13014
13015    /** Binder call */
13016    @Override
13017    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13018            final int flags) {
13019        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13020        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13021        int returnCode = PackageManager.MOVE_SUCCEEDED;
13022        int currInstallFlags = 0;
13023        int newInstallFlags = 0;
13024
13025        File codeFile = null;
13026        String installerPackageName = null;
13027        String packageAbiOverride = null;
13028
13029        // reader
13030        synchronized (mPackages) {
13031            final PackageParser.Package pkg = mPackages.get(packageName);
13032            final PackageSetting ps = mSettings.mPackages.get(packageName);
13033            if (pkg == null || ps == null) {
13034                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13035            } else {
13036                // Disable moving fwd locked apps and system packages
13037                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13038                    Slog.w(TAG, "Cannot move system application");
13039                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13040                } else if (pkg.mOperationPending) {
13041                    Slog.w(TAG, "Attempt to move package which has pending operations");
13042                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13043                } else {
13044                    // Find install location first
13045                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13046                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13047                        Slog.w(TAG, "Ambigous flags specified for move location.");
13048                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13049                    } else {
13050                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13051                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13052                        currInstallFlags = isExternal(pkg)
13053                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13054
13055                        if (newInstallFlags == currInstallFlags) {
13056                            Slog.w(TAG, "No move required. Trying to move to same location");
13057                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13058                        } else {
13059                            if (isForwardLocked(pkg)) {
13060                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13061                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13062                            }
13063                        }
13064                    }
13065                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13066                        pkg.mOperationPending = true;
13067                    }
13068                }
13069
13070                codeFile = new File(pkg.codePath);
13071                installerPackageName = ps.installerPackageName;
13072                packageAbiOverride = ps.cpuAbiOverrideString;
13073            }
13074        }
13075
13076        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13077            try {
13078                observer.packageMoved(packageName, returnCode);
13079            } catch (RemoteException ignored) {
13080            }
13081            return;
13082        }
13083
13084        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13085            @Override
13086            public void onUserActionRequired(Intent intent) throws RemoteException {
13087                throw new IllegalStateException();
13088            }
13089
13090            @Override
13091            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13092                    Bundle extras) throws RemoteException {
13093                Slog.d(TAG, "Install result for move: "
13094                        + PackageManager.installStatusToString(returnCode, msg));
13095
13096                // We usually have a new package now after the install, but if
13097                // we failed we need to clear the pending flag on the original
13098                // package object.
13099                synchronized (mPackages) {
13100                    final PackageParser.Package pkg = mPackages.get(packageName);
13101                    if (pkg != null) {
13102                        pkg.mOperationPending = false;
13103                    }
13104                }
13105
13106                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13107                switch (status) {
13108                    case PackageInstaller.STATUS_SUCCESS:
13109                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13110                        break;
13111                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13112                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13113                        break;
13114                    default:
13115                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13116                        break;
13117                }
13118            }
13119        };
13120
13121        // Treat a move like reinstalling an existing app, which ensures that we
13122        // process everythign uniformly, like unpacking native libraries.
13123        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13124
13125        final Message msg = mHandler.obtainMessage(INIT_COPY);
13126        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13127        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13128                installerPackageName, null, user, packageAbiOverride);
13129        mHandler.sendMessage(msg);
13130    }
13131
13132    @Override
13133    public boolean setInstallLocation(int loc) {
13134        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13135                null);
13136        if (getInstallLocation() == loc) {
13137            return true;
13138        }
13139        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13140                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13141            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13142                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13143            return true;
13144        }
13145        return false;
13146   }
13147
13148    @Override
13149    public int getInstallLocation() {
13150        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13151                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13152                PackageHelper.APP_INSTALL_AUTO);
13153    }
13154
13155    /** Called by UserManagerService */
13156    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13157        mDirtyUsers.remove(userHandle);
13158        mSettings.removeUserLPw(userHandle);
13159        mPendingBroadcasts.remove(userHandle);
13160        if (mInstaller != null) {
13161            // Technically, we shouldn't be doing this with the package lock
13162            // held.  However, this is very rare, and there is already so much
13163            // other disk I/O going on, that we'll let it slide for now.
13164            mInstaller.removeUserDataDirs(userHandle);
13165        }
13166        mUserNeedsBadging.delete(userHandle);
13167        removeUnusedPackagesLILPw(userManager, userHandle);
13168    }
13169
13170    /**
13171     * We're removing userHandle and would like to remove any downloaded packages
13172     * that are no longer in use by any other user.
13173     * @param userHandle the user being removed
13174     */
13175    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13176        final boolean DEBUG_CLEAN_APKS = false;
13177        int [] users = userManager.getUserIdsLPr();
13178        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13179        while (psit.hasNext()) {
13180            PackageSetting ps = psit.next();
13181            if (ps.pkg == null) {
13182                continue;
13183            }
13184            final String packageName = ps.pkg.packageName;
13185            // Skip over if system app
13186            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13187                continue;
13188            }
13189            if (DEBUG_CLEAN_APKS) {
13190                Slog.i(TAG, "Checking package " + packageName);
13191            }
13192            boolean keep = false;
13193            for (int i = 0; i < users.length; i++) {
13194                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13195                    keep = true;
13196                    if (DEBUG_CLEAN_APKS) {
13197                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13198                                + users[i]);
13199                    }
13200                    break;
13201                }
13202            }
13203            if (!keep) {
13204                if (DEBUG_CLEAN_APKS) {
13205                    Slog.i(TAG, "  Removing package " + packageName);
13206                }
13207                mHandler.post(new Runnable() {
13208                    public void run() {
13209                        deletePackageX(packageName, userHandle, 0);
13210                    } //end run
13211                });
13212            }
13213        }
13214    }
13215
13216    /** Called by UserManagerService */
13217    void createNewUserLILPw(int userHandle, File path) {
13218        if (mInstaller != null) {
13219            mInstaller.createUserConfig(userHandle);
13220            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13221        }
13222    }
13223
13224    @Override
13225    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13226        mContext.enforceCallingOrSelfPermission(
13227                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13228                "Only package verification agents can read the verifier device identity");
13229
13230        synchronized (mPackages) {
13231            return mSettings.getVerifierDeviceIdentityLPw();
13232        }
13233    }
13234
13235    @Override
13236    public void setPermissionEnforced(String permission, boolean enforced) {
13237        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13238        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13239            synchronized (mPackages) {
13240                if (mSettings.mReadExternalStorageEnforced == null
13241                        || mSettings.mReadExternalStorageEnforced != enforced) {
13242                    mSettings.mReadExternalStorageEnforced = enforced;
13243                    mSettings.writeLPr();
13244                }
13245            }
13246            // kill any non-foreground processes so we restart them and
13247            // grant/revoke the GID.
13248            final IActivityManager am = ActivityManagerNative.getDefault();
13249            if (am != null) {
13250                final long token = Binder.clearCallingIdentity();
13251                try {
13252                    am.killProcessesBelowForeground("setPermissionEnforcement");
13253                } catch (RemoteException e) {
13254                } finally {
13255                    Binder.restoreCallingIdentity(token);
13256                }
13257            }
13258        } else {
13259            throw new IllegalArgumentException("No selective enforcement for " + permission);
13260        }
13261    }
13262
13263    @Override
13264    @Deprecated
13265    public boolean isPermissionEnforced(String permission) {
13266        return true;
13267    }
13268
13269    @Override
13270    public boolean isStorageLow() {
13271        final long token = Binder.clearCallingIdentity();
13272        try {
13273            final DeviceStorageMonitorInternal
13274                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13275            if (dsm != null) {
13276                return dsm.isMemoryLow();
13277            } else {
13278                return false;
13279            }
13280        } finally {
13281            Binder.restoreCallingIdentity(token);
13282        }
13283    }
13284
13285    @Override
13286    public IPackageInstaller getPackageInstaller() {
13287        return mInstallerService;
13288    }
13289
13290    private boolean userNeedsBadging(int userId) {
13291        int index = mUserNeedsBadging.indexOfKey(userId);
13292        if (index < 0) {
13293            final UserInfo userInfo;
13294            final long token = Binder.clearCallingIdentity();
13295            try {
13296                userInfo = sUserManager.getUserInfo(userId);
13297            } finally {
13298                Binder.restoreCallingIdentity(token);
13299            }
13300            final boolean b;
13301            if (userInfo != null && userInfo.isManagedProfile()) {
13302                b = true;
13303            } else {
13304                b = false;
13305            }
13306            mUserNeedsBadging.put(userId, b);
13307            return b;
13308        }
13309        return mUserNeedsBadging.valueAt(index);
13310    }
13311
13312    @Override
13313    public KeySet getKeySetByAlias(String packageName, String alias) {
13314        if (packageName == null || alias == null) {
13315            return null;
13316        }
13317        synchronized(mPackages) {
13318            final PackageParser.Package pkg = mPackages.get(packageName);
13319            if (pkg == null) {
13320                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13321                throw new IllegalArgumentException("Unknown package: " + packageName);
13322            }
13323            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13324            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13325        }
13326    }
13327
13328    @Override
13329    public KeySet getSigningKeySet(String packageName) {
13330        if (packageName == null) {
13331            return null;
13332        }
13333        synchronized(mPackages) {
13334            final PackageParser.Package pkg = mPackages.get(packageName);
13335            if (pkg == null) {
13336                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13337                throw new IllegalArgumentException("Unknown package: " + packageName);
13338            }
13339            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13340                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13341                throw new SecurityException("May not access signing KeySet of other apps.");
13342            }
13343            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13344            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13345        }
13346    }
13347
13348    @Override
13349    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13350        if (packageName == null || ks == null) {
13351            return false;
13352        }
13353        synchronized(mPackages) {
13354            final PackageParser.Package pkg = mPackages.get(packageName);
13355            if (pkg == null) {
13356                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13357                throw new IllegalArgumentException("Unknown package: " + packageName);
13358            }
13359            IBinder ksh = ks.getToken();
13360            if (ksh instanceof KeySetHandle) {
13361                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13362                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13363            }
13364            return false;
13365        }
13366    }
13367
13368    @Override
13369    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13370        if (packageName == null || ks == null) {
13371            return false;
13372        }
13373        synchronized(mPackages) {
13374            final PackageParser.Package pkg = mPackages.get(packageName);
13375            if (pkg == null) {
13376                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13377                throw new IllegalArgumentException("Unknown package: " + packageName);
13378            }
13379            IBinder ksh = ks.getToken();
13380            if (ksh instanceof KeySetHandle) {
13381                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13382                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13383            }
13384            return false;
13385        }
13386    }
13387
13388    public void getUsageStatsIfNoPackageUsageInfo() {
13389        if (!mPackageUsage.isHistoricalPackageUsageAvailable()) {
13390            UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
13391            if (usm == null) {
13392                throw new IllegalStateException("UsageStatsManager must be initialized");
13393            }
13394            long now = System.currentTimeMillis();
13395            Map<String, UsageStats> stats = usm.queryAndAggregateUsageStats(now - mDexOptLRUThresholdInMills, now);
13396            for (Map.Entry<String, UsageStats> entry : stats.entrySet()) {
13397                String packageName = entry.getKey();
13398                PackageParser.Package pkg = mPackages.get(packageName);
13399                if (pkg == null) {
13400                    continue;
13401                }
13402                UsageStats usage = entry.getValue();
13403                pkg.mLastPackageUsageTimeInMills = usage.getLastTimeUsed();
13404                mPackageUsage.mIsHistoricalPackageUsageAvailable = true;
13405            }
13406        }
13407    }
13408}
13409