PackageManagerService.java revision 735600c1e654ef3d4fe1201aa31d1f4eb33c18e3
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.content.BroadcastReceiver;
88import android.content.ComponentName;
89import android.content.Context;
90import android.content.IIntentReceiver;
91import android.content.Intent;
92import android.content.IntentFilter;
93import android.content.IntentSender;
94import android.content.IntentSender.SendIntentException;
95import android.content.ServiceConnection;
96import android.content.pm.ActivityInfo;
97import android.content.pm.ApplicationInfo;
98import android.content.pm.FeatureInfo;
99import android.content.pm.IPackageDataObserver;
100import android.content.pm.IPackageDeleteObserver;
101import android.content.pm.IPackageDeleteObserver2;
102import android.content.pm.IPackageInstallObserver2;
103import android.content.pm.IPackageInstaller;
104import android.content.pm.IPackageManager;
105import android.content.pm.IPackageMoveObserver;
106import android.content.pm.IPackageStatsObserver;
107import android.content.pm.InstrumentationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageParser.ActivityIntentInfo;
117import android.content.pm.PackageParser.PackageLite;
118import android.content.pm.PackageParser.PackageParserException;
119import android.content.pm.PackageParser;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Environment;
140import android.os.Environment.UserEnvironment;
141import android.os.storage.StorageManager;
142import android.os.Debug;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.util.ArraySet;
165import android.util.AtomicFile;
166import android.util.DisplayMetrics;
167import android.util.EventLog;
168import android.util.ExceptionUtils;
169import android.util.Log;
170import android.util.LogPrinter;
171import android.util.PrintStreamPrinter;
172import android.util.Slog;
173import android.util.SparseArray;
174import android.util.SparseBooleanArray;
175import android.view.Display;
176
177import java.io.BufferedInputStream;
178import java.io.BufferedOutputStream;
179import java.io.BufferedReader;
180import java.io.File;
181import java.io.FileDescriptor;
182import java.io.FileInputStream;
183import java.io.FileNotFoundException;
184import java.io.FileOutputStream;
185import java.io.FileReader;
186import java.io.FilenameFilter;
187import java.io.IOException;
188import java.io.InputStream;
189import java.io.PrintWriter;
190import java.nio.charset.StandardCharsets;
191import java.security.NoSuchAlgorithmException;
192import java.security.PublicKey;
193import java.security.cert.CertificateEncodingException;
194import java.security.cert.CertificateException;
195import java.text.SimpleDateFormat;
196import java.util.ArrayList;
197import java.util.Arrays;
198import java.util.Collection;
199import java.util.Collections;
200import java.util.Comparator;
201import java.util.Date;
202import java.util.HashMap;
203import java.util.HashSet;
204import java.util.Iterator;
205import java.util.List;
206import java.util.Map;
207import java.util.Objects;
208import java.util.Set;
209import java.util.concurrent.atomic.AtomicBoolean;
210import java.util.concurrent.atomic.AtomicLong;
211
212import dalvik.system.DexFile;
213import dalvik.system.StaleDexCacheError;
214import dalvik.system.VMRuntime;
215
216import libcore.io.IoUtils;
217import libcore.util.EmptyArray;
218
219/**
220 * Keep track of all those .apks everywhere.
221 *
222 * This is very central to the platform's security; please run the unit
223 * tests whenever making modifications here:
224 *
225mmm frameworks/base/tests/AndroidTests
226adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
227adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
228 *
229 * {@hide}
230 */
231public class PackageManagerService extends IPackageManager.Stub {
232    static final String TAG = "PackageManager";
233    static final boolean DEBUG_SETTINGS = false;
234    static final boolean DEBUG_PREFERRED = false;
235    static final boolean DEBUG_UPGRADE = false;
236    private static final boolean DEBUG_INSTALL = false;
237    private static final boolean DEBUG_REMOVE = false;
238    private static final boolean DEBUG_BROADCASTS = false;
239    private static final boolean DEBUG_SHOW_INFO = false;
240    private static final boolean DEBUG_PACKAGE_INFO = false;
241    private static final boolean DEBUG_INTENT_MATCHING = false;
242    private static final boolean DEBUG_PACKAGE_SCANNING = false;
243    private static final boolean DEBUG_VERIFY = false;
244    private static final boolean DEBUG_DEXOPT = false;
245    private static final boolean DEBUG_ABI_SELECTION = false;
246
247    private static final int RADIO_UID = Process.PHONE_UID;
248    private static final int LOG_UID = Process.LOG_UID;
249    private static final int NFC_UID = Process.NFC_UID;
250    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
251    private static final int SHELL_UID = Process.SHELL_UID;
252
253    // Cap the size of permission trees that 3rd party apps can define
254    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
255
256    // Suffix used during package installation when copying/moving
257    // package apks to install directory.
258    private static final String INSTALL_PACKAGE_SUFFIX = "-";
259
260    static final int SCAN_NO_DEX = 1<<1;
261    static final int SCAN_FORCE_DEX = 1<<2;
262    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
263    static final int SCAN_NEW_INSTALL = 1<<4;
264    static final int SCAN_NO_PATHS = 1<<5;
265    static final int SCAN_UPDATE_TIME = 1<<6;
266    static final int SCAN_DEFER_DEX = 1<<7;
267    static final int SCAN_BOOTING = 1<<8;
268    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
269    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
270    static final int SCAN_REPLACING = 1<<11;
271
272    static final int REMOVE_CHATTY = 1<<16;
273
274    /**
275     * Timeout (in milliseconds) after which the watchdog should declare that
276     * our handler thread is wedged.  The usual default for such things is one
277     * minute but we sometimes do very lengthy I/O operations on this thread,
278     * such as installing multi-gigabyte applications, so ours needs to be longer.
279     */
280    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
281
282    /**
283     * Whether verification is enabled by default.
284     */
285    private static final boolean DEFAULT_VERIFY_ENABLE = true;
286
287    /**
288     * The default maximum time to wait for the verification agent to return in
289     * milliseconds.
290     */
291    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
292
293    /**
294     * The default response for package verification timeout.
295     *
296     * This can be either PackageManager.VERIFICATION_ALLOW or
297     * PackageManager.VERIFICATION_REJECT.
298     */
299    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
300
301    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
302
303    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
304            DEFAULT_CONTAINER_PACKAGE,
305            "com.android.defcontainer.DefaultContainerService");
306
307    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
308
309    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
310
311    private static String sPreferredInstructionSet;
312
313    final ServiceThread mHandlerThread;
314
315    private static final String IDMAP_PREFIX = "/data/resource-cache/";
316    private static final String IDMAP_SUFFIX = "@idmap";
317
318    final PackageHandler mHandler;
319
320    /**
321     * Messages for {@link #mHandler} that need to wait for system ready before
322     * being dispatched.
323     */
324    private ArrayList<Message> mPostSystemReadyMessages;
325
326    final int mSdkVersion = Build.VERSION.SDK_INT;
327
328    final Context mContext;
329    final boolean mFactoryTest;
330    final boolean mOnlyCore;
331    final boolean mLazyDexOpt;
332    final DisplayMetrics mMetrics;
333    final int mDefParseFlags;
334    final String[] mSeparateProcesses;
335
336    // This is where all application persistent data goes.
337    final File mAppDataDir;
338
339    // This is where all application persistent data goes for secondary users.
340    final File mUserAppDataDir;
341
342    /** The location for ASEC container files on internal storage. */
343    final String mAsecInternalPath;
344
345    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
346    // LOCK HELD.  Can be called with mInstallLock held.
347    final Installer mInstaller;
348
349    /** Directory where installed third-party apps stored */
350    final File mAppInstallDir;
351
352    /**
353     * Directory to which applications installed internally have their
354     * 32 bit native libraries copied.
355     */
356    private File mAppLib32InstallDir;
357
358    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
359    // apps.
360    final File mDrmAppPrivateInstallDir;
361
362    // ----------------------------------------------------------------
363
364    // Lock for state used when installing and doing other long running
365    // operations.  Methods that must be called with this lock held have
366    // the suffix "LI".
367    final Object mInstallLock = new Object();
368
369    // ----------------------------------------------------------------
370
371    // Keys are String (package name), values are Package.  This also serves
372    // as the lock for the global state.  Methods that must be called with
373    // this lock held have the prefix "LP".
374    final HashMap<String, PackageParser.Package> mPackages =
375            new HashMap<String, PackageParser.Package>();
376
377    // Tracks available target package names -> overlay package paths.
378    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
379        new HashMap<String, HashMap<String, PackageParser.Package>>();
380
381    final Settings mSettings;
382    boolean mRestoredSettings;
383
384    // System configuration read by SystemConfig.
385    final int[] mGlobalGids;
386    final SparseArray<HashSet<String>> mSystemPermissions;
387    final HashMap<String, FeatureInfo> mAvailableFeatures;
388
389    // If mac_permissions.xml was found for seinfo labeling.
390    boolean mFoundPolicyFile;
391
392    // If a recursive restorecon of /data/data/<pkg> is needed.
393    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
394
395    public static final class SharedLibraryEntry {
396        public final String path;
397        public final String apk;
398
399        SharedLibraryEntry(String _path, String _apk) {
400            path = _path;
401            apk = _apk;
402        }
403    }
404
405    // Currently known shared libraries.
406    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
407            new HashMap<String, SharedLibraryEntry>();
408
409    // All available activities, for your resolving pleasure.
410    final ActivityIntentResolver mActivities =
411            new ActivityIntentResolver();
412
413    // All available receivers, for your resolving pleasure.
414    final ActivityIntentResolver mReceivers =
415            new ActivityIntentResolver();
416
417    // All available services, for your resolving pleasure.
418    final ServiceIntentResolver mServices = new ServiceIntentResolver();
419
420    // All available providers, for your resolving pleasure.
421    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
422
423    // Mapping from provider base names (first directory in content URI codePath)
424    // to the provider information.
425    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
426            new HashMap<String, PackageParser.Provider>();
427
428    // Mapping from instrumentation class names to info about them.
429    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
430            new HashMap<ComponentName, PackageParser.Instrumentation>();
431
432    // Mapping from permission names to info about them.
433    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
434            new HashMap<String, PackageParser.PermissionGroup>();
435
436    // Packages whose data we have transfered into another package, thus
437    // should no longer exist.
438    final HashSet<String> mTransferedPackages = new HashSet<String>();
439
440    // Broadcast actions that are only available to the system.
441    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
442
443    /** List of packages waiting for verification. */
444    final SparseArray<PackageVerificationState> mPendingVerification
445            = new SparseArray<PackageVerificationState>();
446
447    /** Set of packages associated with each app op permission. */
448    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
449
450    final PackageInstallerService mInstallerService;
451
452    HashSet<PackageParser.Package> mDeferredDexOpt = null;
453
454    // Cache of users who need badging.
455    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
456
457    /** Token for keys in mPendingVerification. */
458    private int mPendingVerificationToken = 0;
459
460    volatile boolean mSystemReady;
461    volatile boolean mSafeMode;
462    volatile boolean mHasSystemUidErrors;
463
464    ApplicationInfo mAndroidApplication;
465    final ActivityInfo mResolveActivity = new ActivityInfo();
466    final ResolveInfo mResolveInfo = new ResolveInfo();
467    ComponentName mResolveComponentName;
468    PackageParser.Package mPlatformPackage;
469    ComponentName mCustomResolverComponentName;
470
471    boolean mResolverReplaced = false;
472
473    // Set of pending broadcasts for aggregating enable/disable of components.
474    static class PendingPackageBroadcasts {
475        // for each user id, a map of <package name -> components within that package>
476        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
477
478        public PendingPackageBroadcasts() {
479            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
480        }
481
482        public ArrayList<String> get(int userId, String packageName) {
483            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
484            return packages.get(packageName);
485        }
486
487        public void put(int userId, String packageName, ArrayList<String> components) {
488            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
489            packages.put(packageName, components);
490        }
491
492        public void remove(int userId, String packageName) {
493            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
494            if (packages != null) {
495                packages.remove(packageName);
496            }
497        }
498
499        public void remove(int userId) {
500            mUidMap.remove(userId);
501        }
502
503        public int userIdCount() {
504            return mUidMap.size();
505        }
506
507        public int userIdAt(int n) {
508            return mUidMap.keyAt(n);
509        }
510
511        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
512            return mUidMap.get(userId);
513        }
514
515        public int size() {
516            // total number of pending broadcast entries across all userIds
517            int num = 0;
518            for (int i = 0; i< mUidMap.size(); i++) {
519                num += mUidMap.valueAt(i).size();
520            }
521            return num;
522        }
523
524        public void clear() {
525            mUidMap.clear();
526        }
527
528        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
529            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
530            if (map == null) {
531                map = new HashMap<String, ArrayList<String>>();
532                mUidMap.put(userId, map);
533            }
534            return map;
535        }
536    }
537    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
538
539    // Service Connection to remote media container service to copy
540    // package uri's from external media onto secure containers
541    // or internal storage.
542    private IMediaContainerService mContainerService = null;
543
544    static final int SEND_PENDING_BROADCAST = 1;
545    static final int MCS_BOUND = 3;
546    static final int END_COPY = 4;
547    static final int INIT_COPY = 5;
548    static final int MCS_UNBIND = 6;
549    static final int START_CLEANING_PACKAGE = 7;
550    static final int FIND_INSTALL_LOC = 8;
551    static final int POST_INSTALL = 9;
552    static final int MCS_RECONNECT = 10;
553    static final int MCS_GIVE_UP = 11;
554    static final int UPDATED_MEDIA_STATUS = 12;
555    static final int WRITE_SETTINGS = 13;
556    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
557    static final int PACKAGE_VERIFIED = 15;
558    static final int CHECK_PENDING_VERIFICATION = 16;
559
560    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
561
562    // Delay time in millisecs
563    static final int BROADCAST_DELAY = 10 * 1000;
564
565    static UserManagerService sUserManager;
566
567    // Stores a list of users whose package restrictions file needs to be updated
568    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
569
570    final private DefaultContainerConnection mDefContainerConn =
571            new DefaultContainerConnection();
572    class DefaultContainerConnection implements ServiceConnection {
573        public void onServiceConnected(ComponentName name, IBinder service) {
574            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
575            IMediaContainerService imcs =
576                IMediaContainerService.Stub.asInterface(service);
577            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
578        }
579
580        public void onServiceDisconnected(ComponentName name) {
581            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
582        }
583    };
584
585    // Recordkeeping of restore-after-install operations that are currently in flight
586    // between the Package Manager and the Backup Manager
587    class PostInstallData {
588        public InstallArgs args;
589        public PackageInstalledInfo res;
590
591        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
592            args = _a;
593            res = _r;
594        }
595    };
596    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
597    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
598
599    private final String mRequiredVerifierPackage;
600
601    private final PackageUsage mPackageUsage = new PackageUsage();
602
603    private class PackageUsage {
604        private static final int WRITE_INTERVAL
605            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
606
607        private final Object mFileLock = new Object();
608        private final AtomicLong mLastWritten = new AtomicLong(0);
609        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
610
611        private boolean mIsHistoricalPackageUsageAvailable = true;
612
613        boolean isHistoricalPackageUsageAvailable() {
614            return mIsHistoricalPackageUsageAvailable;
615        }
616
617        void write(boolean force) {
618            if (force) {
619                writeInternal();
620                return;
621            }
622            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
623                && !DEBUG_DEXOPT) {
624                return;
625            }
626            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
627                new Thread("PackageUsage_DiskWriter") {
628                    @Override
629                    public void run() {
630                        try {
631                            writeInternal();
632                        } finally {
633                            mBackgroundWriteRunning.set(false);
634                        }
635                    }
636                }.start();
637            }
638        }
639
640        private void writeInternal() {
641            synchronized (mPackages) {
642                synchronized (mFileLock) {
643                    AtomicFile file = getFile();
644                    FileOutputStream f = null;
645                    try {
646                        f = file.startWrite();
647                        BufferedOutputStream out = new BufferedOutputStream(f);
648                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
649                        StringBuilder sb = new StringBuilder();
650                        for (PackageParser.Package pkg : mPackages.values()) {
651                            if (pkg.mLastPackageUsageTimeInMills == 0) {
652                                continue;
653                            }
654                            sb.setLength(0);
655                            sb.append(pkg.packageName);
656                            sb.append(' ');
657                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
658                            sb.append('\n');
659                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
660                        }
661                        out.flush();
662                        file.finishWrite(f);
663                    } catch (IOException e) {
664                        if (f != null) {
665                            file.failWrite(f);
666                        }
667                        Log.e(TAG, "Failed to write package usage times", e);
668                    }
669                }
670            }
671            mLastWritten.set(SystemClock.elapsedRealtime());
672        }
673
674        void readLP() {
675            synchronized (mFileLock) {
676                AtomicFile file = getFile();
677                BufferedInputStream in = null;
678                try {
679                    in = new BufferedInputStream(file.openRead());
680                    StringBuffer sb = new StringBuffer();
681                    while (true) {
682                        String packageName = readToken(in, sb, ' ');
683                        if (packageName == null) {
684                            break;
685                        }
686                        String timeInMillisString = readToken(in, sb, '\n');
687                        if (timeInMillisString == null) {
688                            throw new IOException("Failed to find last usage time for package "
689                                                  + packageName);
690                        }
691                        PackageParser.Package pkg = mPackages.get(packageName);
692                        if (pkg == null) {
693                            continue;
694                        }
695                        long timeInMillis;
696                        try {
697                            timeInMillis = Long.parseLong(timeInMillisString.toString());
698                        } catch (NumberFormatException e) {
699                            throw new IOException("Failed to parse " + timeInMillisString
700                                                  + " as a long.", e);
701                        }
702                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
703                    }
704                } catch (FileNotFoundException expected) {
705                    mIsHistoricalPackageUsageAvailable = false;
706                } catch (IOException e) {
707                    Log.w(TAG, "Failed to read package usage times", e);
708                } finally {
709                    IoUtils.closeQuietly(in);
710                }
711            }
712            mLastWritten.set(SystemClock.elapsedRealtime());
713        }
714
715        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
716                throws IOException {
717            sb.setLength(0);
718            while (true) {
719                int ch = in.read();
720                if (ch == -1) {
721                    if (sb.length() == 0) {
722                        return null;
723                    }
724                    throw new IOException("Unexpected EOF");
725                }
726                if (ch == endOfToken) {
727                    return sb.toString();
728                }
729                sb.append((char)ch);
730            }
731        }
732
733        private AtomicFile getFile() {
734            File dataDir = Environment.getDataDirectory();
735            File systemDir = new File(dataDir, "system");
736            File fname = new File(systemDir, "package-usage.list");
737            return new AtomicFile(fname);
738        }
739    }
740
741    class PackageHandler extends Handler {
742        private boolean mBound = false;
743        final ArrayList<HandlerParams> mPendingInstalls =
744            new ArrayList<HandlerParams>();
745
746        private boolean connectToService() {
747            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
748                    " DefaultContainerService");
749            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
750            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
751            if (mContext.bindServiceAsUser(service, mDefContainerConn,
752                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
753                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754                mBound = true;
755                return true;
756            }
757            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
758            return false;
759        }
760
761        private void disconnectService() {
762            mContainerService = null;
763            mBound = false;
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            mContext.unbindService(mDefContainerConn);
766            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767        }
768
769        PackageHandler(Looper looper) {
770            super(looper);
771        }
772
773        public void handleMessage(Message msg) {
774            try {
775                doHandleMessage(msg);
776            } finally {
777                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
778            }
779        }
780
781        void doHandleMessage(Message msg) {
782            switch (msg.what) {
783                case INIT_COPY: {
784                    HandlerParams params = (HandlerParams) msg.obj;
785                    int idx = mPendingInstalls.size();
786                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
787                    // If a bind was already initiated we dont really
788                    // need to do anything. The pending install
789                    // will be processed later on.
790                    if (!mBound) {
791                        // If this is the only one pending we might
792                        // have to bind to the service again.
793                        if (!connectToService()) {
794                            Slog.e(TAG, "Failed to bind to media container service");
795                            params.serviceError();
796                            return;
797                        } else {
798                            // Once we bind to the service, the first
799                            // pending request will be processed.
800                            mPendingInstalls.add(idx, params);
801                        }
802                    } else {
803                        mPendingInstalls.add(idx, params);
804                        // Already bound to the service. Just make
805                        // sure we trigger off processing the first request.
806                        if (idx == 0) {
807                            mHandler.sendEmptyMessage(MCS_BOUND);
808                        }
809                    }
810                    break;
811                }
812                case MCS_BOUND: {
813                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
814                    if (msg.obj != null) {
815                        mContainerService = (IMediaContainerService) msg.obj;
816                    }
817                    if (mContainerService == null) {
818                        // Something seriously wrong. Bail out
819                        Slog.e(TAG, "Cannot bind to media container service");
820                        for (HandlerParams params : mPendingInstalls) {
821                            // Indicate service bind error
822                            params.serviceError();
823                        }
824                        mPendingInstalls.clear();
825                    } else if (mPendingInstalls.size() > 0) {
826                        HandlerParams params = mPendingInstalls.get(0);
827                        if (params != null) {
828                            if (params.startCopy()) {
829                                // We are done...  look for more work or to
830                                // go idle.
831                                if (DEBUG_SD_INSTALL) Log.i(TAG,
832                                        "Checking for more work or unbind...");
833                                // Delete pending install
834                                if (mPendingInstalls.size() > 0) {
835                                    mPendingInstalls.remove(0);
836                                }
837                                if (mPendingInstalls.size() == 0) {
838                                    if (mBound) {
839                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
840                                                "Posting delayed MCS_UNBIND");
841                                        removeMessages(MCS_UNBIND);
842                                        Message ubmsg = obtainMessage(MCS_UNBIND);
843                                        // Unbind after a little delay, to avoid
844                                        // continual thrashing.
845                                        sendMessageDelayed(ubmsg, 10000);
846                                    }
847                                } else {
848                                    // There are more pending requests in queue.
849                                    // Just post MCS_BOUND message to trigger processing
850                                    // of next pending install.
851                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
852                                            "Posting MCS_BOUND for next work");
853                                    mHandler.sendEmptyMessage(MCS_BOUND);
854                                }
855                            }
856                        }
857                    } else {
858                        // Should never happen ideally.
859                        Slog.w(TAG, "Empty queue");
860                    }
861                    break;
862                }
863                case MCS_RECONNECT: {
864                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
865                    if (mPendingInstalls.size() > 0) {
866                        if (mBound) {
867                            disconnectService();
868                        }
869                        if (!connectToService()) {
870                            Slog.e(TAG, "Failed to bind to media container service");
871                            for (HandlerParams params : mPendingInstalls) {
872                                // Indicate service bind error
873                                params.serviceError();
874                            }
875                            mPendingInstalls.clear();
876                        }
877                    }
878                    break;
879                }
880                case MCS_UNBIND: {
881                    // If there is no actual work left, then time to unbind.
882                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
883
884                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
885                        if (mBound) {
886                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
887
888                            disconnectService();
889                        }
890                    } else if (mPendingInstalls.size() > 0) {
891                        // There are more pending requests in queue.
892                        // Just post MCS_BOUND message to trigger processing
893                        // of next pending install.
894                        mHandler.sendEmptyMessage(MCS_BOUND);
895                    }
896
897                    break;
898                }
899                case MCS_GIVE_UP: {
900                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
901                    mPendingInstalls.remove(0);
902                    break;
903                }
904                case SEND_PENDING_BROADCAST: {
905                    String packages[];
906                    ArrayList<String> components[];
907                    int size = 0;
908                    int uids[];
909                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
910                    synchronized (mPackages) {
911                        if (mPendingBroadcasts == null) {
912                            return;
913                        }
914                        size = mPendingBroadcasts.size();
915                        if (size <= 0) {
916                            // Nothing to be done. Just return
917                            return;
918                        }
919                        packages = new String[size];
920                        components = new ArrayList[size];
921                        uids = new int[size];
922                        int i = 0;  // filling out the above arrays
923
924                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
925                            int packageUserId = mPendingBroadcasts.userIdAt(n);
926                            Iterator<Map.Entry<String, ArrayList<String>>> it
927                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
928                                            .entrySet().iterator();
929                            while (it.hasNext() && i < size) {
930                                Map.Entry<String, ArrayList<String>> ent = it.next();
931                                packages[i] = ent.getKey();
932                                components[i] = ent.getValue();
933                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
934                                uids[i] = (ps != null)
935                                        ? UserHandle.getUid(packageUserId, ps.appId)
936                                        : -1;
937                                i++;
938                            }
939                        }
940                        size = i;
941                        mPendingBroadcasts.clear();
942                    }
943                    // Send broadcasts
944                    for (int i = 0; i < size; i++) {
945                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
946                    }
947                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
948                    break;
949                }
950                case START_CLEANING_PACKAGE: {
951                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
952                    final String packageName = (String)msg.obj;
953                    final int userId = msg.arg1;
954                    final boolean andCode = msg.arg2 != 0;
955                    synchronized (mPackages) {
956                        if (userId == UserHandle.USER_ALL) {
957                            int[] users = sUserManager.getUserIds();
958                            for (int user : users) {
959                                mSettings.addPackageToCleanLPw(
960                                        new PackageCleanItem(user, packageName, andCode));
961                            }
962                        } else {
963                            mSettings.addPackageToCleanLPw(
964                                    new PackageCleanItem(userId, packageName, andCode));
965                        }
966                    }
967                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
968                    startCleaningPackages();
969                } break;
970                case POST_INSTALL: {
971                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
972                    PostInstallData data = mRunningInstalls.get(msg.arg1);
973                    mRunningInstalls.delete(msg.arg1);
974                    boolean deleteOld = false;
975
976                    if (data != null) {
977                        InstallArgs args = data.args;
978                        PackageInstalledInfo res = data.res;
979
980                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
981                            res.removedInfo.sendBroadcast(false, true, false);
982                            Bundle extras = new Bundle(1);
983                            extras.putInt(Intent.EXTRA_UID, res.uid);
984                            // Determine the set of users who are adding this
985                            // package for the first time vs. those who are seeing
986                            // an update.
987                            int[] firstUsers;
988                            int[] updateUsers = new int[0];
989                            if (res.origUsers == null || res.origUsers.length == 0) {
990                                firstUsers = res.newUsers;
991                            } else {
992                                firstUsers = new int[0];
993                                for (int i=0; i<res.newUsers.length; i++) {
994                                    int user = res.newUsers[i];
995                                    boolean isNew = true;
996                                    for (int j=0; j<res.origUsers.length; j++) {
997                                        if (res.origUsers[j] == user) {
998                                            isNew = false;
999                                            break;
1000                                        }
1001                                    }
1002                                    if (isNew) {
1003                                        int[] newFirst = new int[firstUsers.length+1];
1004                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1005                                                firstUsers.length);
1006                                        newFirst[firstUsers.length] = user;
1007                                        firstUsers = newFirst;
1008                                    } else {
1009                                        int[] newUpdate = new int[updateUsers.length+1];
1010                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1011                                                updateUsers.length);
1012                                        newUpdate[updateUsers.length] = user;
1013                                        updateUsers = newUpdate;
1014                                    }
1015                                }
1016                            }
1017                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1018                                    res.pkg.applicationInfo.packageName,
1019                                    extras, null, null, firstUsers);
1020                            final boolean update = res.removedInfo.removedPackage != null;
1021                            if (update) {
1022                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1023                            }
1024                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1025                                    res.pkg.applicationInfo.packageName,
1026                                    extras, null, null, updateUsers);
1027                            if (update) {
1028                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1029                                        res.pkg.applicationInfo.packageName,
1030                                        extras, null, null, updateUsers);
1031                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1032                                        null, null,
1033                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1034
1035                                // treat asec-hosted packages like removable media on upgrade
1036                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1037                                    if (DEBUG_INSTALL) {
1038                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1039                                                + " is ASEC-hosted -> AVAILABLE");
1040                                    }
1041                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1042                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1043                                    pkgList.add(res.pkg.applicationInfo.packageName);
1044                                    sendResourcesChangedBroadcast(true, true,
1045                                            pkgList,uidArray, null);
1046                                }
1047                            }
1048                            if (res.removedInfo.args != null) {
1049                                // Remove the replaced package's older resources safely now
1050                                deleteOld = true;
1051                            }
1052
1053                            // Log current value of "unknown sources" setting
1054                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1055                                getUnknownSourcesSettings());
1056                        }
1057                        // Force a gc to clear up things
1058                        Runtime.getRuntime().gc();
1059                        // We delete after a gc for applications  on sdcard.
1060                        if (deleteOld) {
1061                            synchronized (mInstallLock) {
1062                                res.removedInfo.args.doPostDeleteLI(true);
1063                            }
1064                        }
1065                        if (args.observer != null) {
1066                            try {
1067                                Bundle extras = extrasForInstallResult(res);
1068                                args.observer.onPackageInstalled(res.name, res.returnCode,
1069                                        res.returnMsg, extras);
1070                            } catch (RemoteException e) {
1071                                Slog.i(TAG, "Observer no longer exists.");
1072                            }
1073                        }
1074                    } else {
1075                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1076                    }
1077                } break;
1078                case UPDATED_MEDIA_STATUS: {
1079                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1080                    boolean reportStatus = msg.arg1 == 1;
1081                    boolean doGc = msg.arg2 == 1;
1082                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1083                    if (doGc) {
1084                        // Force a gc to clear up stale containers.
1085                        Runtime.getRuntime().gc();
1086                    }
1087                    if (msg.obj != null) {
1088                        @SuppressWarnings("unchecked")
1089                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1090                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1091                        // Unload containers
1092                        unloadAllContainers(args);
1093                    }
1094                    if (reportStatus) {
1095                        try {
1096                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1097                            PackageHelper.getMountService().finishMediaUpdate();
1098                        } catch (RemoteException e) {
1099                            Log.e(TAG, "MountService not running?");
1100                        }
1101                    }
1102                } break;
1103                case WRITE_SETTINGS: {
1104                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1105                    synchronized (mPackages) {
1106                        removeMessages(WRITE_SETTINGS);
1107                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1108                        mSettings.writeLPr();
1109                        mDirtyUsers.clear();
1110                    }
1111                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                } break;
1113                case WRITE_PACKAGE_RESTRICTIONS: {
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1115                    synchronized (mPackages) {
1116                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1117                        for (int userId : mDirtyUsers) {
1118                            mSettings.writePackageRestrictionsLPr(userId);
1119                        }
1120                        mDirtyUsers.clear();
1121                    }
1122                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1123                } break;
1124                case CHECK_PENDING_VERIFICATION: {
1125                    final int verificationId = msg.arg1;
1126                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1127
1128                    if ((state != null) && !state.timeoutExtended()) {
1129                        final InstallArgs args = state.getInstallArgs();
1130                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1131
1132                        Slog.i(TAG, "Verification timed out for " + originUri);
1133                        mPendingVerification.remove(verificationId);
1134
1135                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1136
1137                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1138                            Slog.i(TAG, "Continuing with installation of " + originUri);
1139                            state.setVerifierResponse(Binder.getCallingUid(),
1140                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1141                            broadcastPackageVerified(verificationId, originUri,
1142                                    PackageManager.VERIFICATION_ALLOW,
1143                                    state.getInstallArgs().getUser());
1144                            try {
1145                                ret = args.copyApk(mContainerService, true);
1146                            } catch (RemoteException e) {
1147                                Slog.e(TAG, "Could not contact the ContainerService");
1148                            }
1149                        } else {
1150                            broadcastPackageVerified(verificationId, originUri,
1151                                    PackageManager.VERIFICATION_REJECT,
1152                                    state.getInstallArgs().getUser());
1153                        }
1154
1155                        processPendingInstall(args, ret);
1156                        mHandler.sendEmptyMessage(MCS_UNBIND);
1157                    }
1158                    break;
1159                }
1160                case PACKAGE_VERIFIED: {
1161                    final int verificationId = msg.arg1;
1162
1163                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1164                    if (state == null) {
1165                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1166                        break;
1167                    }
1168
1169                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1170
1171                    state.setVerifierResponse(response.callerUid, response.code);
1172
1173                    if (state.isVerificationComplete()) {
1174                        mPendingVerification.remove(verificationId);
1175
1176                        final InstallArgs args = state.getInstallArgs();
1177                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1178
1179                        int ret;
1180                        if (state.isInstallAllowed()) {
1181                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1182                            broadcastPackageVerified(verificationId, originUri,
1183                                    response.code, state.getInstallArgs().getUser());
1184                            try {
1185                                ret = args.copyApk(mContainerService, true);
1186                            } catch (RemoteException e) {
1187                                Slog.e(TAG, "Could not contact the ContainerService");
1188                            }
1189                        } else {
1190                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1191                        }
1192
1193                        processPendingInstall(args, ret);
1194
1195                        mHandler.sendEmptyMessage(MCS_UNBIND);
1196                    }
1197
1198                    break;
1199                }
1200            }
1201        }
1202    }
1203
1204    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1205        Bundle extras = null;
1206        switch (res.returnCode) {
1207            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1208                extras = new Bundle();
1209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1210                        res.origPermission);
1211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1212                        res.origPackage);
1213                break;
1214            }
1215        }
1216        return extras;
1217    }
1218
1219    void scheduleWriteSettingsLocked() {
1220        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1221            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1222        }
1223    }
1224
1225    void scheduleWritePackageRestrictionsLocked(int userId) {
1226        if (!sUserManager.exists(userId)) return;
1227        mDirtyUsers.add(userId);
1228        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1229            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1230        }
1231    }
1232
1233    public static final PackageManagerService main(Context context, Installer installer,
1234            boolean factoryTest, boolean onlyCore) {
1235        PackageManagerService m = new PackageManagerService(context, installer,
1236                factoryTest, onlyCore);
1237        ServiceManager.addService("package", m);
1238        return m;
1239    }
1240
1241    static String[] splitString(String str, char sep) {
1242        int count = 1;
1243        int i = 0;
1244        while ((i=str.indexOf(sep, i)) >= 0) {
1245            count++;
1246            i++;
1247        }
1248
1249        String[] res = new String[count];
1250        i=0;
1251        count = 0;
1252        int lastI=0;
1253        while ((i=str.indexOf(sep, i)) >= 0) {
1254            res[count] = str.substring(lastI, i);
1255            count++;
1256            i++;
1257            lastI = i;
1258        }
1259        res[count] = str.substring(lastI, str.length());
1260        return res;
1261    }
1262
1263    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1264        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1265                Context.DISPLAY_SERVICE);
1266        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1267    }
1268
1269    public PackageManagerService(Context context, Installer installer,
1270            boolean factoryTest, boolean onlyCore) {
1271        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1272                SystemClock.uptimeMillis());
1273
1274        if (mSdkVersion <= 0) {
1275            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1276        }
1277
1278        mContext = context;
1279        mFactoryTest = factoryTest;
1280        mOnlyCore = onlyCore;
1281        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1282        mMetrics = new DisplayMetrics();
1283        mSettings = new Settings(context);
1284        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1285                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1287                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1288        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1289                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1290        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1291                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1292        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1293                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1294        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1295                ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED);
1296
1297        String separateProcesses = SystemProperties.get("debug.separate_processes");
1298        if (separateProcesses != null && separateProcesses.length() > 0) {
1299            if ("*".equals(separateProcesses)) {
1300                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1301                mSeparateProcesses = null;
1302                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1303            } else {
1304                mDefParseFlags = 0;
1305                mSeparateProcesses = separateProcesses.split(",");
1306                Slog.w(TAG, "Running with debug.separate_processes: "
1307                        + separateProcesses);
1308            }
1309        } else {
1310            mDefParseFlags = 0;
1311            mSeparateProcesses = null;
1312        }
1313
1314        mInstaller = installer;
1315
1316        getDefaultDisplayMetrics(context, mMetrics);
1317
1318        SystemConfig systemConfig = SystemConfig.getInstance();
1319        mGlobalGids = systemConfig.getGlobalGids();
1320        mSystemPermissions = systemConfig.getSystemPermissions();
1321        mAvailableFeatures = systemConfig.getAvailableFeatures();
1322
1323        synchronized (mInstallLock) {
1324        // writer
1325        synchronized (mPackages) {
1326            mHandlerThread = new ServiceThread(TAG,
1327                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1328            mHandlerThread.start();
1329            mHandler = new PackageHandler(mHandlerThread.getLooper());
1330            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1331
1332            File dataDir = Environment.getDataDirectory();
1333            mAppDataDir = new File(dataDir, "data");
1334            mAppInstallDir = new File(dataDir, "app");
1335            mAppLib32InstallDir = new File(dataDir, "app-lib");
1336            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1337            mUserAppDataDir = new File(dataDir, "user");
1338            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1339
1340            sUserManager = new UserManagerService(context, this,
1341                    mInstallLock, mPackages);
1342
1343            // Propagate permission configuration in to package manager.
1344            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1345                    = systemConfig.getPermissions();
1346            for (int i=0; i<permConfig.size(); i++) {
1347                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1348                BasePermission bp = mSettings.mPermissions.get(perm.name);
1349                if (bp == null) {
1350                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1351                    mSettings.mPermissions.put(perm.name, bp);
1352                }
1353                if (perm.gids != null) {
1354                    bp.gids = appendInts(bp.gids, perm.gids);
1355                }
1356            }
1357
1358            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1359            for (int i=0; i<libConfig.size(); i++) {
1360                mSharedLibraries.put(libConfig.keyAt(i),
1361                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1362            }
1363
1364            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1365
1366            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1367                    mSdkVersion, mOnlyCore);
1368
1369            String customResolverActivity = Resources.getSystem().getString(
1370                    R.string.config_customResolverActivity);
1371            if (TextUtils.isEmpty(customResolverActivity)) {
1372                customResolverActivity = null;
1373            } else {
1374                mCustomResolverComponentName = ComponentName.unflattenFromString(
1375                        customResolverActivity);
1376            }
1377
1378            long startTime = SystemClock.uptimeMillis();
1379
1380            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1381                    startTime);
1382
1383            // Set flag to monitor and not change apk file paths when
1384            // scanning install directories.
1385            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1386
1387            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1388
1389            /**
1390             * Add everything in the in the boot class path to the
1391             * list of process files because dexopt will have been run
1392             * if necessary during zygote startup.
1393             */
1394            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1395            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1396
1397            if (bootClassPath != null) {
1398                String[] bootClassPathElements = splitString(bootClassPath, ':');
1399                for (String element : bootClassPathElements) {
1400                    alreadyDexOpted.add(element);
1401                }
1402            } else {
1403                Slog.w(TAG, "No BOOTCLASSPATH found!");
1404            }
1405
1406            if (systemServerClassPath != null) {
1407                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1408                for (String element : systemServerClassPathElements) {
1409                    alreadyDexOpted.add(element);
1410                }
1411            } else {
1412                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1413            }
1414
1415            boolean didDexOptLibraryOrTool = false;
1416
1417            final List<String> allInstructionSets = getAllInstructionSets();
1418            final String[] dexCodeInstructionSets =
1419                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1420
1421            /**
1422             * Ensure all external libraries have had dexopt run on them.
1423             */
1424            if (mSharedLibraries.size() > 0) {
1425                // NOTE: For now, we're compiling these system "shared libraries"
1426                // (and framework jars) into all available architectures. It's possible
1427                // to compile them only when we come across an app that uses them (there's
1428                // already logic for that in scanPackageLI) but that adds some complexity.
1429                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1430                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1431                        final String lib = libEntry.path;
1432                        if (lib == null) {
1433                            continue;
1434                        }
1435
1436                        try {
1437                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1438                                                                                 dexCodeInstructionSet,
1439                                                                                 false);
1440                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1441                                alreadyDexOpted.add(lib);
1442
1443                                // The list of "shared libraries" we have at this point is
1444                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1445                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1446                                } else {
1447                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1448                                }
1449                                didDexOptLibraryOrTool = true;
1450                            }
1451                        } catch (FileNotFoundException e) {
1452                            Slog.w(TAG, "Library not found: " + lib);
1453                        } catch (IOException e) {
1454                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1455                                    + e.getMessage());
1456                        }
1457                    }
1458                }
1459            }
1460
1461            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1462
1463            // Gross hack for now: we know this file doesn't contain any
1464            // code, so don't dexopt it to avoid the resulting log spew.
1465            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1466
1467            // Gross hack for now: we know this file is only part of
1468            // the boot class path for art, so don't dexopt it to
1469            // avoid the resulting log spew.
1470            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1471
1472            /**
1473             * And there are a number of commands implemented in Java, which
1474             * we currently need to do the dexopt on so that they can be
1475             * run from a non-root shell.
1476             */
1477            String[] frameworkFiles = frameworkDir.list();
1478            if (frameworkFiles != null) {
1479                // TODO: We could compile these only for the most preferred ABI. We should
1480                // first double check that the dex files for these commands are not referenced
1481                // by other system apps.
1482                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1483                    for (int i=0; i<frameworkFiles.length; i++) {
1484                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1485                        String path = libPath.getPath();
1486                        // Skip the file if we already did it.
1487                        if (alreadyDexOpted.contains(path)) {
1488                            continue;
1489                        }
1490                        // Skip the file if it is not a type we want to dexopt.
1491                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1492                            continue;
1493                        }
1494                        try {
1495                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1496                                                                                 dexCodeInstructionSet,
1497                                                                                 false);
1498                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1499                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1500                                didDexOptLibraryOrTool = true;
1501                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1502                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1503                                didDexOptLibraryOrTool = true;
1504                            }
1505                        } catch (FileNotFoundException e) {
1506                            Slog.w(TAG, "Jar not found: " + path);
1507                        } catch (IOException e) {
1508                            Slog.w(TAG, "Exception reading jar: " + path, e);
1509                        }
1510                    }
1511                }
1512            }
1513
1514            // Collect vendor overlay packages.
1515            // (Do this before scanning any apps.)
1516            // For security and version matching reason, only consider
1517            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1518            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1519            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1520                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1521
1522            // Find base frameworks (resource packages without code).
1523            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1524                    | PackageParser.PARSE_IS_SYSTEM_DIR
1525                    | PackageParser.PARSE_IS_PRIVILEGED,
1526                    scanFlags | SCAN_NO_DEX, 0);
1527
1528            // Collected privileged system packages.
1529            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1530            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1531                    | PackageParser.PARSE_IS_SYSTEM_DIR
1532                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1533
1534            // Collect ordinary system packages.
1535            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1536            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1537                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1538
1539            // Collect all vendor packages.
1540            File vendorAppDir = new File("/vendor/app");
1541            try {
1542                vendorAppDir = vendorAppDir.getCanonicalFile();
1543            } catch (IOException e) {
1544                // failed to look up canonical path, continue with original one
1545            }
1546            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1547                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1548
1549            // Collect all OEM packages.
1550            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1551            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1553
1554            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1555            mInstaller.moveFiles();
1556
1557            // Prune any system packages that no longer exist.
1558            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1559            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1560            if (!mOnlyCore) {
1561                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1562                while (psit.hasNext()) {
1563                    PackageSetting ps = psit.next();
1564
1565                    /*
1566                     * If this is not a system app, it can't be a
1567                     * disable system app.
1568                     */
1569                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1570                        continue;
1571                    }
1572
1573                    /*
1574                     * If the package is scanned, it's not erased.
1575                     */
1576                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1577                    if (scannedPkg != null) {
1578                        /*
1579                         * If the system app is both scanned and in the
1580                         * disabled packages list, then it must have been
1581                         * added via OTA. Remove it from the currently
1582                         * scanned package so the previously user-installed
1583                         * application can be scanned.
1584                         */
1585                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1586                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1587                                    + ps.name + "; removing system app.  Last known codePath="
1588                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1589                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1590                                    + scannedPkg.mVersionCode);
1591                            removePackageLI(ps, true);
1592                            expectingBetter.put(ps.name, ps.codePath);
1593                        }
1594
1595                        continue;
1596                    }
1597
1598                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1599                        psit.remove();
1600                        logCriticalInfo(Log.WARN, "System package " + ps.name
1601                                + " no longer exists; wiping its data");
1602                        removeDataDirsLI(ps.name);
1603                    } else {
1604                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1605                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1606                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1607                        }
1608                    }
1609                }
1610            }
1611
1612            //look for any incomplete package installations
1613            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1614            //clean up list
1615            for(int i = 0; i < deletePkgsList.size(); i++) {
1616                //clean up here
1617                cleanupInstallFailedPackage(deletePkgsList.get(i));
1618            }
1619            //delete tmp files
1620            deleteTempPackageFiles();
1621
1622            // Remove any shared userIDs that have no associated packages
1623            mSettings.pruneSharedUsersLPw();
1624
1625            if (!mOnlyCore) {
1626                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1627                        SystemClock.uptimeMillis());
1628                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1629
1630                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1631                        scanFlags, 0);
1632
1633                /**
1634                 * Remove disable package settings for any updated system
1635                 * apps that were removed via an OTA. If they're not a
1636                 * previously-updated app, remove them completely.
1637                 * Otherwise, just revoke their system-level permissions.
1638                 */
1639                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1640                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1641                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1642
1643                    String msg;
1644                    if (deletedPkg == null) {
1645                        msg = "Updated system package " + deletedAppName
1646                                + " no longer exists; wiping its data";
1647                        removeDataDirsLI(deletedAppName);
1648                    } else {
1649                        msg = "Updated system app + " + deletedAppName
1650                                + " no longer present; removing system privileges for "
1651                                + deletedAppName;
1652
1653                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1654
1655                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1656                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1657                    }
1658                    logCriticalInfo(Log.WARN, msg);
1659                }
1660
1661                /**
1662                 * Make sure all system apps that we expected to appear on
1663                 * the userdata partition actually showed up. If they never
1664                 * appeared, crawl back and revive the system version.
1665                 */
1666                for (int i = 0; i < expectingBetter.size(); i++) {
1667                    final String packageName = expectingBetter.keyAt(i);
1668                    if (!mPackages.containsKey(packageName)) {
1669                        final File scanFile = expectingBetter.valueAt(i);
1670
1671                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1672                                + " but never showed up; reverting to system");
1673
1674                        final int reparseFlags;
1675                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1676                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1677                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1678                                    | PackageParser.PARSE_IS_PRIVILEGED;
1679                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1680                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1681                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1682                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1683                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1684                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1685                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1686                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1687                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1688                        } else {
1689                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1690                            continue;
1691                        }
1692
1693                        mSettings.enableSystemPackageLPw(packageName);
1694
1695                        try {
1696                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1697                        } catch (PackageManagerException e) {
1698                            Slog.e(TAG, "Failed to parse original system package: "
1699                                    + e.getMessage());
1700                        }
1701                    }
1702                }
1703            }
1704
1705            // Now that we know all of the shared libraries, update all clients to have
1706            // the correct library paths.
1707            updateAllSharedLibrariesLPw();
1708
1709            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1710                // NOTE: We ignore potential failures here during a system scan (like
1711                // the rest of the commands above) because there's precious little we
1712                // can do about it. A settings error is reported, though.
1713                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1714                        false /* force dexopt */, false /* defer dexopt */);
1715            }
1716
1717            // Now that we know all the packages we are keeping,
1718            // read and update their last usage times.
1719            mPackageUsage.readLP();
1720
1721            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1722                    SystemClock.uptimeMillis());
1723            Slog.i(TAG, "Time to scan packages: "
1724                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1725                    + " seconds");
1726
1727            // If the platform SDK has changed since the last time we booted,
1728            // we need to re-grant app permission to catch any new ones that
1729            // appear.  This is really a hack, and means that apps can in some
1730            // cases get permissions that the user didn't initially explicitly
1731            // allow...  it would be nice to have some better way to handle
1732            // this situation.
1733            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1734                    != mSdkVersion;
1735            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1736                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1737                    + "; regranting permissions for internal storage");
1738            mSettings.mInternalSdkPlatform = mSdkVersion;
1739
1740            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1741                    | (regrantPermissions
1742                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1743                            : 0));
1744
1745            // If this is the first boot, and it is a normal boot, then
1746            // we need to initialize the default preferred apps.
1747            if (!mRestoredSettings && !onlyCore) {
1748                mSettings.readDefaultPreferredAppsLPw(this, 0);
1749            }
1750
1751            // If this is first boot after an OTA, and a normal boot, then
1752            // we need to clear code cache directories.
1753            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1754                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1755                for (String pkgName : mSettings.mPackages.keySet()) {
1756                    deleteCodeCacheDirsLI(pkgName);
1757                }
1758                mSettings.mFingerprint = Build.FINGERPRINT;
1759            }
1760
1761            // All the changes are done during package scanning.
1762            mSettings.updateInternalDatabaseVersion();
1763
1764            // can downgrade to reader
1765            mSettings.writeLPr();
1766
1767            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1768                    SystemClock.uptimeMillis());
1769
1770
1771            mRequiredVerifierPackage = getRequiredVerifierLPr();
1772        } // synchronized (mPackages)
1773        } // synchronized (mInstallLock)
1774
1775        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1776
1777        // Now after opening every single application zip, make sure they
1778        // are all flushed.  Not really needed, but keeps things nice and
1779        // tidy.
1780        Runtime.getRuntime().gc();
1781    }
1782
1783    @Override
1784    public boolean isFirstBoot() {
1785        return !mRestoredSettings;
1786    }
1787
1788    @Override
1789    public boolean isOnlyCoreApps() {
1790        return mOnlyCore;
1791    }
1792
1793    private String getRequiredVerifierLPr() {
1794        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1795        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1796                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1797
1798        String requiredVerifier = null;
1799
1800        final int N = receivers.size();
1801        for (int i = 0; i < N; i++) {
1802            final ResolveInfo info = receivers.get(i);
1803
1804            if (info.activityInfo == null) {
1805                continue;
1806            }
1807
1808            final String packageName = info.activityInfo.packageName;
1809
1810            final PackageSetting ps = mSettings.mPackages.get(packageName);
1811            if (ps == null) {
1812                continue;
1813            }
1814
1815            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1816            if (!gp.grantedPermissions
1817                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1818                continue;
1819            }
1820
1821            if (requiredVerifier != null) {
1822                throw new RuntimeException("There can be only one required verifier");
1823            }
1824
1825            requiredVerifier = packageName;
1826        }
1827
1828        return requiredVerifier;
1829    }
1830
1831    @Override
1832    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1833            throws RemoteException {
1834        try {
1835            return super.onTransact(code, data, reply, flags);
1836        } catch (RuntimeException e) {
1837            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1838                Slog.wtf(TAG, "Package Manager Crash", e);
1839            }
1840            throw e;
1841        }
1842    }
1843
1844    void cleanupInstallFailedPackage(PackageSetting ps) {
1845        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1846
1847        removeDataDirsLI(ps.name);
1848        if (ps.codePath != null) {
1849            if (ps.codePath.isDirectory()) {
1850                FileUtils.deleteContents(ps.codePath);
1851            }
1852            ps.codePath.delete();
1853        }
1854        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1855            if (ps.resourcePath.isDirectory()) {
1856                FileUtils.deleteContents(ps.resourcePath);
1857            }
1858            ps.resourcePath.delete();
1859        }
1860        mSettings.removePackageLPw(ps.name);
1861    }
1862
1863    static int[] appendInts(int[] cur, int[] add) {
1864        if (add == null) return cur;
1865        if (cur == null) return add;
1866        final int N = add.length;
1867        for (int i=0; i<N; i++) {
1868            cur = appendInt(cur, add[i]);
1869        }
1870        return cur;
1871    }
1872
1873    static int[] removeInts(int[] cur, int[] rem) {
1874        if (rem == null) return cur;
1875        if (cur == null) return cur;
1876        final int N = rem.length;
1877        for (int i=0; i<N; i++) {
1878            cur = removeInt(cur, rem[i]);
1879        }
1880        return cur;
1881    }
1882
1883    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1884        if (!sUserManager.exists(userId)) return null;
1885        final PackageSetting ps = (PackageSetting) p.mExtras;
1886        if (ps == null) {
1887            return null;
1888        }
1889        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1890        final PackageUserState state = ps.readUserState(userId);
1891        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1892                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1893                state, userId);
1894    }
1895
1896    @Override
1897    public boolean isPackageAvailable(String packageName, int userId) {
1898        if (!sUserManager.exists(userId)) return false;
1899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1900        synchronized (mPackages) {
1901            PackageParser.Package p = mPackages.get(packageName);
1902            if (p != null) {
1903                final PackageSetting ps = (PackageSetting) p.mExtras;
1904                if (ps != null) {
1905                    final PackageUserState state = ps.readUserState(userId);
1906                    if (state != null) {
1907                        return PackageParser.isAvailable(state);
1908                    }
1909                }
1910            }
1911        }
1912        return false;
1913    }
1914
1915    @Override
1916    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1917        if (!sUserManager.exists(userId)) return null;
1918        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1919        // reader
1920        synchronized (mPackages) {
1921            PackageParser.Package p = mPackages.get(packageName);
1922            if (DEBUG_PACKAGE_INFO)
1923                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1924            if (p != null) {
1925                return generatePackageInfo(p, flags, userId);
1926            }
1927            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1928                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1929            }
1930        }
1931        return null;
1932    }
1933
1934    @Override
1935    public String[] currentToCanonicalPackageNames(String[] names) {
1936        String[] out = new String[names.length];
1937        // reader
1938        synchronized (mPackages) {
1939            for (int i=names.length-1; i>=0; i--) {
1940                PackageSetting ps = mSettings.mPackages.get(names[i]);
1941                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1942            }
1943        }
1944        return out;
1945    }
1946
1947    @Override
1948    public String[] canonicalToCurrentPackageNames(String[] names) {
1949        String[] out = new String[names.length];
1950        // reader
1951        synchronized (mPackages) {
1952            for (int i=names.length-1; i>=0; i--) {
1953                String cur = mSettings.mRenamedPackages.get(names[i]);
1954                out[i] = cur != null ? cur : names[i];
1955            }
1956        }
1957        return out;
1958    }
1959
1960    @Override
1961    public int getPackageUid(String packageName, int userId) {
1962        if (!sUserManager.exists(userId)) return -1;
1963        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1964        // reader
1965        synchronized (mPackages) {
1966            PackageParser.Package p = mPackages.get(packageName);
1967            if(p != null) {
1968                return UserHandle.getUid(userId, p.applicationInfo.uid);
1969            }
1970            PackageSetting ps = mSettings.mPackages.get(packageName);
1971            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1972                return -1;
1973            }
1974            p = ps.pkg;
1975            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1976        }
1977    }
1978
1979    @Override
1980    public int[] getPackageGids(String packageName) {
1981        // reader
1982        synchronized (mPackages) {
1983            PackageParser.Package p = mPackages.get(packageName);
1984            if (DEBUG_PACKAGE_INFO)
1985                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1986            if (p != null) {
1987                final PackageSetting ps = (PackageSetting)p.mExtras;
1988                return ps.getGids();
1989            }
1990        }
1991        // stupid thing to indicate an error.
1992        return new int[0];
1993    }
1994
1995    static final PermissionInfo generatePermissionInfo(
1996            BasePermission bp, int flags) {
1997        if (bp.perm != null) {
1998            return PackageParser.generatePermissionInfo(bp.perm, flags);
1999        }
2000        PermissionInfo pi = new PermissionInfo();
2001        pi.name = bp.name;
2002        pi.packageName = bp.sourcePackage;
2003        pi.nonLocalizedLabel = bp.name;
2004        pi.protectionLevel = bp.protectionLevel;
2005        return pi;
2006    }
2007
2008    @Override
2009    public PermissionInfo getPermissionInfo(String name, int flags) {
2010        // reader
2011        synchronized (mPackages) {
2012            final BasePermission p = mSettings.mPermissions.get(name);
2013            if (p != null) {
2014                return generatePermissionInfo(p, flags);
2015            }
2016            return null;
2017        }
2018    }
2019
2020    @Override
2021    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2022        // reader
2023        synchronized (mPackages) {
2024            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2025            for (BasePermission p : mSettings.mPermissions.values()) {
2026                if (group == null) {
2027                    if (p.perm == null || p.perm.info.group == null) {
2028                        out.add(generatePermissionInfo(p, flags));
2029                    }
2030                } else {
2031                    if (p.perm != null && group.equals(p.perm.info.group)) {
2032                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2033                    }
2034                }
2035            }
2036
2037            if (out.size() > 0) {
2038                return out;
2039            }
2040            return mPermissionGroups.containsKey(group) ? out : null;
2041        }
2042    }
2043
2044    @Override
2045    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2046        // reader
2047        synchronized (mPackages) {
2048            return PackageParser.generatePermissionGroupInfo(
2049                    mPermissionGroups.get(name), flags);
2050        }
2051    }
2052
2053    @Override
2054    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2055        // reader
2056        synchronized (mPackages) {
2057            final int N = mPermissionGroups.size();
2058            ArrayList<PermissionGroupInfo> out
2059                    = new ArrayList<PermissionGroupInfo>(N);
2060            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2061                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2062            }
2063            return out;
2064        }
2065    }
2066
2067    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2068            int userId) {
2069        if (!sUserManager.exists(userId)) return null;
2070        PackageSetting ps = mSettings.mPackages.get(packageName);
2071        if (ps != null) {
2072            if (ps.pkg == null) {
2073                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2074                        flags, userId);
2075                if (pInfo != null) {
2076                    return pInfo.applicationInfo;
2077                }
2078                return null;
2079            }
2080            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2081                    ps.readUserState(userId), userId);
2082        }
2083        return null;
2084    }
2085
2086    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2087            int userId) {
2088        if (!sUserManager.exists(userId)) return null;
2089        PackageSetting ps = mSettings.mPackages.get(packageName);
2090        if (ps != null) {
2091            PackageParser.Package pkg = ps.pkg;
2092            if (pkg == null) {
2093                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2094                    return null;
2095                }
2096                // Only data remains, so we aren't worried about code paths
2097                pkg = new PackageParser.Package(packageName);
2098                pkg.applicationInfo.packageName = packageName;
2099                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2100                pkg.applicationInfo.privateFlags = ps.pkgPrivateFlags;
2101                pkg.applicationInfo.dataDir =
2102                        getDataPathForPackage(packageName, 0).getPath();
2103                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2104                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2105            }
2106            return generatePackageInfo(pkg, flags, userId);
2107        }
2108        return null;
2109    }
2110
2111    @Override
2112    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2113        if (!sUserManager.exists(userId)) return null;
2114        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2115        // writer
2116        synchronized (mPackages) {
2117            PackageParser.Package p = mPackages.get(packageName);
2118            if (DEBUG_PACKAGE_INFO) Log.v(
2119                    TAG, "getApplicationInfo " + packageName
2120                    + ": " + p);
2121            if (p != null) {
2122                PackageSetting ps = mSettings.mPackages.get(packageName);
2123                if (ps == null) return null;
2124                // Note: isEnabledLP() does not apply here - always return info
2125                return PackageParser.generateApplicationInfo(
2126                        p, flags, ps.readUserState(userId), userId);
2127            }
2128            if ("android".equals(packageName)||"system".equals(packageName)) {
2129                return mAndroidApplication;
2130            }
2131            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2132                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2133            }
2134        }
2135        return null;
2136    }
2137
2138
2139    @Override
2140    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2141        mContext.enforceCallingOrSelfPermission(
2142                android.Manifest.permission.CLEAR_APP_CACHE, null);
2143        // Queue up an async operation since clearing cache may take a little while.
2144        mHandler.post(new Runnable() {
2145            public void run() {
2146                mHandler.removeCallbacks(this);
2147                int retCode = -1;
2148                synchronized (mInstallLock) {
2149                    retCode = mInstaller.freeCache(freeStorageSize);
2150                    if (retCode < 0) {
2151                        Slog.w(TAG, "Couldn't clear application caches");
2152                    }
2153                }
2154                if (observer != null) {
2155                    try {
2156                        observer.onRemoveCompleted(null, (retCode >= 0));
2157                    } catch (RemoteException e) {
2158                        Slog.w(TAG, "RemoveException when invoking call back");
2159                    }
2160                }
2161            }
2162        });
2163    }
2164
2165    @Override
2166    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2167        mContext.enforceCallingOrSelfPermission(
2168                android.Manifest.permission.CLEAR_APP_CACHE, null);
2169        // Queue up an async operation since clearing cache may take a little while.
2170        mHandler.post(new Runnable() {
2171            public void run() {
2172                mHandler.removeCallbacks(this);
2173                int retCode = -1;
2174                synchronized (mInstallLock) {
2175                    retCode = mInstaller.freeCache(freeStorageSize);
2176                    if (retCode < 0) {
2177                        Slog.w(TAG, "Couldn't clear application caches");
2178                    }
2179                }
2180                if(pi != null) {
2181                    try {
2182                        // Callback via pending intent
2183                        int code = (retCode >= 0) ? 1 : 0;
2184                        pi.sendIntent(null, code, null,
2185                                null, null);
2186                    } catch (SendIntentException e1) {
2187                        Slog.i(TAG, "Failed to send pending intent");
2188                    }
2189                }
2190            }
2191        });
2192    }
2193
2194    void freeStorage(long freeStorageSize) throws IOException {
2195        synchronized (mInstallLock) {
2196            if (mInstaller.freeCache(freeStorageSize) < 0) {
2197                throw new IOException("Failed to free enough space");
2198            }
2199        }
2200    }
2201
2202    @Override
2203    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2204        if (!sUserManager.exists(userId)) return null;
2205        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2206        synchronized (mPackages) {
2207            PackageParser.Activity a = mActivities.mActivities.get(component);
2208
2209            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2210            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2211                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2212                if (ps == null) return null;
2213                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2214                        userId);
2215            }
2216            if (mResolveComponentName.equals(component)) {
2217                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2218                        new PackageUserState(), userId);
2219            }
2220        }
2221        return null;
2222    }
2223
2224    @Override
2225    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2226            String resolvedType) {
2227        synchronized (mPackages) {
2228            PackageParser.Activity a = mActivities.mActivities.get(component);
2229            if (a == null) {
2230                return false;
2231            }
2232            for (int i=0; i<a.intents.size(); i++) {
2233                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2234                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2235                    return true;
2236                }
2237            }
2238            return false;
2239        }
2240    }
2241
2242    @Override
2243    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2244        if (!sUserManager.exists(userId)) return null;
2245        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2246        synchronized (mPackages) {
2247            PackageParser.Activity a = mReceivers.mActivities.get(component);
2248            if (DEBUG_PACKAGE_INFO) Log.v(
2249                TAG, "getReceiverInfo " + component + ": " + a);
2250            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2251                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2252                if (ps == null) return null;
2253                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2254                        userId);
2255            }
2256        }
2257        return null;
2258    }
2259
2260    @Override
2261    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2262        if (!sUserManager.exists(userId)) return null;
2263        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2264        synchronized (mPackages) {
2265            PackageParser.Service s = mServices.mServices.get(component);
2266            if (DEBUG_PACKAGE_INFO) Log.v(
2267                TAG, "getServiceInfo " + component + ": " + s);
2268            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2269                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2270                if (ps == null) return null;
2271                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2272                        userId);
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2280        if (!sUserManager.exists(userId)) return null;
2281        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2282        synchronized (mPackages) {
2283            PackageParser.Provider p = mProviders.mProviders.get(component);
2284            if (DEBUG_PACKAGE_INFO) Log.v(
2285                TAG, "getProviderInfo " + component + ": " + p);
2286            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2287                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2288                if (ps == null) return null;
2289                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2290                        userId);
2291            }
2292        }
2293        return null;
2294    }
2295
2296    @Override
2297    public String[] getSystemSharedLibraryNames() {
2298        Set<String> libSet;
2299        synchronized (mPackages) {
2300            libSet = mSharedLibraries.keySet();
2301            int size = libSet.size();
2302            if (size > 0) {
2303                String[] libs = new String[size];
2304                libSet.toArray(libs);
2305                return libs;
2306            }
2307        }
2308        return null;
2309    }
2310
2311    @Override
2312    public FeatureInfo[] getSystemAvailableFeatures() {
2313        Collection<FeatureInfo> featSet;
2314        synchronized (mPackages) {
2315            featSet = mAvailableFeatures.values();
2316            int size = featSet.size();
2317            if (size > 0) {
2318                FeatureInfo[] features = new FeatureInfo[size+1];
2319                featSet.toArray(features);
2320                FeatureInfo fi = new FeatureInfo();
2321                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2322                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2323                features[size] = fi;
2324                return features;
2325            }
2326        }
2327        return null;
2328    }
2329
2330    @Override
2331    public boolean hasSystemFeature(String name) {
2332        synchronized (mPackages) {
2333            return mAvailableFeatures.containsKey(name);
2334        }
2335    }
2336
2337    private void checkValidCaller(int uid, int userId) {
2338        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2339            return;
2340
2341        throw new SecurityException("Caller uid=" + uid
2342                + " is not privileged to communicate with user=" + userId);
2343    }
2344
2345    @Override
2346    public int checkPermission(String permName, String pkgName) {
2347        synchronized (mPackages) {
2348            PackageParser.Package p = mPackages.get(pkgName);
2349            if (p != null && p.mExtras != null) {
2350                PackageSetting ps = (PackageSetting)p.mExtras;
2351                if (ps.sharedUser != null) {
2352                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2353                        return PackageManager.PERMISSION_GRANTED;
2354                    }
2355                } else if (ps.grantedPermissions.contains(permName)) {
2356                    return PackageManager.PERMISSION_GRANTED;
2357                }
2358            }
2359        }
2360        return PackageManager.PERMISSION_DENIED;
2361    }
2362
2363    @Override
2364    public int checkUidPermission(String permName, int uid) {
2365        synchronized (mPackages) {
2366            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2367            if (obj != null) {
2368                GrantedPermissions gp = (GrantedPermissions)obj;
2369                if (gp.grantedPermissions.contains(permName)) {
2370                    return PackageManager.PERMISSION_GRANTED;
2371                }
2372            } else {
2373                HashSet<String> perms = mSystemPermissions.get(uid);
2374                if (perms != null && perms.contains(permName)) {
2375                    return PackageManager.PERMISSION_GRANTED;
2376                }
2377            }
2378        }
2379        return PackageManager.PERMISSION_DENIED;
2380    }
2381
2382    /**
2383     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2384     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2385     * @param checkShell TODO(yamasani):
2386     * @param message the message to log on security exception
2387     */
2388    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2389            boolean checkShell, String message) {
2390        if (userId < 0) {
2391            throw new IllegalArgumentException("Invalid userId " + userId);
2392        }
2393        if (checkShell) {
2394            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2395        }
2396        if (userId == UserHandle.getUserId(callingUid)) return;
2397        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2398            if (requireFullPermission) {
2399                mContext.enforceCallingOrSelfPermission(
2400                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2401            } else {
2402                try {
2403                    mContext.enforceCallingOrSelfPermission(
2404                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2405                } catch (SecurityException se) {
2406                    mContext.enforceCallingOrSelfPermission(
2407                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2408                }
2409            }
2410        }
2411    }
2412
2413    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2414        if (callingUid == Process.SHELL_UID) {
2415            if (userHandle >= 0
2416                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2417                throw new SecurityException("Shell does not have permission to access user "
2418                        + userHandle);
2419            } else if (userHandle < 0) {
2420                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2421                        + Debug.getCallers(3));
2422            }
2423        }
2424    }
2425
2426    private BasePermission findPermissionTreeLP(String permName) {
2427        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2428            if (permName.startsWith(bp.name) &&
2429                    permName.length() > bp.name.length() &&
2430                    permName.charAt(bp.name.length()) == '.') {
2431                return bp;
2432            }
2433        }
2434        return null;
2435    }
2436
2437    private BasePermission checkPermissionTreeLP(String permName) {
2438        if (permName != null) {
2439            BasePermission bp = findPermissionTreeLP(permName);
2440            if (bp != null) {
2441                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2442                    return bp;
2443                }
2444                throw new SecurityException("Calling uid "
2445                        + Binder.getCallingUid()
2446                        + " is not allowed to add to permission tree "
2447                        + bp.name + " owned by uid " + bp.uid);
2448            }
2449        }
2450        throw new SecurityException("No permission tree found for " + permName);
2451    }
2452
2453    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2454        if (s1 == null) {
2455            return s2 == null;
2456        }
2457        if (s2 == null) {
2458            return false;
2459        }
2460        if (s1.getClass() != s2.getClass()) {
2461            return false;
2462        }
2463        return s1.equals(s2);
2464    }
2465
2466    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2467        if (pi1.icon != pi2.icon) return false;
2468        if (pi1.logo != pi2.logo) return false;
2469        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2470        if (!compareStrings(pi1.name, pi2.name)) return false;
2471        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2472        // We'll take care of setting this one.
2473        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2474        // These are not currently stored in settings.
2475        //if (!compareStrings(pi1.group, pi2.group)) return false;
2476        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2477        //if (pi1.labelRes != pi2.labelRes) return false;
2478        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2479        return true;
2480    }
2481
2482    int permissionInfoFootprint(PermissionInfo info) {
2483        int size = info.name.length();
2484        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2485        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2486        return size;
2487    }
2488
2489    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2490        int size = 0;
2491        for (BasePermission perm : mSettings.mPermissions.values()) {
2492            if (perm.uid == tree.uid) {
2493                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2494            }
2495        }
2496        return size;
2497    }
2498
2499    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2500        // We calculate the max size of permissions defined by this uid and throw
2501        // if that plus the size of 'info' would exceed our stated maximum.
2502        if (tree.uid != Process.SYSTEM_UID) {
2503            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2504            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2505                throw new SecurityException("Permission tree size cap exceeded");
2506            }
2507        }
2508    }
2509
2510    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2511        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2512            throw new SecurityException("Label must be specified in permission");
2513        }
2514        BasePermission tree = checkPermissionTreeLP(info.name);
2515        BasePermission bp = mSettings.mPermissions.get(info.name);
2516        boolean added = bp == null;
2517        boolean changed = true;
2518        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2519        if (added) {
2520            enforcePermissionCapLocked(info, tree);
2521            bp = new BasePermission(info.name, tree.sourcePackage,
2522                    BasePermission.TYPE_DYNAMIC);
2523        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2524            throw new SecurityException(
2525                    "Not allowed to modify non-dynamic permission "
2526                    + info.name);
2527        } else {
2528            if (bp.protectionLevel == fixedLevel
2529                    && bp.perm.owner.equals(tree.perm.owner)
2530                    && bp.uid == tree.uid
2531                    && comparePermissionInfos(bp.perm.info, info)) {
2532                changed = false;
2533            }
2534        }
2535        bp.protectionLevel = fixedLevel;
2536        info = new PermissionInfo(info);
2537        info.protectionLevel = fixedLevel;
2538        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2539        bp.perm.info.packageName = tree.perm.info.packageName;
2540        bp.uid = tree.uid;
2541        if (added) {
2542            mSettings.mPermissions.put(info.name, bp);
2543        }
2544        if (changed) {
2545            if (!async) {
2546                mSettings.writeLPr();
2547            } else {
2548                scheduleWriteSettingsLocked();
2549            }
2550        }
2551        return added;
2552    }
2553
2554    @Override
2555    public boolean addPermission(PermissionInfo info) {
2556        synchronized (mPackages) {
2557            return addPermissionLocked(info, false);
2558        }
2559    }
2560
2561    @Override
2562    public boolean addPermissionAsync(PermissionInfo info) {
2563        synchronized (mPackages) {
2564            return addPermissionLocked(info, true);
2565        }
2566    }
2567
2568    @Override
2569    public void removePermission(String name) {
2570        synchronized (mPackages) {
2571            checkPermissionTreeLP(name);
2572            BasePermission bp = mSettings.mPermissions.get(name);
2573            if (bp != null) {
2574                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2575                    throw new SecurityException(
2576                            "Not allowed to modify non-dynamic permission "
2577                            + name);
2578                }
2579                mSettings.mPermissions.remove(name);
2580                mSettings.writeLPr();
2581            }
2582        }
2583    }
2584
2585    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2586        int index = pkg.requestedPermissions.indexOf(bp.name);
2587        if (index == -1) {
2588            throw new SecurityException("Package " + pkg.packageName
2589                    + " has not requested permission " + bp.name);
2590        }
2591        boolean isNormal =
2592                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2593                        == PermissionInfo.PROTECTION_NORMAL);
2594        boolean isDangerous =
2595                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2596                        == PermissionInfo.PROTECTION_DANGEROUS);
2597        boolean isDevelopment =
2598                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2599
2600        if (!isNormal && !isDangerous && !isDevelopment) {
2601            throw new SecurityException("Permission " + bp.name
2602                    + " is not a changeable permission type");
2603        }
2604
2605        if (isNormal || isDangerous) {
2606            if (pkg.requestedPermissionsRequired.get(index)) {
2607                throw new SecurityException("Can't change " + bp.name
2608                        + ". It is required by the application");
2609            }
2610        }
2611    }
2612
2613    @Override
2614    public void grantPermission(String packageName, String permissionName) {
2615        mContext.enforceCallingOrSelfPermission(
2616                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2617        synchronized (mPackages) {
2618            final PackageParser.Package pkg = mPackages.get(packageName);
2619            if (pkg == null) {
2620                throw new IllegalArgumentException("Unknown package: " + packageName);
2621            }
2622            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2623            if (bp == null) {
2624                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2625            }
2626
2627            checkGrantRevokePermissions(pkg, bp);
2628
2629            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2630            if (ps == null) {
2631                return;
2632            }
2633            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2634            if (gp.grantedPermissions.add(permissionName)) {
2635                if (ps.haveGids) {
2636                    gp.gids = appendInts(gp.gids, bp.gids);
2637                }
2638                mSettings.writeLPr();
2639            }
2640        }
2641    }
2642
2643    @Override
2644    public void revokePermission(String packageName, String permissionName) {
2645        int changedAppId = -1;
2646
2647        synchronized (mPackages) {
2648            final PackageParser.Package pkg = mPackages.get(packageName);
2649            if (pkg == null) {
2650                throw new IllegalArgumentException("Unknown package: " + packageName);
2651            }
2652            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2653                mContext.enforceCallingOrSelfPermission(
2654                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2655            }
2656            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2657            if (bp == null) {
2658                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2659            }
2660
2661            checkGrantRevokePermissions(pkg, bp);
2662
2663            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2664            if (ps == null) {
2665                return;
2666            }
2667            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2668            if (gp.grantedPermissions.remove(permissionName)) {
2669                gp.grantedPermissions.remove(permissionName);
2670                if (ps.haveGids) {
2671                    gp.gids = removeInts(gp.gids, bp.gids);
2672                }
2673                mSettings.writeLPr();
2674                changedAppId = ps.appId;
2675            }
2676        }
2677
2678        if (changedAppId >= 0) {
2679            // We changed the perm on someone, kill its processes.
2680            IActivityManager am = ActivityManagerNative.getDefault();
2681            if (am != null) {
2682                final int callingUserId = UserHandle.getCallingUserId();
2683                final long ident = Binder.clearCallingIdentity();
2684                try {
2685                    //XXX we should only revoke for the calling user's app permissions,
2686                    // but for now we impact all users.
2687                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2688                    //        "revoke " + permissionName);
2689                    int[] users = sUserManager.getUserIds();
2690                    for (int user : users) {
2691                        am.killUid(UserHandle.getUid(user, changedAppId),
2692                                "revoke " + permissionName);
2693                    }
2694                } catch (RemoteException e) {
2695                } finally {
2696                    Binder.restoreCallingIdentity(ident);
2697                }
2698            }
2699        }
2700    }
2701
2702    @Override
2703    public boolean isProtectedBroadcast(String actionName) {
2704        synchronized (mPackages) {
2705            return mProtectedBroadcasts.contains(actionName);
2706        }
2707    }
2708
2709    @Override
2710    public int checkSignatures(String pkg1, String pkg2) {
2711        synchronized (mPackages) {
2712            final PackageParser.Package p1 = mPackages.get(pkg1);
2713            final PackageParser.Package p2 = mPackages.get(pkg2);
2714            if (p1 == null || p1.mExtras == null
2715                    || p2 == null || p2.mExtras == null) {
2716                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2717            }
2718            return compareSignatures(p1.mSignatures, p2.mSignatures);
2719        }
2720    }
2721
2722    @Override
2723    public int checkUidSignatures(int uid1, int uid2) {
2724        // Map to base uids.
2725        uid1 = UserHandle.getAppId(uid1);
2726        uid2 = UserHandle.getAppId(uid2);
2727        // reader
2728        synchronized (mPackages) {
2729            Signature[] s1;
2730            Signature[] s2;
2731            Object obj = mSettings.getUserIdLPr(uid1);
2732            if (obj != null) {
2733                if (obj instanceof SharedUserSetting) {
2734                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2735                } else if (obj instanceof PackageSetting) {
2736                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2737                } else {
2738                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2739                }
2740            } else {
2741                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2742            }
2743            obj = mSettings.getUserIdLPr(uid2);
2744            if (obj != null) {
2745                if (obj instanceof SharedUserSetting) {
2746                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2747                } else if (obj instanceof PackageSetting) {
2748                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2749                } else {
2750                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2751                }
2752            } else {
2753                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2754            }
2755            return compareSignatures(s1, s2);
2756        }
2757    }
2758
2759    /**
2760     * Compares two sets of signatures. Returns:
2761     * <br />
2762     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2763     * <br />
2764     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2765     * <br />
2766     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2767     * <br />
2768     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2769     * <br />
2770     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2771     */
2772    static int compareSignatures(Signature[] s1, Signature[] s2) {
2773        if (s1 == null) {
2774            return s2 == null
2775                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2776                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2777        }
2778
2779        if (s2 == null) {
2780            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2781        }
2782
2783        if (s1.length != s2.length) {
2784            return PackageManager.SIGNATURE_NO_MATCH;
2785        }
2786
2787        // Since both signature sets are of size 1, we can compare without HashSets.
2788        if (s1.length == 1) {
2789            return s1[0].equals(s2[0]) ?
2790                    PackageManager.SIGNATURE_MATCH :
2791                    PackageManager.SIGNATURE_NO_MATCH;
2792        }
2793
2794        HashSet<Signature> set1 = new HashSet<Signature>();
2795        for (Signature sig : s1) {
2796            set1.add(sig);
2797        }
2798        HashSet<Signature> set2 = new HashSet<Signature>();
2799        for (Signature sig : s2) {
2800            set2.add(sig);
2801        }
2802        // Make sure s2 contains all signatures in s1.
2803        if (set1.equals(set2)) {
2804            return PackageManager.SIGNATURE_MATCH;
2805        }
2806        return PackageManager.SIGNATURE_NO_MATCH;
2807    }
2808
2809    /**
2810     * If the database version for this type of package (internal storage or
2811     * external storage) is less than the version where package signatures
2812     * were updated, return true.
2813     */
2814    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2815        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2816                DatabaseVersion.SIGNATURE_END_ENTITY))
2817                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2818                        DatabaseVersion.SIGNATURE_END_ENTITY));
2819    }
2820
2821    /**
2822     * Used for backward compatibility to make sure any packages with
2823     * certificate chains get upgraded to the new style. {@code existingSigs}
2824     * will be in the old format (since they were stored on disk from before the
2825     * system upgrade) and {@code scannedSigs} will be in the newer format.
2826     */
2827    private int compareSignaturesCompat(PackageSignatures existingSigs,
2828            PackageParser.Package scannedPkg) {
2829        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2830            return PackageManager.SIGNATURE_NO_MATCH;
2831        }
2832
2833        HashSet<Signature> existingSet = new HashSet<Signature>();
2834        for (Signature sig : existingSigs.mSignatures) {
2835            existingSet.add(sig);
2836        }
2837        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2838        for (Signature sig : scannedPkg.mSignatures) {
2839            try {
2840                Signature[] chainSignatures = sig.getChainSignatures();
2841                for (Signature chainSig : chainSignatures) {
2842                    scannedCompatSet.add(chainSig);
2843                }
2844            } catch (CertificateEncodingException e) {
2845                scannedCompatSet.add(sig);
2846            }
2847        }
2848        /*
2849         * Make sure the expanded scanned set contains all signatures in the
2850         * existing one.
2851         */
2852        if (scannedCompatSet.equals(existingSet)) {
2853            // Migrate the old signatures to the new scheme.
2854            existingSigs.assignSignatures(scannedPkg.mSignatures);
2855            // The new KeySets will be re-added later in the scanning process.
2856            synchronized (mPackages) {
2857                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2858            }
2859            return PackageManager.SIGNATURE_MATCH;
2860        }
2861        return PackageManager.SIGNATURE_NO_MATCH;
2862    }
2863
2864    @Override
2865    public String[] getPackagesForUid(int uid) {
2866        uid = UserHandle.getAppId(uid);
2867        // reader
2868        synchronized (mPackages) {
2869            Object obj = mSettings.getUserIdLPr(uid);
2870            if (obj instanceof SharedUserSetting) {
2871                final SharedUserSetting sus = (SharedUserSetting) obj;
2872                final int N = sus.packages.size();
2873                final String[] res = new String[N];
2874                final Iterator<PackageSetting> it = sus.packages.iterator();
2875                int i = 0;
2876                while (it.hasNext()) {
2877                    res[i++] = it.next().name;
2878                }
2879                return res;
2880            } else if (obj instanceof PackageSetting) {
2881                final PackageSetting ps = (PackageSetting) obj;
2882                return new String[] { ps.name };
2883            }
2884        }
2885        return null;
2886    }
2887
2888    @Override
2889    public String getNameForUid(int uid) {
2890        // reader
2891        synchronized (mPackages) {
2892            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2893            if (obj instanceof SharedUserSetting) {
2894                final SharedUserSetting sus = (SharedUserSetting) obj;
2895                return sus.name + ":" + sus.userId;
2896            } else if (obj instanceof PackageSetting) {
2897                final PackageSetting ps = (PackageSetting) obj;
2898                return ps.name;
2899            }
2900        }
2901        return null;
2902    }
2903
2904    @Override
2905    public int getUidForSharedUser(String sharedUserName) {
2906        if(sharedUserName == null) {
2907            return -1;
2908        }
2909        // reader
2910        synchronized (mPackages) {
2911            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false);
2912            if (suid == null) {
2913                return -1;
2914            }
2915            return suid.userId;
2916        }
2917    }
2918
2919    @Override
2920    public int getFlagsForUid(int uid) {
2921        synchronized (mPackages) {
2922            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2923            if (obj instanceof SharedUserSetting) {
2924                final SharedUserSetting sus = (SharedUserSetting) obj;
2925                return sus.pkgFlags;
2926            } else if (obj instanceof PackageSetting) {
2927                final PackageSetting ps = (PackageSetting) obj;
2928                return ps.pkgFlags;
2929            }
2930        }
2931        return 0;
2932    }
2933
2934    @Override
2935    public int getPrivateFlagsForUid(int uid) {
2936        synchronized (mPackages) {
2937            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2938            if (obj instanceof SharedUserSetting) {
2939                final SharedUserSetting sus = (SharedUserSetting) obj;
2940                return sus.pkgPrivateFlags;
2941            } else if (obj instanceof PackageSetting) {
2942                final PackageSetting ps = (PackageSetting) obj;
2943                return ps.pkgPrivateFlags;
2944            }
2945        }
2946        return 0;
2947    }
2948
2949    @Override
2950    public boolean isUidPrivileged(int uid) {
2951        uid = UserHandle.getAppId(uid);
2952        // reader
2953        synchronized (mPackages) {
2954            Object obj = mSettings.getUserIdLPr(uid);
2955            if (obj instanceof SharedUserSetting) {
2956                final SharedUserSetting sus = (SharedUserSetting) obj;
2957                final Iterator<PackageSetting> it = sus.packages.iterator();
2958                while (it.hasNext()) {
2959                    if (it.next().isPrivileged()) {
2960                        return true;
2961                    }
2962                }
2963            } else if (obj instanceof PackageSetting) {
2964                final PackageSetting ps = (PackageSetting) obj;
2965                return ps.isPrivileged();
2966            }
2967        }
2968        return false;
2969    }
2970
2971    @Override
2972    public String[] getAppOpPermissionPackages(String permissionName) {
2973        synchronized (mPackages) {
2974            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2975            if (pkgs == null) {
2976                return null;
2977            }
2978            return pkgs.toArray(new String[pkgs.size()]);
2979        }
2980    }
2981
2982    @Override
2983    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2984            int flags, int userId) {
2985        if (!sUserManager.exists(userId)) return null;
2986        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2987        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2988        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2989    }
2990
2991    @Override
2992    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2993            IntentFilter filter, int match, ComponentName activity) {
2994        final int userId = UserHandle.getCallingUserId();
2995        if (DEBUG_PREFERRED) {
2996            Log.v(TAG, "setLastChosenActivity intent=" + intent
2997                + " resolvedType=" + resolvedType
2998                + " flags=" + flags
2999                + " filter=" + filter
3000                + " match=" + match
3001                + " activity=" + activity);
3002            filter.dump(new PrintStreamPrinter(System.out), "    ");
3003        }
3004        intent.setComponent(null);
3005        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3006        // Find any earlier preferred or last chosen entries and nuke them
3007        findPreferredActivity(intent, resolvedType,
3008                flags, query, 0, false, true, false, userId);
3009        // Add the new activity as the last chosen for this filter
3010        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3011                "Setting last chosen");
3012    }
3013
3014    @Override
3015    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3016        final int userId = UserHandle.getCallingUserId();
3017        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3018        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3019        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3020                false, false, false, userId);
3021    }
3022
3023    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3024            int flags, List<ResolveInfo> query, int userId) {
3025        if (query != null) {
3026            final int N = query.size();
3027            if (N == 1) {
3028                return query.get(0);
3029            } else if (N > 1) {
3030                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3031                // If there is more than one activity with the same priority,
3032                // then let the user decide between them.
3033                ResolveInfo r0 = query.get(0);
3034                ResolveInfo r1 = query.get(1);
3035                if (DEBUG_INTENT_MATCHING || debug) {
3036                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3037                            + r1.activityInfo.name + "=" + r1.priority);
3038                }
3039                // If the first activity has a higher priority, or a different
3040                // default, then it is always desireable to pick it.
3041                if (r0.priority != r1.priority
3042                        || r0.preferredOrder != r1.preferredOrder
3043                        || r0.isDefault != r1.isDefault) {
3044                    return query.get(0);
3045                }
3046                // If we have saved a preference for a preferred activity for
3047                // this Intent, use that.
3048                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3049                        flags, query, r0.priority, true, false, debug, userId);
3050                if (ri != null) {
3051                    return ri;
3052                }
3053                if (userId != 0) {
3054                    ri = new ResolveInfo(mResolveInfo);
3055                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3056                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3057                            ri.activityInfo.applicationInfo);
3058                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3059                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3060                    return ri;
3061                }
3062                return mResolveInfo;
3063            }
3064        }
3065        return null;
3066    }
3067
3068    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3069            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3070        final int N = query.size();
3071        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3072                .get(userId);
3073        // Get the list of persistent preferred activities that handle the intent
3074        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3075        List<PersistentPreferredActivity> pprefs = ppir != null
3076                ? ppir.queryIntent(intent, resolvedType,
3077                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3078                : null;
3079        if (pprefs != null && pprefs.size() > 0) {
3080            final int M = pprefs.size();
3081            for (int i=0; i<M; i++) {
3082                final PersistentPreferredActivity ppa = pprefs.get(i);
3083                if (DEBUG_PREFERRED || debug) {
3084                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3085                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3086                            + "\n  component=" + ppa.mComponent);
3087                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3088                }
3089                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3090                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3091                if (DEBUG_PREFERRED || debug) {
3092                    Slog.v(TAG, "Found persistent preferred activity:");
3093                    if (ai != null) {
3094                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3095                    } else {
3096                        Slog.v(TAG, "  null");
3097                    }
3098                }
3099                if (ai == null) {
3100                    // This previously registered persistent preferred activity
3101                    // component is no longer known. Ignore it and do NOT remove it.
3102                    continue;
3103                }
3104                for (int j=0; j<N; j++) {
3105                    final ResolveInfo ri = query.get(j);
3106                    if (!ri.activityInfo.applicationInfo.packageName
3107                            .equals(ai.applicationInfo.packageName)) {
3108                        continue;
3109                    }
3110                    if (!ri.activityInfo.name.equals(ai.name)) {
3111                        continue;
3112                    }
3113                    //  Found a persistent preference that can handle the intent.
3114                    if (DEBUG_PREFERRED || debug) {
3115                        Slog.v(TAG, "Returning persistent preferred activity: " +
3116                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3117                    }
3118                    return ri;
3119                }
3120            }
3121        }
3122        return null;
3123    }
3124
3125    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3126            List<ResolveInfo> query, int priority, boolean always,
3127            boolean removeMatches, boolean debug, int userId) {
3128        if (!sUserManager.exists(userId)) return null;
3129        // writer
3130        synchronized (mPackages) {
3131            if (intent.getSelector() != null) {
3132                intent = intent.getSelector();
3133            }
3134            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3135
3136            // Try to find a matching persistent preferred activity.
3137            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3138                    debug, userId);
3139
3140            // If a persistent preferred activity matched, use it.
3141            if (pri != null) {
3142                return pri;
3143            }
3144
3145            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3146            // Get the list of preferred activities that handle the intent
3147            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3148            List<PreferredActivity> prefs = pir != null
3149                    ? pir.queryIntent(intent, resolvedType,
3150                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3151                    : null;
3152            if (prefs != null && prefs.size() > 0) {
3153                boolean changed = false;
3154                try {
3155                    // First figure out how good the original match set is.
3156                    // We will only allow preferred activities that came
3157                    // from the same match quality.
3158                    int match = 0;
3159
3160                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3161
3162                    final int N = query.size();
3163                    for (int j=0; j<N; j++) {
3164                        final ResolveInfo ri = query.get(j);
3165                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3166                                + ": 0x" + Integer.toHexString(match));
3167                        if (ri.match > match) {
3168                            match = ri.match;
3169                        }
3170                    }
3171
3172                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3173                            + Integer.toHexString(match));
3174
3175                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3176                    final int M = prefs.size();
3177                    for (int i=0; i<M; i++) {
3178                        final PreferredActivity pa = prefs.get(i);
3179                        if (DEBUG_PREFERRED || debug) {
3180                            Slog.v(TAG, "Checking PreferredActivity ds="
3181                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3182                                    + "\n  component=" + pa.mPref.mComponent);
3183                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3184                        }
3185                        if (pa.mPref.mMatch != match) {
3186                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3187                                    + Integer.toHexString(pa.mPref.mMatch));
3188                            continue;
3189                        }
3190                        // If it's not an "always" type preferred activity and that's what we're
3191                        // looking for, skip it.
3192                        if (always && !pa.mPref.mAlways) {
3193                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3194                            continue;
3195                        }
3196                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3197                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3198                        if (DEBUG_PREFERRED || debug) {
3199                            Slog.v(TAG, "Found preferred activity:");
3200                            if (ai != null) {
3201                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3202                            } else {
3203                                Slog.v(TAG, "  null");
3204                            }
3205                        }
3206                        if (ai == null) {
3207                            // This previously registered preferred activity
3208                            // component is no longer known.  Most likely an update
3209                            // to the app was installed and in the new version this
3210                            // component no longer exists.  Clean it up by removing
3211                            // it from the preferred activities list, and skip it.
3212                            Slog.w(TAG, "Removing dangling preferred activity: "
3213                                    + pa.mPref.mComponent);
3214                            pir.removeFilter(pa);
3215                            changed = true;
3216                            continue;
3217                        }
3218                        for (int j=0; j<N; j++) {
3219                            final ResolveInfo ri = query.get(j);
3220                            if (!ri.activityInfo.applicationInfo.packageName
3221                                    .equals(ai.applicationInfo.packageName)) {
3222                                continue;
3223                            }
3224                            if (!ri.activityInfo.name.equals(ai.name)) {
3225                                continue;
3226                            }
3227
3228                            if (removeMatches) {
3229                                pir.removeFilter(pa);
3230                                changed = true;
3231                                if (DEBUG_PREFERRED) {
3232                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3233                                }
3234                                break;
3235                            }
3236
3237                            // Okay we found a previously set preferred or last chosen app.
3238                            // If the result set is different from when this
3239                            // was created, we need to clear it and re-ask the
3240                            // user their preference, if we're looking for an "always" type entry.
3241                            if (always && !pa.mPref.sameSet(query, priority)) {
3242                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3243                                        + intent + " type " + resolvedType);
3244                                if (DEBUG_PREFERRED) {
3245                                    Slog.v(TAG, "Removing preferred activity since set changed "
3246                                            + pa.mPref.mComponent);
3247                                }
3248                                pir.removeFilter(pa);
3249                                // Re-add the filter as a "last chosen" entry (!always)
3250                                PreferredActivity lastChosen = new PreferredActivity(
3251                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3252                                pir.addFilter(lastChosen);
3253                                changed = true;
3254                                return null;
3255                            }
3256
3257                            // Yay! Either the set matched or we're looking for the last chosen
3258                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3259                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3260                            return ri;
3261                        }
3262                    }
3263                } finally {
3264                    if (changed) {
3265                        if (DEBUG_PREFERRED) {
3266                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3267                        }
3268                        mSettings.writePackageRestrictionsLPr(userId);
3269                    }
3270                }
3271            }
3272        }
3273        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3274        return null;
3275    }
3276
3277    /*
3278     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3279     */
3280    @Override
3281    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3282            int targetUserId) {
3283        mContext.enforceCallingOrSelfPermission(
3284                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3285        List<CrossProfileIntentFilter> matches =
3286                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3287        if (matches != null) {
3288            int size = matches.size();
3289            for (int i = 0; i < size; i++) {
3290                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3291            }
3292        }
3293        return false;
3294    }
3295
3296    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3297            String resolvedType, int userId) {
3298        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3299        if (resolver != null) {
3300            return resolver.queryIntent(intent, resolvedType, false, userId);
3301        }
3302        return null;
3303    }
3304
3305    @Override
3306    public List<ResolveInfo> queryIntentActivities(Intent intent,
3307            String resolvedType, int flags, int userId) {
3308        if (!sUserManager.exists(userId)) return Collections.emptyList();
3309        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3310        ComponentName comp = intent.getComponent();
3311        if (comp == null) {
3312            if (intent.getSelector() != null) {
3313                intent = intent.getSelector();
3314                comp = intent.getComponent();
3315            }
3316        }
3317
3318        if (comp != null) {
3319            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3320            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3321            if (ai != null) {
3322                final ResolveInfo ri = new ResolveInfo();
3323                ri.activityInfo = ai;
3324                list.add(ri);
3325            }
3326            return list;
3327        }
3328
3329        // reader
3330        synchronized (mPackages) {
3331            final String pkgName = intent.getPackage();
3332            if (pkgName == null) {
3333                List<CrossProfileIntentFilter> matchingFilters =
3334                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3335                // Check for results that need to skip the current profile.
3336                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3337                        resolvedType, flags, userId);
3338                if (resolveInfo != null) {
3339                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3340                    result.add(resolveInfo);
3341                    return result;
3342                }
3343                // Check for cross profile results.
3344                resolveInfo = queryCrossProfileIntents(
3345                        matchingFilters, intent, resolvedType, flags, userId);
3346
3347                // Check for results in the current profile.
3348                List<ResolveInfo> result = mActivities.queryIntent(
3349                        intent, resolvedType, flags, userId);
3350                if (resolveInfo != null) {
3351                    result.add(resolveInfo);
3352                    Collections.sort(result, mResolvePrioritySorter);
3353                }
3354                return result;
3355            }
3356            final PackageParser.Package pkg = mPackages.get(pkgName);
3357            if (pkg != null) {
3358                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3359                        pkg.activities, userId);
3360            }
3361            return new ArrayList<ResolveInfo>();
3362        }
3363    }
3364
3365    private ResolveInfo querySkipCurrentProfileIntents(
3366            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3367            int flags, int sourceUserId) {
3368        if (matchingFilters != null) {
3369            int size = matchingFilters.size();
3370            for (int i = 0; i < size; i ++) {
3371                CrossProfileIntentFilter filter = matchingFilters.get(i);
3372                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3373                    // Checking if there are activities in the target user that can handle the
3374                    // intent.
3375                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3376                            flags, sourceUserId);
3377                    if (resolveInfo != null) {
3378                        return resolveInfo;
3379                    }
3380                }
3381            }
3382        }
3383        return null;
3384    }
3385
3386    // Return matching ResolveInfo if any for skip current profile intent filters.
3387    private ResolveInfo queryCrossProfileIntents(
3388            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3389            int flags, int sourceUserId) {
3390        if (matchingFilters != null) {
3391            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3392            // match the same intent. For performance reasons, it is better not to
3393            // run queryIntent twice for the same userId
3394            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3395            int size = matchingFilters.size();
3396            for (int i = 0; i < size; i++) {
3397                CrossProfileIntentFilter filter = matchingFilters.get(i);
3398                int targetUserId = filter.getTargetUserId();
3399                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3400                        && !alreadyTriedUserIds.get(targetUserId)) {
3401                    // Checking if there are activities in the target user that can handle the
3402                    // intent.
3403                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3404                            flags, sourceUserId);
3405                    if (resolveInfo != null) return resolveInfo;
3406                    alreadyTriedUserIds.put(targetUserId, true);
3407                }
3408            }
3409        }
3410        return null;
3411    }
3412
3413    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3414            String resolvedType, int flags, int sourceUserId) {
3415        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3416                resolvedType, flags, filter.getTargetUserId());
3417        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3418            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3419        }
3420        return null;
3421    }
3422
3423    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3424            int sourceUserId, int targetUserId) {
3425        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3426        String className;
3427        if (targetUserId == UserHandle.USER_OWNER) {
3428            className = FORWARD_INTENT_TO_USER_OWNER;
3429        } else {
3430            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3431        }
3432        ComponentName forwardingActivityComponentName = new ComponentName(
3433                mAndroidApplication.packageName, className);
3434        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3435                sourceUserId);
3436        if (targetUserId == UserHandle.USER_OWNER) {
3437            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3438            forwardingResolveInfo.noResourceId = true;
3439        }
3440        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3441        forwardingResolveInfo.priority = 0;
3442        forwardingResolveInfo.preferredOrder = 0;
3443        forwardingResolveInfo.match = 0;
3444        forwardingResolveInfo.isDefault = true;
3445        forwardingResolveInfo.filter = filter;
3446        forwardingResolveInfo.targetUserId = targetUserId;
3447        return forwardingResolveInfo;
3448    }
3449
3450    @Override
3451    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3452            Intent[] specifics, String[] specificTypes, Intent intent,
3453            String resolvedType, int flags, int userId) {
3454        if (!sUserManager.exists(userId)) return Collections.emptyList();
3455        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3456                false, "query intent activity options");
3457        final String resultsAction = intent.getAction();
3458
3459        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3460                | PackageManager.GET_RESOLVED_FILTER, userId);
3461
3462        if (DEBUG_INTENT_MATCHING) {
3463            Log.v(TAG, "Query " + intent + ": " + results);
3464        }
3465
3466        int specificsPos = 0;
3467        int N;
3468
3469        // todo: note that the algorithm used here is O(N^2).  This
3470        // isn't a problem in our current environment, but if we start running
3471        // into situations where we have more than 5 or 10 matches then this
3472        // should probably be changed to something smarter...
3473
3474        // First we go through and resolve each of the specific items
3475        // that were supplied, taking care of removing any corresponding
3476        // duplicate items in the generic resolve list.
3477        if (specifics != null) {
3478            for (int i=0; i<specifics.length; i++) {
3479                final Intent sintent = specifics[i];
3480                if (sintent == null) {
3481                    continue;
3482                }
3483
3484                if (DEBUG_INTENT_MATCHING) {
3485                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3486                }
3487
3488                String action = sintent.getAction();
3489                if (resultsAction != null && resultsAction.equals(action)) {
3490                    // If this action was explicitly requested, then don't
3491                    // remove things that have it.
3492                    action = null;
3493                }
3494
3495                ResolveInfo ri = null;
3496                ActivityInfo ai = null;
3497
3498                ComponentName comp = sintent.getComponent();
3499                if (comp == null) {
3500                    ri = resolveIntent(
3501                        sintent,
3502                        specificTypes != null ? specificTypes[i] : null,
3503                            flags, userId);
3504                    if (ri == null) {
3505                        continue;
3506                    }
3507                    if (ri == mResolveInfo) {
3508                        // ACK!  Must do something better with this.
3509                    }
3510                    ai = ri.activityInfo;
3511                    comp = new ComponentName(ai.applicationInfo.packageName,
3512                            ai.name);
3513                } else {
3514                    ai = getActivityInfo(comp, flags, userId);
3515                    if (ai == null) {
3516                        continue;
3517                    }
3518                }
3519
3520                // Look for any generic query activities that are duplicates
3521                // of this specific one, and remove them from the results.
3522                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3523                N = results.size();
3524                int j;
3525                for (j=specificsPos; j<N; j++) {
3526                    ResolveInfo sri = results.get(j);
3527                    if ((sri.activityInfo.name.equals(comp.getClassName())
3528                            && sri.activityInfo.applicationInfo.packageName.equals(
3529                                    comp.getPackageName()))
3530                        || (action != null && sri.filter.matchAction(action))) {
3531                        results.remove(j);
3532                        if (DEBUG_INTENT_MATCHING) Log.v(
3533                            TAG, "Removing duplicate item from " + j
3534                            + " due to specific " + specificsPos);
3535                        if (ri == null) {
3536                            ri = sri;
3537                        }
3538                        j--;
3539                        N--;
3540                    }
3541                }
3542
3543                // Add this specific item to its proper place.
3544                if (ri == null) {
3545                    ri = new ResolveInfo();
3546                    ri.activityInfo = ai;
3547                }
3548                results.add(specificsPos, ri);
3549                ri.specificIndex = i;
3550                specificsPos++;
3551            }
3552        }
3553
3554        // Now we go through the remaining generic results and remove any
3555        // duplicate actions that are found here.
3556        N = results.size();
3557        for (int i=specificsPos; i<N-1; i++) {
3558            final ResolveInfo rii = results.get(i);
3559            if (rii.filter == null) {
3560                continue;
3561            }
3562
3563            // Iterate over all of the actions of this result's intent
3564            // filter...  typically this should be just one.
3565            final Iterator<String> it = rii.filter.actionsIterator();
3566            if (it == null) {
3567                continue;
3568            }
3569            while (it.hasNext()) {
3570                final String action = it.next();
3571                if (resultsAction != null && resultsAction.equals(action)) {
3572                    // If this action was explicitly requested, then don't
3573                    // remove things that have it.
3574                    continue;
3575                }
3576                for (int j=i+1; j<N; j++) {
3577                    final ResolveInfo rij = results.get(j);
3578                    if (rij.filter != null && rij.filter.hasAction(action)) {
3579                        results.remove(j);
3580                        if (DEBUG_INTENT_MATCHING) Log.v(
3581                            TAG, "Removing duplicate item from " + j
3582                            + " due to action " + action + " at " + i);
3583                        j--;
3584                        N--;
3585                    }
3586                }
3587            }
3588
3589            // If the caller didn't request filter information, drop it now
3590            // so we don't have to marshall/unmarshall it.
3591            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3592                rii.filter = null;
3593            }
3594        }
3595
3596        // Filter out the caller activity if so requested.
3597        if (caller != null) {
3598            N = results.size();
3599            for (int i=0; i<N; i++) {
3600                ActivityInfo ainfo = results.get(i).activityInfo;
3601                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3602                        && caller.getClassName().equals(ainfo.name)) {
3603                    results.remove(i);
3604                    break;
3605                }
3606            }
3607        }
3608
3609        // If the caller didn't request filter information,
3610        // drop them now so we don't have to
3611        // marshall/unmarshall it.
3612        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3613            N = results.size();
3614            for (int i=0; i<N; i++) {
3615                results.get(i).filter = null;
3616            }
3617        }
3618
3619        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3620        return results;
3621    }
3622
3623    @Override
3624    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3625            int userId) {
3626        if (!sUserManager.exists(userId)) return Collections.emptyList();
3627        ComponentName comp = intent.getComponent();
3628        if (comp == null) {
3629            if (intent.getSelector() != null) {
3630                intent = intent.getSelector();
3631                comp = intent.getComponent();
3632            }
3633        }
3634        if (comp != null) {
3635            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3636            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3637            if (ai != null) {
3638                ResolveInfo ri = new ResolveInfo();
3639                ri.activityInfo = ai;
3640                list.add(ri);
3641            }
3642            return list;
3643        }
3644
3645        // reader
3646        synchronized (mPackages) {
3647            String pkgName = intent.getPackage();
3648            if (pkgName == null) {
3649                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3650            }
3651            final PackageParser.Package pkg = mPackages.get(pkgName);
3652            if (pkg != null) {
3653                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3654                        userId);
3655            }
3656            return null;
3657        }
3658    }
3659
3660    @Override
3661    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3662        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3663        if (!sUserManager.exists(userId)) return null;
3664        if (query != null) {
3665            if (query.size() >= 1) {
3666                // If there is more than one service with the same priority,
3667                // just arbitrarily pick the first one.
3668                return query.get(0);
3669            }
3670        }
3671        return null;
3672    }
3673
3674    @Override
3675    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3676            int userId) {
3677        if (!sUserManager.exists(userId)) return Collections.emptyList();
3678        ComponentName comp = intent.getComponent();
3679        if (comp == null) {
3680            if (intent.getSelector() != null) {
3681                intent = intent.getSelector();
3682                comp = intent.getComponent();
3683            }
3684        }
3685        if (comp != null) {
3686            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3687            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3688            if (si != null) {
3689                final ResolveInfo ri = new ResolveInfo();
3690                ri.serviceInfo = si;
3691                list.add(ri);
3692            }
3693            return list;
3694        }
3695
3696        // reader
3697        synchronized (mPackages) {
3698            String pkgName = intent.getPackage();
3699            if (pkgName == null) {
3700                return mServices.queryIntent(intent, resolvedType, flags, userId);
3701            }
3702            final PackageParser.Package pkg = mPackages.get(pkgName);
3703            if (pkg != null) {
3704                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3705                        userId);
3706            }
3707            return null;
3708        }
3709    }
3710
3711    @Override
3712    public List<ResolveInfo> queryIntentContentProviders(
3713            Intent intent, String resolvedType, int flags, int userId) {
3714        if (!sUserManager.exists(userId)) return Collections.emptyList();
3715        ComponentName comp = intent.getComponent();
3716        if (comp == null) {
3717            if (intent.getSelector() != null) {
3718                intent = intent.getSelector();
3719                comp = intent.getComponent();
3720            }
3721        }
3722        if (comp != null) {
3723            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3724            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3725            if (pi != null) {
3726                final ResolveInfo ri = new ResolveInfo();
3727                ri.providerInfo = pi;
3728                list.add(ri);
3729            }
3730            return list;
3731        }
3732
3733        // reader
3734        synchronized (mPackages) {
3735            String pkgName = intent.getPackage();
3736            if (pkgName == null) {
3737                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3738            }
3739            final PackageParser.Package pkg = mPackages.get(pkgName);
3740            if (pkg != null) {
3741                return mProviders.queryIntentForPackage(
3742                        intent, resolvedType, flags, pkg.providers, userId);
3743            }
3744            return null;
3745        }
3746    }
3747
3748    @Override
3749    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3750        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3751
3752        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3753
3754        // writer
3755        synchronized (mPackages) {
3756            ArrayList<PackageInfo> list;
3757            if (listUninstalled) {
3758                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3759                for (PackageSetting ps : mSettings.mPackages.values()) {
3760                    PackageInfo pi;
3761                    if (ps.pkg != null) {
3762                        pi = generatePackageInfo(ps.pkg, flags, userId);
3763                    } else {
3764                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3765                    }
3766                    if (pi != null) {
3767                        list.add(pi);
3768                    }
3769                }
3770            } else {
3771                list = new ArrayList<PackageInfo>(mPackages.size());
3772                for (PackageParser.Package p : mPackages.values()) {
3773                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3774                    if (pi != null) {
3775                        list.add(pi);
3776                    }
3777                }
3778            }
3779
3780            return new ParceledListSlice<PackageInfo>(list);
3781        }
3782    }
3783
3784    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3785            String[] permissions, boolean[] tmp, int flags, int userId) {
3786        int numMatch = 0;
3787        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3788        for (int i=0; i<permissions.length; i++) {
3789            if (gp.grantedPermissions.contains(permissions[i])) {
3790                tmp[i] = true;
3791                numMatch++;
3792            } else {
3793                tmp[i] = false;
3794            }
3795        }
3796        if (numMatch == 0) {
3797            return;
3798        }
3799        PackageInfo pi;
3800        if (ps.pkg != null) {
3801            pi = generatePackageInfo(ps.pkg, flags, userId);
3802        } else {
3803            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3804        }
3805        // The above might return null in cases of uninstalled apps or install-state
3806        // skew across users/profiles.
3807        if (pi != null) {
3808            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3809                if (numMatch == permissions.length) {
3810                    pi.requestedPermissions = permissions;
3811                } else {
3812                    pi.requestedPermissions = new String[numMatch];
3813                    numMatch = 0;
3814                    for (int i=0; i<permissions.length; i++) {
3815                        if (tmp[i]) {
3816                            pi.requestedPermissions[numMatch] = permissions[i];
3817                            numMatch++;
3818                        }
3819                    }
3820                }
3821            }
3822            list.add(pi);
3823        }
3824    }
3825
3826    @Override
3827    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3828            String[] permissions, int flags, int userId) {
3829        if (!sUserManager.exists(userId)) return null;
3830        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3831
3832        // writer
3833        synchronized (mPackages) {
3834            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3835            boolean[] tmpBools = new boolean[permissions.length];
3836            if (listUninstalled) {
3837                for (PackageSetting ps : mSettings.mPackages.values()) {
3838                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3839                }
3840            } else {
3841                for (PackageParser.Package pkg : mPackages.values()) {
3842                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3843                    if (ps != null) {
3844                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3845                                userId);
3846                    }
3847                }
3848            }
3849
3850            return new ParceledListSlice<PackageInfo>(list);
3851        }
3852    }
3853
3854    @Override
3855    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3856        if (!sUserManager.exists(userId)) return null;
3857        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3858
3859        // writer
3860        synchronized (mPackages) {
3861            ArrayList<ApplicationInfo> list;
3862            if (listUninstalled) {
3863                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3864                for (PackageSetting ps : mSettings.mPackages.values()) {
3865                    ApplicationInfo ai;
3866                    if (ps.pkg != null) {
3867                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3868                                ps.readUserState(userId), userId);
3869                    } else {
3870                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3871                    }
3872                    if (ai != null) {
3873                        list.add(ai);
3874                    }
3875                }
3876            } else {
3877                list = new ArrayList<ApplicationInfo>(mPackages.size());
3878                for (PackageParser.Package p : mPackages.values()) {
3879                    if (p.mExtras != null) {
3880                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3881                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3882                        if (ai != null) {
3883                            list.add(ai);
3884                        }
3885                    }
3886                }
3887            }
3888
3889            return new ParceledListSlice<ApplicationInfo>(list);
3890        }
3891    }
3892
3893    public List<ApplicationInfo> getPersistentApplications(int flags) {
3894        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3895
3896        // reader
3897        synchronized (mPackages) {
3898            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3899            final int userId = UserHandle.getCallingUserId();
3900            while (i.hasNext()) {
3901                final PackageParser.Package p = i.next();
3902                if (p.applicationInfo != null
3903                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3904                        && (!mSafeMode || isSystemApp(p))) {
3905                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3906                    if (ps != null) {
3907                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3908                                ps.readUserState(userId), userId);
3909                        if (ai != null) {
3910                            finalList.add(ai);
3911                        }
3912                    }
3913                }
3914            }
3915        }
3916
3917        return finalList;
3918    }
3919
3920    @Override
3921    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3922        if (!sUserManager.exists(userId)) return null;
3923        // reader
3924        synchronized (mPackages) {
3925            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3926            PackageSetting ps = provider != null
3927                    ? mSettings.mPackages.get(provider.owner.packageName)
3928                    : null;
3929            return ps != null
3930                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3931                    && (!mSafeMode || (provider.info.applicationInfo.flags
3932                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3933                    ? PackageParser.generateProviderInfo(provider, flags,
3934                            ps.readUserState(userId), userId)
3935                    : null;
3936        }
3937    }
3938
3939    /**
3940     * @deprecated
3941     */
3942    @Deprecated
3943    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3944        // reader
3945        synchronized (mPackages) {
3946            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3947                    .entrySet().iterator();
3948            final int userId = UserHandle.getCallingUserId();
3949            while (i.hasNext()) {
3950                Map.Entry<String, PackageParser.Provider> entry = i.next();
3951                PackageParser.Provider p = entry.getValue();
3952                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3953
3954                if (ps != null && p.syncable
3955                        && (!mSafeMode || (p.info.applicationInfo.flags
3956                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3957                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3958                            ps.readUserState(userId), userId);
3959                    if (info != null) {
3960                        outNames.add(entry.getKey());
3961                        outInfo.add(info);
3962                    }
3963                }
3964            }
3965        }
3966    }
3967
3968    @Override
3969    public List<ProviderInfo> queryContentProviders(String processName,
3970            int uid, int flags) {
3971        ArrayList<ProviderInfo> finalList = null;
3972        // reader
3973        synchronized (mPackages) {
3974            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3975            final int userId = processName != null ?
3976                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3977            while (i.hasNext()) {
3978                final PackageParser.Provider p = i.next();
3979                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3980                if (ps != null && p.info.authority != null
3981                        && (processName == null
3982                                || (p.info.processName.equals(processName)
3983                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3984                        && mSettings.isEnabledLPr(p.info, flags, userId)
3985                        && (!mSafeMode
3986                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3987                    if (finalList == null) {
3988                        finalList = new ArrayList<ProviderInfo>(3);
3989                    }
3990                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3991                            ps.readUserState(userId), userId);
3992                    if (info != null) {
3993                        finalList.add(info);
3994                    }
3995                }
3996            }
3997        }
3998
3999        if (finalList != null) {
4000            Collections.sort(finalList, mProviderInitOrderSorter);
4001        }
4002
4003        return finalList;
4004    }
4005
4006    @Override
4007    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4008            int flags) {
4009        // reader
4010        synchronized (mPackages) {
4011            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4012            return PackageParser.generateInstrumentationInfo(i, flags);
4013        }
4014    }
4015
4016    @Override
4017    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4018            int flags) {
4019        ArrayList<InstrumentationInfo> finalList =
4020            new ArrayList<InstrumentationInfo>();
4021
4022        // reader
4023        synchronized (mPackages) {
4024            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4025            while (i.hasNext()) {
4026                final PackageParser.Instrumentation p = i.next();
4027                if (targetPackage == null
4028                        || targetPackage.equals(p.info.targetPackage)) {
4029                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4030                            flags);
4031                    if (ii != null) {
4032                        finalList.add(ii);
4033                    }
4034                }
4035            }
4036        }
4037
4038        return finalList;
4039    }
4040
4041    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4042        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4043        if (overlays == null) {
4044            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4045            return;
4046        }
4047        for (PackageParser.Package opkg : overlays.values()) {
4048            // Not much to do if idmap fails: we already logged the error
4049            // and we certainly don't want to abort installation of pkg simply
4050            // because an overlay didn't fit properly. For these reasons,
4051            // ignore the return value of createIdmapForPackagePairLI.
4052            createIdmapForPackagePairLI(pkg, opkg);
4053        }
4054    }
4055
4056    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4057            PackageParser.Package opkg) {
4058        if (!opkg.mTrustedOverlay) {
4059            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4060                    opkg.baseCodePath + ": overlay not trusted");
4061            return false;
4062        }
4063        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4064        if (overlaySet == null) {
4065            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4066                    opkg.baseCodePath + " but target package has no known overlays");
4067            return false;
4068        }
4069        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4070        // TODO: generate idmap for split APKs
4071        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4072            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4073                    + opkg.baseCodePath);
4074            return false;
4075        }
4076        PackageParser.Package[] overlayArray =
4077            overlaySet.values().toArray(new PackageParser.Package[0]);
4078        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4079            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4080                return p1.mOverlayPriority - p2.mOverlayPriority;
4081            }
4082        };
4083        Arrays.sort(overlayArray, cmp);
4084
4085        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4086        int i = 0;
4087        for (PackageParser.Package p : overlayArray) {
4088            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4089        }
4090        return true;
4091    }
4092
4093    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4094        final File[] files = dir.listFiles();
4095        if (ArrayUtils.isEmpty(files)) {
4096            Log.d(TAG, "No files in app dir " + dir);
4097            return;
4098        }
4099
4100        if (DEBUG_PACKAGE_SCANNING) {
4101            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4102                    + " flags=0x" + Integer.toHexString(parseFlags));
4103        }
4104
4105        for (File file : files) {
4106            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4107                    && !PackageInstallerService.isStageName(file.getName());
4108            if (!isPackage) {
4109                // Ignore entries which are not packages
4110                continue;
4111            }
4112            try {
4113                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4114                        scanFlags, currentTime, null);
4115            } catch (PackageManagerException e) {
4116                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4117
4118                // Delete invalid userdata apps
4119                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4120                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4121                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4122                    if (file.isDirectory()) {
4123                        FileUtils.deleteContents(file);
4124                    }
4125                    file.delete();
4126                }
4127            }
4128        }
4129    }
4130
4131    private static File getSettingsProblemFile() {
4132        File dataDir = Environment.getDataDirectory();
4133        File systemDir = new File(dataDir, "system");
4134        File fname = new File(systemDir, "uiderrors.txt");
4135        return fname;
4136    }
4137
4138    static void reportSettingsProblem(int priority, String msg) {
4139        logCriticalInfo(priority, msg);
4140    }
4141
4142    static void logCriticalInfo(int priority, String msg) {
4143        Slog.println(priority, TAG, msg);
4144        EventLogTags.writePmCriticalInfo(msg);
4145        try {
4146            File fname = getSettingsProblemFile();
4147            FileOutputStream out = new FileOutputStream(fname, true);
4148            PrintWriter pw = new FastPrintWriter(out);
4149            SimpleDateFormat formatter = new SimpleDateFormat();
4150            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4151            pw.println(dateString + ": " + msg);
4152            pw.close();
4153            FileUtils.setPermissions(
4154                    fname.toString(),
4155                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4156                    -1, -1);
4157        } catch (java.io.IOException e) {
4158        }
4159    }
4160
4161    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4162            PackageParser.Package pkg, File srcFile, int parseFlags)
4163            throws PackageManagerException {
4164        if (ps != null
4165                && ps.codePath.equals(srcFile)
4166                && ps.timeStamp == srcFile.lastModified()
4167                && !isCompatSignatureUpdateNeeded(pkg)) {
4168            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4169            if (ps.signatures.mSignatures != null
4170                    && ps.signatures.mSignatures.length != 0
4171                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4172                // Optimization: reuse the existing cached certificates
4173                // if the package appears to be unchanged.
4174                pkg.mSignatures = ps.signatures.mSignatures;
4175                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4176                synchronized (mPackages) {
4177                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4178                }
4179                return;
4180            }
4181
4182            Slog.w(TAG, "PackageSetting for " + ps.name
4183                    + " is missing signatures.  Collecting certs again to recover them.");
4184        } else {
4185            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4186        }
4187
4188        try {
4189            pp.collectCertificates(pkg, parseFlags);
4190            pp.collectManifestDigest(pkg);
4191        } catch (PackageParserException e) {
4192            throw PackageManagerException.from(e);
4193        }
4194    }
4195
4196    /*
4197     *  Scan a package and return the newly parsed package.
4198     *  Returns null in case of errors and the error code is stored in mLastScanError
4199     */
4200    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4201            long currentTime, UserHandle user) throws PackageManagerException {
4202        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4203        parseFlags |= mDefParseFlags;
4204        PackageParser pp = new PackageParser();
4205        pp.setSeparateProcesses(mSeparateProcesses);
4206        pp.setOnlyCoreApps(mOnlyCore);
4207        pp.setDisplayMetrics(mMetrics);
4208
4209        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4210            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4211        }
4212
4213        final PackageParser.Package pkg;
4214        try {
4215            pkg = pp.parsePackage(scanFile, parseFlags);
4216        } catch (PackageParserException e) {
4217            throw PackageManagerException.from(e);
4218        }
4219
4220        PackageSetting ps = null;
4221        PackageSetting updatedPkg;
4222        // reader
4223        synchronized (mPackages) {
4224            // Look to see if we already know about this package.
4225            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4226            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4227                // This package has been renamed to its original name.  Let's
4228                // use that.
4229                ps = mSettings.peekPackageLPr(oldName);
4230            }
4231            // If there was no original package, see one for the real package name.
4232            if (ps == null) {
4233                ps = mSettings.peekPackageLPr(pkg.packageName);
4234            }
4235            // Check to see if this package could be hiding/updating a system
4236            // package.  Must look for it either under the original or real
4237            // package name depending on our state.
4238            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4239            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4240        }
4241        boolean updatedPkgBetter = false;
4242        // First check if this is a system package that may involve an update
4243        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4244            // If new package is not located in "/system/priv-app" (e.g. due to an OTA),
4245            // it needs to drop FLAG_PRIVILEGED.
4246            if (locationIsPrivileged(scanFile)) {
4247                updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4248            } else {
4249                updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
4250            }
4251
4252            if (ps != null && !ps.codePath.equals(scanFile)) {
4253                // The path has changed from what was last scanned...  check the
4254                // version of the new path against what we have stored to determine
4255                // what to do.
4256                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4257                if (pkg.mVersionCode < ps.versionCode) {
4258                    // The system package has been updated and the code path does not match
4259                    // Ignore entry. Skip it.
4260                    logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
4261                            + " ignored: updated version " + ps.versionCode
4262                            + " better than this " + pkg.mVersionCode);
4263                    if (!updatedPkg.codePath.equals(scanFile)) {
4264                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4265                                + ps.name + " changing from " + updatedPkg.codePathString
4266                                + " to " + scanFile);
4267                        updatedPkg.codePath = scanFile;
4268                        updatedPkg.codePathString = scanFile.toString();
4269                        updatedPkg.resourcePath = scanFile;
4270                        updatedPkg.resourcePathString = scanFile.toString();
4271                    }
4272                    updatedPkg.pkg = pkg;
4273                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4274                } else {
4275                    // The current app on the system partition is better than
4276                    // what we have updated to on the data partition; switch
4277                    // back to the system partition version.
4278                    // At this point, its safely assumed that package installation for
4279                    // apps in system partition will go through. If not there won't be a working
4280                    // version of the app
4281                    // writer
4282                    synchronized (mPackages) {
4283                        // Just remove the loaded entries from package lists.
4284                        mPackages.remove(ps.name);
4285                    }
4286
4287                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4288                            + " reverting from " + ps.codePathString
4289                            + ": new version " + pkg.mVersionCode
4290                            + " better than installed " + ps.versionCode);
4291
4292                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4293                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4294                            getAppDexInstructionSets(ps));
4295                    synchronized (mInstallLock) {
4296                        args.cleanUpResourcesLI();
4297                    }
4298                    synchronized (mPackages) {
4299                        mSettings.enableSystemPackageLPw(ps.name);
4300                    }
4301                    updatedPkgBetter = true;
4302                }
4303            }
4304        }
4305
4306        if (updatedPkg != null) {
4307            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4308            // initially
4309            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4310
4311            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4312            // flag set initially
4313            if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
4314                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4315            }
4316        }
4317
4318        // Verify certificates against what was last scanned
4319        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4320
4321        /*
4322         * A new system app appeared, but we already had a non-system one of the
4323         * same name installed earlier.
4324         */
4325        boolean shouldHideSystemApp = false;
4326        if (updatedPkg == null && ps != null
4327                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4328            /*
4329             * Check to make sure the signatures match first. If they don't,
4330             * wipe the installed application and its data.
4331             */
4332            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4333                    != PackageManager.SIGNATURE_MATCH) {
4334                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4335                        + " signatures don't match existing userdata copy; removing");
4336                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4337                ps = null;
4338            } else {
4339                /*
4340                 * If the newly-added system app is an older version than the
4341                 * already installed version, hide it. It will be scanned later
4342                 * and re-added like an update.
4343                 */
4344                if (pkg.mVersionCode < ps.versionCode) {
4345                    shouldHideSystemApp = true;
4346                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4347                            + " but new version " + pkg.mVersionCode + " better than installed "
4348                            + ps.versionCode + "; hiding system");
4349                } else {
4350                    /*
4351                     * The newly found system app is a newer version that the
4352                     * one previously installed. Simply remove the
4353                     * already-installed application and replace it with our own
4354                     * while keeping the application data.
4355                     */
4356                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4357                            + " reverting from " + ps.codePathString + ": new version "
4358                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4359                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4360                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4361                            getAppDexInstructionSets(ps));
4362                    synchronized (mInstallLock) {
4363                        args.cleanUpResourcesLI();
4364                    }
4365                }
4366            }
4367        }
4368
4369        // The apk is forward locked (not public) if its code and resources
4370        // are kept in different files. (except for app in either system or
4371        // vendor path).
4372        // TODO grab this value from PackageSettings
4373        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4374            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4375                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4376            }
4377        }
4378
4379        // TODO: extend to support forward-locked splits
4380        String resourcePath = null;
4381        String baseResourcePath = null;
4382        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4383            if (ps != null && ps.resourcePathString != null) {
4384                resourcePath = ps.resourcePathString;
4385                baseResourcePath = ps.resourcePathString;
4386            } else {
4387                // Should not happen at all. Just log an error.
4388                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4389            }
4390        } else {
4391            resourcePath = pkg.codePath;
4392            baseResourcePath = pkg.baseCodePath;
4393        }
4394
4395        // Set application objects path explicitly.
4396        pkg.applicationInfo.setCodePath(pkg.codePath);
4397        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4398        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4399        pkg.applicationInfo.setResourcePath(resourcePath);
4400        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4401        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4402
4403        // Note that we invoke the following method only if we are about to unpack an application
4404        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4405                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4406
4407        /*
4408         * If the system app should be overridden by a previously installed
4409         * data, hide the system app now and let the /data/app scan pick it up
4410         * again.
4411         */
4412        if (shouldHideSystemApp) {
4413            synchronized (mPackages) {
4414                /*
4415                 * We have to grant systems permissions before we hide, because
4416                 * grantPermissions will assume the package update is trying to
4417                 * expand its permissions.
4418                 */
4419                grantPermissionsLPw(pkg, true, pkg.packageName);
4420                mSettings.disableSystemPackageLPw(pkg.packageName);
4421            }
4422        }
4423
4424        return scannedPkg;
4425    }
4426
4427    private static String fixProcessName(String defProcessName,
4428            String processName, int uid) {
4429        if (processName == null) {
4430            return defProcessName;
4431        }
4432        return processName;
4433    }
4434
4435    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4436            throws PackageManagerException {
4437        if (pkgSetting.signatures.mSignatures != null) {
4438            // Already existing package. Make sure signatures match
4439            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4440                    == PackageManager.SIGNATURE_MATCH;
4441            if (!match) {
4442                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4443                        == PackageManager.SIGNATURE_MATCH;
4444            }
4445            if (!match) {
4446                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4447                        + pkg.packageName + " signatures do not match the "
4448                        + "previously installed version; ignoring!");
4449            }
4450        }
4451
4452        // Check for shared user signatures
4453        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4454            // Already existing package. Make sure signatures match
4455            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4456                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4457            if (!match) {
4458                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4459                        == PackageManager.SIGNATURE_MATCH;
4460            }
4461            if (!match) {
4462                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4463                        "Package " + pkg.packageName
4464                        + " has no signatures that match those in shared user "
4465                        + pkgSetting.sharedUser.name + "; ignoring!");
4466            }
4467        }
4468    }
4469
4470    /**
4471     * Enforces that only the system UID or root's UID can call a method exposed
4472     * via Binder.
4473     *
4474     * @param message used as message if SecurityException is thrown
4475     * @throws SecurityException if the caller is not system or root
4476     */
4477    private static final void enforceSystemOrRoot(String message) {
4478        final int uid = Binder.getCallingUid();
4479        if (uid != Process.SYSTEM_UID && uid != 0) {
4480            throw new SecurityException(message);
4481        }
4482    }
4483
4484    @Override
4485    public void performBootDexOpt() {
4486        enforceSystemOrRoot("Only the system can request dexopt be performed");
4487
4488        final HashSet<PackageParser.Package> pkgs;
4489        synchronized (mPackages) {
4490            pkgs = mDeferredDexOpt;
4491            mDeferredDexOpt = null;
4492        }
4493
4494        if (pkgs != null) {
4495            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4496            // in case the device runs out of space.
4497            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4498            // Give priority to core apps.
4499            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4500                PackageParser.Package pkg = it.next();
4501                if (pkg.coreApp) {
4502                    if (DEBUG_DEXOPT) {
4503                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4504                    }
4505                    sortedPkgs.add(pkg);
4506                    it.remove();
4507                }
4508            }
4509            // Give priority to system apps that listen for pre boot complete.
4510            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4511            HashSet<String> pkgNames = getPackageNamesForIntent(intent);
4512            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4513                PackageParser.Package pkg = it.next();
4514                if (pkgNames.contains(pkg.packageName)) {
4515                    if (DEBUG_DEXOPT) {
4516                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4517                    }
4518                    sortedPkgs.add(pkg);
4519                    it.remove();
4520                }
4521            }
4522            // Give priority to system apps.
4523            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4524                PackageParser.Package pkg = it.next();
4525                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4526                    if (DEBUG_DEXOPT) {
4527                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4528                    }
4529                    sortedPkgs.add(pkg);
4530                    it.remove();
4531                }
4532            }
4533            // Give priority to updated system apps.
4534            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4535                PackageParser.Package pkg = it.next();
4536                if (isUpdatedSystemApp(pkg)) {
4537                    if (DEBUG_DEXOPT) {
4538                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4539                    }
4540                    sortedPkgs.add(pkg);
4541                    it.remove();
4542                }
4543            }
4544            // Give priority to apps that listen for boot complete.
4545            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4546            pkgNames = getPackageNamesForIntent(intent);
4547            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4548                PackageParser.Package pkg = it.next();
4549                if (pkgNames.contains(pkg.packageName)) {
4550                    if (DEBUG_DEXOPT) {
4551                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4552                    }
4553                    sortedPkgs.add(pkg);
4554                    it.remove();
4555                }
4556            }
4557            // Filter out packages that aren't recently used.
4558            filterRecentlyUsedApps(pkgs);
4559            // Add all remaining apps.
4560            for (PackageParser.Package pkg : pkgs) {
4561                if (DEBUG_DEXOPT) {
4562                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4563                }
4564                sortedPkgs.add(pkg);
4565            }
4566
4567            int i = 0;
4568            int total = sortedPkgs.size();
4569            File dataDir = Environment.getDataDirectory();
4570            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4571            if (lowThreshold == 0) {
4572                throw new IllegalStateException("Invalid low memory threshold");
4573            }
4574            for (PackageParser.Package pkg : sortedPkgs) {
4575                long usableSpace = dataDir.getUsableSpace();
4576                if (usableSpace < lowThreshold) {
4577                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4578                    break;
4579                }
4580                performBootDexOpt(pkg, ++i, total);
4581            }
4582        }
4583    }
4584
4585    private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) {
4586        // Filter out packages that aren't recently used.
4587        //
4588        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4589        // should do a full dexopt.
4590        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4591            // TODO: add a property to control this?
4592            long dexOptLRUThresholdInMinutes;
4593            if (mLazyDexOpt) {
4594                dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4595            } else {
4596                dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4597            }
4598            long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4599
4600            int total = pkgs.size();
4601            int skipped = 0;
4602            long now = System.currentTimeMillis();
4603            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4604                PackageParser.Package pkg = i.next();
4605                long then = pkg.mLastPackageUsageTimeInMills;
4606                if (then + dexOptLRUThresholdInMills < now) {
4607                    if (DEBUG_DEXOPT) {
4608                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4609                              ((then == 0) ? "never" : new Date(then)));
4610                    }
4611                    i.remove();
4612                    skipped++;
4613                }
4614            }
4615            if (DEBUG_DEXOPT) {
4616                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4617            }
4618        }
4619    }
4620
4621    private HashSet<String> getPackageNamesForIntent(Intent intent) {
4622        List<ResolveInfo> ris = null;
4623        try {
4624            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4625                    intent, null, 0, UserHandle.USER_OWNER);
4626        } catch (RemoteException e) {
4627        }
4628        HashSet<String> pkgNames = new HashSet<String>();
4629        if (ris != null) {
4630            for (ResolveInfo ri : ris) {
4631                pkgNames.add(ri.activityInfo.packageName);
4632            }
4633        }
4634        return pkgNames;
4635    }
4636
4637    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4638        if (DEBUG_DEXOPT) {
4639            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4640        }
4641        if (!isFirstBoot()) {
4642            try {
4643                ActivityManagerNative.getDefault().showBootMessage(
4644                        mContext.getResources().getString(R.string.android_upgrading_apk,
4645                                curr, total), true);
4646            } catch (RemoteException e) {
4647            }
4648        }
4649        PackageParser.Package p = pkg;
4650        synchronized (mInstallLock) {
4651            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4652                            false /* defer */, true /* include dependencies */);
4653        }
4654    }
4655
4656    @Override
4657    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4658        return performDexOpt(packageName, instructionSet, false);
4659    }
4660
4661    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4662        if (info.primaryCpuAbi == null) {
4663            return getPreferredInstructionSet();
4664        }
4665
4666        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4667    }
4668
4669    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4670        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4671        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4672        if (!dexopt && !updateUsage) {
4673            // We aren't going to dexopt or update usage, so bail early.
4674            return false;
4675        }
4676        PackageParser.Package p;
4677        final String targetInstructionSet;
4678        synchronized (mPackages) {
4679            p = mPackages.get(packageName);
4680            if (p == null) {
4681                return false;
4682            }
4683            if (updateUsage) {
4684                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4685            }
4686            mPackageUsage.write(false);
4687            if (!dexopt) {
4688                // We aren't going to dexopt, so bail early.
4689                return false;
4690            }
4691
4692            targetInstructionSet = instructionSet != null ? instructionSet :
4693                    getPrimaryInstructionSet(p.applicationInfo);
4694            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4695                return false;
4696            }
4697        }
4698
4699        synchronized (mInstallLock) {
4700            final String[] instructionSets = new String[] { targetInstructionSet };
4701            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4702                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4703        }
4704    }
4705
4706    public HashSet<String> getPackagesThatNeedDexOpt() {
4707        HashSet<String> pkgs = null;
4708        synchronized (mPackages) {
4709            for (PackageParser.Package p : mPackages.values()) {
4710                if (DEBUG_DEXOPT) {
4711                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4712                }
4713                if (!p.mDexOptPerformed.isEmpty()) {
4714                    continue;
4715                }
4716                if (pkgs == null) {
4717                    pkgs = new HashSet<String>();
4718                }
4719                pkgs.add(p.packageName);
4720            }
4721        }
4722        return pkgs;
4723    }
4724
4725    public void shutdown() {
4726        mPackageUsage.write(true);
4727    }
4728
4729    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4730             boolean forceDex, boolean defer, HashSet<String> done) {
4731        for (int i=0; i<libs.size(); i++) {
4732            PackageParser.Package libPkg;
4733            String libName;
4734            synchronized (mPackages) {
4735                libName = libs.get(i);
4736                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4737                if (lib != null && lib.apk != null) {
4738                    libPkg = mPackages.get(lib.apk);
4739                } else {
4740                    libPkg = null;
4741                }
4742            }
4743            if (libPkg != null && !done.contains(libName)) {
4744                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4745            }
4746        }
4747    }
4748
4749    static final int DEX_OPT_SKIPPED = 0;
4750    static final int DEX_OPT_PERFORMED = 1;
4751    static final int DEX_OPT_DEFERRED = 2;
4752    static final int DEX_OPT_FAILED = -1;
4753
4754    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4755            boolean forceDex, boolean defer, HashSet<String> done) {
4756        final String[] instructionSets = targetInstructionSets != null ?
4757                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4758
4759        if (done != null) {
4760            done.add(pkg.packageName);
4761            if (pkg.usesLibraries != null) {
4762                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4763            }
4764            if (pkg.usesOptionalLibraries != null) {
4765                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4766            }
4767        }
4768
4769        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4770            return DEX_OPT_SKIPPED;
4771        }
4772
4773        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4774        final boolean debuggable = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
4775
4776        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4777        boolean performedDexOpt = false;
4778        // There are three basic cases here:
4779        // 1.) we need to dexopt, either because we are forced or it is needed
4780        // 2.) we are defering a needed dexopt
4781        // 3.) we are skipping an unneeded dexopt
4782        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4783        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4784            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4785                continue;
4786            }
4787
4788            for (String path : paths) {
4789                try {
4790                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4791                    // patckage or the one we find does not match the image checksum (i.e. it was
4792                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4793                    // odex file and it matches the checksum of the image but not its base address,
4794                    // meaning we need to move it.
4795                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4796                            pkg.packageName, dexCodeInstructionSet, defer);
4797                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4798                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4799                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4800                                + " vmSafeMode=" + vmSafeMode + " debuggable=" + debuggable);
4801                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4802                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4803                                pkg.packageName, dexCodeInstructionSet, vmSafeMode, debuggable);
4804
4805                        if (ret < 0) {
4806                            // Don't bother running dexopt again if we failed, it will probably
4807                            // just result in an error again. Also, don't bother dexopting for other
4808                            // paths & ISAs.
4809                            return DEX_OPT_FAILED;
4810                        }
4811
4812                        performedDexOpt = true;
4813                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4814                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4815                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4816                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4817                                pkg.packageName, dexCodeInstructionSet);
4818
4819                        if (ret < 0) {
4820                            // Don't bother running patchoat again if we failed, it will probably
4821                            // just result in an error again. Also, don't bother dexopting for other
4822                            // paths & ISAs.
4823                            return DEX_OPT_FAILED;
4824                        }
4825
4826                        performedDexOpt = true;
4827                    }
4828
4829                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4830                    // paths and instruction sets. We'll deal with them all together when we process
4831                    // our list of deferred dexopts.
4832                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4833                        if (mDeferredDexOpt == null) {
4834                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4835                        }
4836                        mDeferredDexOpt.add(pkg);
4837                        return DEX_OPT_DEFERRED;
4838                    }
4839                } catch (FileNotFoundException e) {
4840                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4841                    return DEX_OPT_FAILED;
4842                } catch (IOException e) {
4843                    Slog.w(TAG, "IOException reading apk: " + path, e);
4844                    return DEX_OPT_FAILED;
4845                } catch (StaleDexCacheError e) {
4846                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4847                    return DEX_OPT_FAILED;
4848                } catch (Exception e) {
4849                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4850                    return DEX_OPT_FAILED;
4851                }
4852            }
4853
4854            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4855            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4856            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4857            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4858            // it.
4859            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4860        }
4861
4862        // If we've gotten here, we're sure that no error occurred and that we haven't
4863        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4864        // we've skipped all of them because they are up to date. In both cases this
4865        // package doesn't need dexopt any longer.
4866        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4867    }
4868
4869    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4870        if (info.primaryCpuAbi != null) {
4871            if (info.secondaryCpuAbi != null) {
4872                return new String[] {
4873                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4874                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4875            } else {
4876                return new String[] {
4877                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4878            }
4879        }
4880
4881        return new String[] { getPreferredInstructionSet() };
4882    }
4883
4884    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4885        if (ps.primaryCpuAbiString != null) {
4886            if (ps.secondaryCpuAbiString != null) {
4887                return new String[] {
4888                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4889                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4890            } else {
4891                return new String[] {
4892                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4893            }
4894        }
4895
4896        return new String[] { getPreferredInstructionSet() };
4897    }
4898
4899    private static String getPreferredInstructionSet() {
4900        if (sPreferredInstructionSet == null) {
4901            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4902        }
4903
4904        return sPreferredInstructionSet;
4905    }
4906
4907    private static List<String> getAllInstructionSets() {
4908        final String[] allAbis = Build.SUPPORTED_ABIS;
4909        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4910
4911        for (String abi : allAbis) {
4912            final String instructionSet = VMRuntime.getInstructionSet(abi);
4913            if (!allInstructionSets.contains(instructionSet)) {
4914                allInstructionSets.add(instructionSet);
4915            }
4916        }
4917
4918        return allInstructionSets;
4919    }
4920
4921    /**
4922     * Returns the instruction set that should be used to compile dex code. In the presence of
4923     * a native bridge this might be different than the one shared libraries use.
4924     */
4925    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4926        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4927        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4928    }
4929
4930    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4931        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4932        for (String instructionSet : instructionSets) {
4933            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4934        }
4935        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4936    }
4937
4938    /**
4939     * Returns deduplicated list of supported instructions for dex code.
4940     */
4941    public static String[] getAllDexCodeInstructionSets() {
4942        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4943        for (int i = 0; i < supportedInstructionSets.length; i++) {
4944            String abi = Build.SUPPORTED_ABIS[i];
4945            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4946        }
4947        return getDexCodeInstructionSets(supportedInstructionSets);
4948    }
4949
4950    @Override
4951    public void forceDexOpt(String packageName) {
4952        enforceSystemOrRoot("forceDexOpt");
4953
4954        PackageParser.Package pkg;
4955        synchronized (mPackages) {
4956            pkg = mPackages.get(packageName);
4957            if (pkg == null) {
4958                throw new IllegalArgumentException("Missing package: " + packageName);
4959            }
4960        }
4961
4962        synchronized (mInstallLock) {
4963            final String[] instructionSets = new String[] {
4964                    getPrimaryInstructionSet(pkg.applicationInfo) };
4965            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4966            if (res != DEX_OPT_PERFORMED) {
4967                throw new IllegalStateException("Failed to dexopt: " + res);
4968            }
4969        }
4970    }
4971
4972    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4973                                boolean forceDex, boolean defer, boolean inclDependencies) {
4974        HashSet<String> done;
4975        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4976            done = new HashSet<String>();
4977            done.add(pkg.packageName);
4978        } else {
4979            done = null;
4980        }
4981        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4982    }
4983
4984    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4985        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4986            Slog.w(TAG, "Unable to update from " + oldPkg.name
4987                    + " to " + newPkg.packageName
4988                    + ": old package not in system partition");
4989            return false;
4990        } else if (mPackages.get(oldPkg.name) != null) {
4991            Slog.w(TAG, "Unable to update from " + oldPkg.name
4992                    + " to " + newPkg.packageName
4993                    + ": old package still exists");
4994            return false;
4995        }
4996        return true;
4997    }
4998
4999    File getDataPathForUser(int userId) {
5000        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
5001    }
5002
5003    private File getDataPathForPackage(String packageName, int userId) {
5004        /*
5005         * Until we fully support multiple users, return the directory we
5006         * previously would have. The PackageManagerTests will need to be
5007         * revised when this is changed back..
5008         */
5009        if (userId == 0) {
5010            return new File(mAppDataDir, packageName);
5011        } else {
5012            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5013                + File.separator + packageName);
5014        }
5015    }
5016
5017    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5018        int[] users = sUserManager.getUserIds();
5019        int res = mInstaller.install(packageName, uid, uid, seinfo);
5020        if (res < 0) {
5021            return res;
5022        }
5023        for (int user : users) {
5024            if (user != 0) {
5025                res = mInstaller.createUserData(packageName,
5026                        UserHandle.getUid(user, uid), user, seinfo);
5027                if (res < 0) {
5028                    return res;
5029                }
5030            }
5031        }
5032        return res;
5033    }
5034
5035    private int removeDataDirsLI(String packageName) {
5036        int[] users = sUserManager.getUserIds();
5037        int res = 0;
5038        for (int user : users) {
5039            int resInner = mInstaller.remove(packageName, user);
5040            if (resInner < 0) {
5041                res = resInner;
5042            }
5043        }
5044
5045        return res;
5046    }
5047
5048    private int deleteCodeCacheDirsLI(String packageName) {
5049        int[] users = sUserManager.getUserIds();
5050        int res = 0;
5051        for (int user : users) {
5052            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5053            if (resInner < 0) {
5054                res = resInner;
5055            }
5056        }
5057        return res;
5058    }
5059
5060    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5061            PackageParser.Package changingLib) {
5062        if (file.path != null) {
5063            usesLibraryFiles.add(file.path);
5064            return;
5065        }
5066        PackageParser.Package p = mPackages.get(file.apk);
5067        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5068            // If we are doing this while in the middle of updating a library apk,
5069            // then we need to make sure to use that new apk for determining the
5070            // dependencies here.  (We haven't yet finished committing the new apk
5071            // to the package manager state.)
5072            if (p == null || p.packageName.equals(changingLib.packageName)) {
5073                p = changingLib;
5074            }
5075        }
5076        if (p != null) {
5077            usesLibraryFiles.addAll(p.getAllCodePaths());
5078        }
5079    }
5080
5081    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5082            PackageParser.Package changingLib) throws PackageManagerException {
5083        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5084            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5085            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5086            for (int i=0; i<N; i++) {
5087                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5088                if (file == null) {
5089                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5090                            "Package " + pkg.packageName + " requires unavailable shared library "
5091                            + pkg.usesLibraries.get(i) + "; failing!");
5092                }
5093                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5094            }
5095            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5096            for (int i=0; i<N; i++) {
5097                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5098                if (file == null) {
5099                    Slog.w(TAG, "Package " + pkg.packageName
5100                            + " desires unavailable shared library "
5101                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5102                } else {
5103                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5104                }
5105            }
5106            N = usesLibraryFiles.size();
5107            if (N > 0) {
5108                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5109            } else {
5110                pkg.usesLibraryFiles = null;
5111            }
5112        }
5113    }
5114
5115    private static boolean hasString(List<String> list, List<String> which) {
5116        if (list == null) {
5117            return false;
5118        }
5119        for (int i=list.size()-1; i>=0; i--) {
5120            for (int j=which.size()-1; j>=0; j--) {
5121                if (which.get(j).equals(list.get(i))) {
5122                    return true;
5123                }
5124            }
5125        }
5126        return false;
5127    }
5128
5129    private void updateAllSharedLibrariesLPw() {
5130        for (PackageParser.Package pkg : mPackages.values()) {
5131            try {
5132                updateSharedLibrariesLPw(pkg, null);
5133            } catch (PackageManagerException e) {
5134                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5135            }
5136        }
5137    }
5138
5139    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5140            PackageParser.Package changingPkg) {
5141        ArrayList<PackageParser.Package> res = null;
5142        for (PackageParser.Package pkg : mPackages.values()) {
5143            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5144                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5145                if (res == null) {
5146                    res = new ArrayList<PackageParser.Package>();
5147                }
5148                res.add(pkg);
5149                try {
5150                    updateSharedLibrariesLPw(pkg, changingPkg);
5151                } catch (PackageManagerException e) {
5152                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5153                }
5154            }
5155        }
5156        return res;
5157    }
5158
5159    /**
5160     * Derive the value of the {@code cpuAbiOverride} based on the provided
5161     * value and an optional stored value from the package settings.
5162     */
5163    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5164        String cpuAbiOverride = null;
5165
5166        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5167            cpuAbiOverride = null;
5168        } else if (abiOverride != null) {
5169            cpuAbiOverride = abiOverride;
5170        } else if (settings != null) {
5171            cpuAbiOverride = settings.cpuAbiOverrideString;
5172        }
5173
5174        return cpuAbiOverride;
5175    }
5176
5177    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5178            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5179        boolean success = false;
5180        try {
5181            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5182                    currentTime, user);
5183            success = true;
5184            return res;
5185        } finally {
5186            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5187                removeDataDirsLI(pkg.packageName);
5188            }
5189        }
5190    }
5191
5192    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5193            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5194        final File scanFile = new File(pkg.codePath);
5195        if (pkg.applicationInfo.getCodePath() == null ||
5196                pkg.applicationInfo.getResourcePath() == null) {
5197            // Bail out. The resource and code paths haven't been set.
5198            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5199                    "Code and resource paths haven't been set correctly");
5200        }
5201
5202        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5203            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5204        } else {
5205            // Only allow system apps to be flagged as core apps.
5206            pkg.coreApp = false;
5207        }
5208
5209        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5210            pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
5211        }
5212
5213        if (mCustomResolverComponentName != null &&
5214                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5215            setUpCustomResolverActivity(pkg);
5216        }
5217
5218        if (pkg.packageName.equals("android")) {
5219            synchronized (mPackages) {
5220                if (mAndroidApplication != null) {
5221                    Slog.w(TAG, "*************************************************");
5222                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5223                    Slog.w(TAG, " file=" + scanFile);
5224                    Slog.w(TAG, "*************************************************");
5225                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5226                            "Core android package being redefined.  Skipping.");
5227                }
5228
5229                // Set up information for our fall-back user intent resolution activity.
5230                mPlatformPackage = pkg;
5231                pkg.mVersionCode = mSdkVersion;
5232                mAndroidApplication = pkg.applicationInfo;
5233
5234                if (!mResolverReplaced) {
5235                    mResolveActivity.applicationInfo = mAndroidApplication;
5236                    mResolveActivity.name = ResolverActivity.class.getName();
5237                    mResolveActivity.packageName = mAndroidApplication.packageName;
5238                    mResolveActivity.processName = "system:ui";
5239                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5240                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5241                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5242                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5243                    mResolveActivity.exported = true;
5244                    mResolveActivity.enabled = true;
5245                    mResolveInfo.activityInfo = mResolveActivity;
5246                    mResolveInfo.priority = 0;
5247                    mResolveInfo.preferredOrder = 0;
5248                    mResolveInfo.match = 0;
5249                    mResolveComponentName = new ComponentName(
5250                            mAndroidApplication.packageName, mResolveActivity.name);
5251                }
5252            }
5253        }
5254
5255        if (DEBUG_PACKAGE_SCANNING) {
5256            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5257                Log.d(TAG, "Scanning package " + pkg.packageName);
5258        }
5259
5260        if (mPackages.containsKey(pkg.packageName)
5261                || mSharedLibraries.containsKey(pkg.packageName)) {
5262            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5263                    "Application package " + pkg.packageName
5264                    + " already installed.  Skipping duplicate.");
5265        }
5266
5267        // Initialize package source and resource directories
5268        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5269        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5270
5271        SharedUserSetting suid = null;
5272        PackageSetting pkgSetting = null;
5273
5274        if (!isSystemApp(pkg)) {
5275            // Only system apps can use these features.
5276            pkg.mOriginalPackages = null;
5277            pkg.mRealPackage = null;
5278            pkg.mAdoptPermissions = null;
5279        }
5280
5281        // writer
5282        synchronized (mPackages) {
5283            if (pkg.mSharedUserId != null) {
5284                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true);
5285                if (suid == null) {
5286                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5287                            "Creating application package " + pkg.packageName
5288                            + " for shared user failed");
5289                }
5290                if (DEBUG_PACKAGE_SCANNING) {
5291                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5292                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5293                                + "): packages=" + suid.packages);
5294                }
5295            }
5296
5297            // Check if we are renaming from an original package name.
5298            PackageSetting origPackage = null;
5299            String realName = null;
5300            if (pkg.mOriginalPackages != null) {
5301                // This package may need to be renamed to a previously
5302                // installed name.  Let's check on that...
5303                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5304                if (pkg.mOriginalPackages.contains(renamed)) {
5305                    // This package had originally been installed as the
5306                    // original name, and we have already taken care of
5307                    // transitioning to the new one.  Just update the new
5308                    // one to continue using the old name.
5309                    realName = pkg.mRealPackage;
5310                    if (!pkg.packageName.equals(renamed)) {
5311                        // Callers into this function may have already taken
5312                        // care of renaming the package; only do it here if
5313                        // it is not already done.
5314                        pkg.setPackageName(renamed);
5315                    }
5316
5317                } else {
5318                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5319                        if ((origPackage = mSettings.peekPackageLPr(
5320                                pkg.mOriginalPackages.get(i))) != null) {
5321                            // We do have the package already installed under its
5322                            // original name...  should we use it?
5323                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5324                                // New package is not compatible with original.
5325                                origPackage = null;
5326                                continue;
5327                            } else if (origPackage.sharedUser != null) {
5328                                // Make sure uid is compatible between packages.
5329                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5330                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5331                                            + " to " + pkg.packageName + ": old uid "
5332                                            + origPackage.sharedUser.name
5333                                            + " differs from " + pkg.mSharedUserId);
5334                                    origPackage = null;
5335                                    continue;
5336                                }
5337                            } else {
5338                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5339                                        + pkg.packageName + " to old name " + origPackage.name);
5340                            }
5341                            break;
5342                        }
5343                    }
5344                }
5345            }
5346
5347            if (mTransferedPackages.contains(pkg.packageName)) {
5348                Slog.w(TAG, "Package " + pkg.packageName
5349                        + " was transferred to another, but its .apk remains");
5350            }
5351
5352            // Just create the setting, don't add it yet. For already existing packages
5353            // the PkgSetting exists already and doesn't have to be created.
5354            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5355                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5356                    pkg.applicationInfo.primaryCpuAbi,
5357                    pkg.applicationInfo.secondaryCpuAbi,
5358                    pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags,
5359                    user, false);
5360            if (pkgSetting == null) {
5361                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5362                        "Creating application package " + pkg.packageName + " failed");
5363            }
5364
5365            if (pkgSetting.origPackage != null) {
5366                // If we are first transitioning from an original package,
5367                // fix up the new package's name now.  We need to do this after
5368                // looking up the package under its new name, so getPackageLP
5369                // can take care of fiddling things correctly.
5370                pkg.setPackageName(origPackage.name);
5371
5372                // File a report about this.
5373                String msg = "New package " + pkgSetting.realName
5374                        + " renamed to replace old package " + pkgSetting.name;
5375                reportSettingsProblem(Log.WARN, msg);
5376
5377                // Make a note of it.
5378                mTransferedPackages.add(origPackage.name);
5379
5380                // No longer need to retain this.
5381                pkgSetting.origPackage = null;
5382            }
5383
5384            if (realName != null) {
5385                // Make a note of it.
5386                mTransferedPackages.add(pkg.packageName);
5387            }
5388
5389            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5390                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5391            }
5392
5393            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5394                // Check all shared libraries and map to their actual file path.
5395                // We only do this here for apps not on a system dir, because those
5396                // are the only ones that can fail an install due to this.  We
5397                // will take care of the system apps by updating all of their
5398                // library paths after the scan is done.
5399                updateSharedLibrariesLPw(pkg, null);
5400            }
5401
5402            if (mFoundPolicyFile) {
5403                SELinuxMMAC.assignSeinfoValue(pkg);
5404            }
5405
5406            pkg.applicationInfo.uid = pkgSetting.appId;
5407            pkg.mExtras = pkgSetting;
5408            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5409                try {
5410                    verifySignaturesLP(pkgSetting, pkg);
5411                } catch (PackageManagerException e) {
5412                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5413                        throw e;
5414                    }
5415                    // The signature has changed, but this package is in the system
5416                    // image...  let's recover!
5417                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5418                    // However...  if this package is part of a shared user, but it
5419                    // doesn't match the signature of the shared user, let's fail.
5420                    // What this means is that you can't change the signatures
5421                    // associated with an overall shared user, which doesn't seem all
5422                    // that unreasonable.
5423                    if (pkgSetting.sharedUser != null) {
5424                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5425                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5426                            throw new PackageManagerException(
5427                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5428                                            "Signature mismatch for shared user : "
5429                                            + pkgSetting.sharedUser);
5430                        }
5431                    }
5432                    // File a report about this.
5433                    String msg = "System package " + pkg.packageName
5434                        + " signature changed; retaining data.";
5435                    reportSettingsProblem(Log.WARN, msg);
5436                }
5437            } else {
5438                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5439                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5440                            + pkg.packageName + " upgrade keys do not match the "
5441                            + "previously installed version");
5442                } else {
5443                    // signatures may have changed as result of upgrade
5444                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5445                }
5446            }
5447            // Verify that this new package doesn't have any content providers
5448            // that conflict with existing packages.  Only do this if the
5449            // package isn't already installed, since we don't want to break
5450            // things that are installed.
5451            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5452                final int N = pkg.providers.size();
5453                int i;
5454                for (i=0; i<N; i++) {
5455                    PackageParser.Provider p = pkg.providers.get(i);
5456                    if (p.info.authority != null) {
5457                        String names[] = p.info.authority.split(";");
5458                        for (int j = 0; j < names.length; j++) {
5459                            if (mProvidersByAuthority.containsKey(names[j])) {
5460                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5461                                final String otherPackageName =
5462                                        ((other != null && other.getComponentName() != null) ?
5463                                                other.getComponentName().getPackageName() : "?");
5464                                throw new PackageManagerException(
5465                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5466                                                "Can't install because provider name " + names[j]
5467                                                + " (in package " + pkg.applicationInfo.packageName
5468                                                + ") is already used by " + otherPackageName);
5469                            }
5470                        }
5471                    }
5472                }
5473            }
5474
5475            if (pkg.mAdoptPermissions != null) {
5476                // This package wants to adopt ownership of permissions from
5477                // another package.
5478                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5479                    final String origName = pkg.mAdoptPermissions.get(i);
5480                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5481                    if (orig != null) {
5482                        if (verifyPackageUpdateLPr(orig, pkg)) {
5483                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5484                                    + pkg.packageName);
5485                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5486                        }
5487                    }
5488                }
5489            }
5490        }
5491
5492        final String pkgName = pkg.packageName;
5493
5494        final long scanFileTime = scanFile.lastModified();
5495        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5496        pkg.applicationInfo.processName = fixProcessName(
5497                pkg.applicationInfo.packageName,
5498                pkg.applicationInfo.processName,
5499                pkg.applicationInfo.uid);
5500
5501        File dataPath;
5502        if (mPlatformPackage == pkg) {
5503            // The system package is special.
5504            dataPath = new File(Environment.getDataDirectory(), "system");
5505
5506            pkg.applicationInfo.dataDir = dataPath.getPath();
5507
5508        } else {
5509            // This is a normal package, need to make its data directory.
5510            dataPath = getDataPathForPackage(pkg.packageName, 0);
5511
5512            boolean uidError = false;
5513            if (dataPath.exists()) {
5514                int currentUid = 0;
5515                try {
5516                    StructStat stat = Os.stat(dataPath.getPath());
5517                    currentUid = stat.st_uid;
5518                } catch (ErrnoException e) {
5519                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5520                }
5521
5522                // If we have mismatched owners for the data path, we have a problem.
5523                if (currentUid != pkg.applicationInfo.uid) {
5524                    boolean recovered = false;
5525                    if (currentUid == 0) {
5526                        // The directory somehow became owned by root.  Wow.
5527                        // This is probably because the system was stopped while
5528                        // installd was in the middle of messing with its libs
5529                        // directory.  Ask installd to fix that.
5530                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5531                                pkg.applicationInfo.uid);
5532                        if (ret >= 0) {
5533                            recovered = true;
5534                            String msg = "Package " + pkg.packageName
5535                                    + " unexpectedly changed to uid 0; recovered to " +
5536                                    + pkg.applicationInfo.uid;
5537                            reportSettingsProblem(Log.WARN, msg);
5538                        }
5539                    }
5540                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5541                            || (scanFlags&SCAN_BOOTING) != 0)) {
5542                        // If this is a system app, we can at least delete its
5543                        // current data so the application will still work.
5544                        int ret = removeDataDirsLI(pkgName);
5545                        if (ret >= 0) {
5546                            // TODO: Kill the processes first
5547                            // Old data gone!
5548                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5549                                    ? "System package " : "Third party package ";
5550                            String msg = prefix + pkg.packageName
5551                                    + " has changed from uid: "
5552                                    + currentUid + " to "
5553                                    + pkg.applicationInfo.uid + "; old data erased";
5554                            reportSettingsProblem(Log.WARN, msg);
5555                            recovered = true;
5556
5557                            // And now re-install the app.
5558                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5559                                                   pkg.applicationInfo.seinfo);
5560                            if (ret == -1) {
5561                                // Ack should not happen!
5562                                msg = prefix + pkg.packageName
5563                                        + " could not have data directory re-created after delete.";
5564                                reportSettingsProblem(Log.WARN, msg);
5565                                throw new PackageManagerException(
5566                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5567                            }
5568                        }
5569                        if (!recovered) {
5570                            mHasSystemUidErrors = true;
5571                        }
5572                    } else if (!recovered) {
5573                        // If we allow this install to proceed, we will be broken.
5574                        // Abort, abort!
5575                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5576                                "scanPackageLI");
5577                    }
5578                    if (!recovered) {
5579                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5580                            + pkg.applicationInfo.uid + "/fs_"
5581                            + currentUid;
5582                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5583                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5584                        String msg = "Package " + pkg.packageName
5585                                + " has mismatched uid: "
5586                                + currentUid + " on disk, "
5587                                + pkg.applicationInfo.uid + " in settings";
5588                        // writer
5589                        synchronized (mPackages) {
5590                            mSettings.mReadMessages.append(msg);
5591                            mSettings.mReadMessages.append('\n');
5592                            uidError = true;
5593                            if (!pkgSetting.uidError) {
5594                                reportSettingsProblem(Log.ERROR, msg);
5595                            }
5596                        }
5597                    }
5598                }
5599                pkg.applicationInfo.dataDir = dataPath.getPath();
5600                if (mShouldRestoreconData) {
5601                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5602                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5603                                pkg.applicationInfo.uid);
5604                }
5605            } else {
5606                if (DEBUG_PACKAGE_SCANNING) {
5607                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5608                        Log.v(TAG, "Want this data dir: " + dataPath);
5609                }
5610                //invoke installer to do the actual installation
5611                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5612                                           pkg.applicationInfo.seinfo);
5613                if (ret < 0) {
5614                    // Error from installer
5615                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5616                            "Unable to create data dirs [errorCode=" + ret + "]");
5617                }
5618
5619                if (dataPath.exists()) {
5620                    pkg.applicationInfo.dataDir = dataPath.getPath();
5621                } else {
5622                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5623                    pkg.applicationInfo.dataDir = null;
5624                }
5625            }
5626
5627            pkgSetting.uidError = uidError;
5628        }
5629
5630        final String path = scanFile.getPath();
5631        final String codePath = pkg.applicationInfo.getCodePath();
5632        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5633        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5634            setBundledAppAbisAndRoots(pkg, pkgSetting);
5635
5636            // If we haven't found any native libraries for the app, check if it has
5637            // renderscript code. We'll need to force the app to 32 bit if it has
5638            // renderscript bitcode.
5639            if (pkg.applicationInfo.primaryCpuAbi == null
5640                    && pkg.applicationInfo.secondaryCpuAbi == null
5641                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5642                NativeLibraryHelper.Handle handle = null;
5643                try {
5644                    handle = NativeLibraryHelper.Handle.create(scanFile);
5645                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5646                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5647                    }
5648                } catch (IOException ioe) {
5649                    Slog.w(TAG, "Error scanning system app : " + ioe);
5650                } finally {
5651                    IoUtils.closeQuietly(handle);
5652                }
5653            }
5654
5655            setNativeLibraryPaths(pkg);
5656        } else {
5657            // TODO: We can probably be smarter about this stuff. For installed apps,
5658            // we can calculate this information at install time once and for all. For
5659            // system apps, we can probably assume that this information doesn't change
5660            // after the first boot scan. As things stand, we do lots of unnecessary work.
5661
5662            // Give ourselves some initial paths; we'll come back for another
5663            // pass once we've determined ABI below.
5664            setNativeLibraryPaths(pkg);
5665
5666            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5667            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5668            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5669
5670            NativeLibraryHelper.Handle handle = null;
5671            try {
5672                handle = NativeLibraryHelper.Handle.create(scanFile);
5673                // TODO(multiArch): This can be null for apps that didn't go through the
5674                // usual installation process. We can calculate it again, like we
5675                // do during install time.
5676                //
5677                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5678                // unnecessary.
5679                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5680
5681                // Null out the abis so that they can be recalculated.
5682                pkg.applicationInfo.primaryCpuAbi = null;
5683                pkg.applicationInfo.secondaryCpuAbi = null;
5684                if (isMultiArch(pkg.applicationInfo)) {
5685                    // Warn if we've set an abiOverride for multi-lib packages..
5686                    // By definition, we need to copy both 32 and 64 bit libraries for
5687                    // such packages.
5688                    if (pkg.cpuAbiOverride != null
5689                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5690                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5691                    }
5692
5693                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5694                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5695                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5696                        if (isAsec) {
5697                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5698                        } else {
5699                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5700                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5701                                    useIsaSpecificSubdirs);
5702                        }
5703                    }
5704
5705                    maybeThrowExceptionForMultiArchCopy(
5706                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5707
5708                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5709                        if (isAsec) {
5710                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5711                        } else {
5712                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5713                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5714                                    useIsaSpecificSubdirs);
5715                        }
5716                    }
5717
5718                    maybeThrowExceptionForMultiArchCopy(
5719                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5720
5721                    if (abi64 >= 0) {
5722                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5723                    }
5724
5725                    if (abi32 >= 0) {
5726                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5727                        if (abi64 >= 0) {
5728                            pkg.applicationInfo.secondaryCpuAbi = abi;
5729                        } else {
5730                            pkg.applicationInfo.primaryCpuAbi = abi;
5731                        }
5732                    }
5733                } else {
5734                    String[] abiList = (cpuAbiOverride != null) ?
5735                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5736
5737                    // Enable gross and lame hacks for apps that are built with old
5738                    // SDK tools. We must scan their APKs for renderscript bitcode and
5739                    // not launch them if it's present. Don't bother checking on devices
5740                    // that don't have 64 bit support.
5741                    boolean needsRenderScriptOverride = false;
5742                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5743                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5744                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5745                        needsRenderScriptOverride = true;
5746                    }
5747
5748                    final int copyRet;
5749                    if (isAsec) {
5750                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5751                    } else {
5752                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5753                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5754                    }
5755
5756                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5757                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5758                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5759                    }
5760
5761                    if (copyRet >= 0) {
5762                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5763                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5764                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5765                    } else if (needsRenderScriptOverride) {
5766                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5767                    }
5768                }
5769            } catch (IOException ioe) {
5770                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5771            } finally {
5772                IoUtils.closeQuietly(handle);
5773            }
5774
5775            // Now that we've calculated the ABIs and determined if it's an internal app,
5776            // we will go ahead and populate the nativeLibraryPath.
5777            setNativeLibraryPaths(pkg);
5778
5779            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5780            final int[] userIds = sUserManager.getUserIds();
5781            synchronized (mInstallLock) {
5782                // Create a native library symlink only if we have native libraries
5783                // and if the native libraries are 32 bit libraries. We do not provide
5784                // this symlink for 64 bit libraries.
5785                if (pkg.applicationInfo.primaryCpuAbi != null &&
5786                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5787                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5788                    for (int userId : userIds) {
5789                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5790                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5791                                    "Failed linking native library dir (user=" + userId + ")");
5792                        }
5793                    }
5794                }
5795            }
5796        }
5797
5798        // This is a special case for the "system" package, where the ABI is
5799        // dictated by the zygote configuration (and init.rc). We should keep track
5800        // of this ABI so that we can deal with "normal" applications that run under
5801        // the same UID correctly.
5802        if (mPlatformPackage == pkg) {
5803            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5804                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5805        }
5806
5807        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5808        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5809        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5810        // Copy the derived override back to the parsed package, so that we can
5811        // update the package settings accordingly.
5812        pkg.cpuAbiOverride = cpuAbiOverride;
5813
5814        if (DEBUG_ABI_SELECTION) {
5815            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5816                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5817                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5818        }
5819
5820        // Push the derived path down into PackageSettings so we know what to
5821        // clean up at uninstall time.
5822        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5823
5824        if (DEBUG_ABI_SELECTION) {
5825            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5826                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5827                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5828        }
5829
5830        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5831            // We don't do this here during boot because we can do it all
5832            // at once after scanning all existing packages.
5833            //
5834            // We also do this *before* we perform dexopt on this package, so that
5835            // we can avoid redundant dexopts, and also to make sure we've got the
5836            // code and package path correct.
5837            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5838                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5839        }
5840
5841        if ((scanFlags & SCAN_NO_DEX) == 0) {
5842            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5843                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5844                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5845            }
5846        }
5847
5848        if (mFactoryTest && pkg.requestedPermissions.contains(
5849                android.Manifest.permission.FACTORY_TEST)) {
5850            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5851        }
5852
5853        ArrayList<PackageParser.Package> clientLibPkgs = null;
5854
5855        // writer
5856        synchronized (mPackages) {
5857            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5858                // Only system apps can add new shared libraries.
5859                if (pkg.libraryNames != null) {
5860                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5861                        String name = pkg.libraryNames.get(i);
5862                        boolean allowed = false;
5863                        if (isUpdatedSystemApp(pkg)) {
5864                            // New library entries can only be added through the
5865                            // system image.  This is important to get rid of a lot
5866                            // of nasty edge cases: for example if we allowed a non-
5867                            // system update of the app to add a library, then uninstalling
5868                            // the update would make the library go away, and assumptions
5869                            // we made such as through app install filtering would now
5870                            // have allowed apps on the device which aren't compatible
5871                            // with it.  Better to just have the restriction here, be
5872                            // conservative, and create many fewer cases that can negatively
5873                            // impact the user experience.
5874                            final PackageSetting sysPs = mSettings
5875                                    .getDisabledSystemPkgLPr(pkg.packageName);
5876                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5877                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5878                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5879                                        allowed = true;
5880                                        allowed = true;
5881                                        break;
5882                                    }
5883                                }
5884                            }
5885                        } else {
5886                            allowed = true;
5887                        }
5888                        if (allowed) {
5889                            if (!mSharedLibraries.containsKey(name)) {
5890                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5891                            } else if (!name.equals(pkg.packageName)) {
5892                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5893                                        + name + " already exists; skipping");
5894                            }
5895                        } else {
5896                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5897                                    + name + " that is not declared on system image; skipping");
5898                        }
5899                    }
5900                    if ((scanFlags&SCAN_BOOTING) == 0) {
5901                        // If we are not booting, we need to update any applications
5902                        // that are clients of our shared library.  If we are booting,
5903                        // this will all be done once the scan is complete.
5904                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5905                    }
5906                }
5907            }
5908        }
5909
5910        // We also need to dexopt any apps that are dependent on this library.  Note that
5911        // if these fail, we should abort the install since installing the library will
5912        // result in some apps being broken.
5913        if (clientLibPkgs != null) {
5914            if ((scanFlags & SCAN_NO_DEX) == 0) {
5915                for (int i = 0; i < clientLibPkgs.size(); i++) {
5916                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5917                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5918                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5919                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5920                                "scanPackageLI failed to dexopt clientLibPkgs");
5921                    }
5922                }
5923            }
5924        }
5925
5926        // Request the ActivityManager to kill the process(only for existing packages)
5927        // so that we do not end up in a confused state while the user is still using the older
5928        // version of the application while the new one gets installed.
5929        if ((scanFlags & SCAN_REPLACING) != 0) {
5930            killApplication(pkg.applicationInfo.packageName,
5931                        pkg.applicationInfo.uid, "update pkg");
5932        }
5933
5934        // Also need to kill any apps that are dependent on the library.
5935        if (clientLibPkgs != null) {
5936            for (int i=0; i<clientLibPkgs.size(); i++) {
5937                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5938                killApplication(clientPkg.applicationInfo.packageName,
5939                        clientPkg.applicationInfo.uid, "update lib");
5940            }
5941        }
5942
5943        // writer
5944        synchronized (mPackages) {
5945            // We don't expect installation to fail beyond this point
5946
5947            // Add the new setting to mSettings
5948            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5949            // Add the new setting to mPackages
5950            mPackages.put(pkg.applicationInfo.packageName, pkg);
5951            // Make sure we don't accidentally delete its data.
5952            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5953            while (iter.hasNext()) {
5954                PackageCleanItem item = iter.next();
5955                if (pkgName.equals(item.packageName)) {
5956                    iter.remove();
5957                }
5958            }
5959
5960            // Take care of first install / last update times.
5961            if (currentTime != 0) {
5962                if (pkgSetting.firstInstallTime == 0) {
5963                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5964                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5965                    pkgSetting.lastUpdateTime = currentTime;
5966                }
5967            } else if (pkgSetting.firstInstallTime == 0) {
5968                // We need *something*.  Take time time stamp of the file.
5969                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5970            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5971                if (scanFileTime != pkgSetting.timeStamp) {
5972                    // A package on the system image has changed; consider this
5973                    // to be an update.
5974                    pkgSetting.lastUpdateTime = scanFileTime;
5975                }
5976            }
5977
5978            // Add the package's KeySets to the global KeySetManagerService
5979            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5980            try {
5981                // Old KeySetData no longer valid.
5982                ksms.removeAppKeySetDataLPw(pkg.packageName);
5983                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5984                if (pkg.mKeySetMapping != null) {
5985                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5986                            pkg.mKeySetMapping.entrySet()) {
5987                        if (entry.getValue() != null) {
5988                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5989                                                          entry.getValue(), entry.getKey());
5990                        }
5991                    }
5992                    if (pkg.mUpgradeKeySets != null) {
5993                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5994                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5995                        }
5996                    }
5997                }
5998            } catch (NullPointerException e) {
5999                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6000            } catch (IllegalArgumentException e) {
6001                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6002            }
6003
6004            int N = pkg.providers.size();
6005            StringBuilder r = null;
6006            int i;
6007            for (i=0; i<N; i++) {
6008                PackageParser.Provider p = pkg.providers.get(i);
6009                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6010                        p.info.processName, pkg.applicationInfo.uid);
6011                mProviders.addProvider(p);
6012                p.syncable = p.info.isSyncable;
6013                if (p.info.authority != null) {
6014                    String names[] = p.info.authority.split(";");
6015                    p.info.authority = null;
6016                    for (int j = 0; j < names.length; j++) {
6017                        if (j == 1 && p.syncable) {
6018                            // We only want the first authority for a provider to possibly be
6019                            // syncable, so if we already added this provider using a different
6020                            // authority clear the syncable flag. We copy the provider before
6021                            // changing it because the mProviders object contains a reference
6022                            // to a provider that we don't want to change.
6023                            // Only do this for the second authority since the resulting provider
6024                            // object can be the same for all future authorities for this provider.
6025                            p = new PackageParser.Provider(p);
6026                            p.syncable = false;
6027                        }
6028                        if (!mProvidersByAuthority.containsKey(names[j])) {
6029                            mProvidersByAuthority.put(names[j], p);
6030                            if (p.info.authority == null) {
6031                                p.info.authority = names[j];
6032                            } else {
6033                                p.info.authority = p.info.authority + ";" + names[j];
6034                            }
6035                            if (DEBUG_PACKAGE_SCANNING) {
6036                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6037                                    Log.d(TAG, "Registered content provider: " + names[j]
6038                                            + ", className = " + p.info.name + ", isSyncable = "
6039                                            + p.info.isSyncable);
6040                            }
6041                        } else {
6042                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6043                            Slog.w(TAG, "Skipping provider name " + names[j] +
6044                                    " (in package " + pkg.applicationInfo.packageName +
6045                                    "): name already used by "
6046                                    + ((other != null && other.getComponentName() != null)
6047                                            ? other.getComponentName().getPackageName() : "?"));
6048                        }
6049                    }
6050                }
6051                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6052                    if (r == null) {
6053                        r = new StringBuilder(256);
6054                    } else {
6055                        r.append(' ');
6056                    }
6057                    r.append(p.info.name);
6058                }
6059            }
6060            if (r != null) {
6061                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6062            }
6063
6064            N = pkg.services.size();
6065            r = null;
6066            for (i=0; i<N; i++) {
6067                PackageParser.Service s = pkg.services.get(i);
6068                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6069                        s.info.processName, pkg.applicationInfo.uid);
6070                mServices.addService(s);
6071                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6072                    if (r == null) {
6073                        r = new StringBuilder(256);
6074                    } else {
6075                        r.append(' ');
6076                    }
6077                    r.append(s.info.name);
6078                }
6079            }
6080            if (r != null) {
6081                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6082            }
6083
6084            N = pkg.receivers.size();
6085            r = null;
6086            for (i=0; i<N; i++) {
6087                PackageParser.Activity a = pkg.receivers.get(i);
6088                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6089                        a.info.processName, pkg.applicationInfo.uid);
6090                mReceivers.addActivity(a, "receiver");
6091                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6092                    if (r == null) {
6093                        r = new StringBuilder(256);
6094                    } else {
6095                        r.append(' ');
6096                    }
6097                    r.append(a.info.name);
6098                }
6099            }
6100            if (r != null) {
6101                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6102            }
6103
6104            N = pkg.activities.size();
6105            r = null;
6106            for (i=0; i<N; i++) {
6107                PackageParser.Activity a = pkg.activities.get(i);
6108                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6109                        a.info.processName, pkg.applicationInfo.uid);
6110                mActivities.addActivity(a, "activity");
6111                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6112                    if (r == null) {
6113                        r = new StringBuilder(256);
6114                    } else {
6115                        r.append(' ');
6116                    }
6117                    r.append(a.info.name);
6118                }
6119            }
6120            if (r != null) {
6121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6122            }
6123
6124            N = pkg.permissionGroups.size();
6125            r = null;
6126            for (i=0; i<N; i++) {
6127                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6128                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6129                if (cur == null) {
6130                    mPermissionGroups.put(pg.info.name, pg);
6131                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6132                        if (r == null) {
6133                            r = new StringBuilder(256);
6134                        } else {
6135                            r.append(' ');
6136                        }
6137                        r.append(pg.info.name);
6138                    }
6139                } else {
6140                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6141                            + pg.info.packageName + " ignored: original from "
6142                            + cur.info.packageName);
6143                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6144                        if (r == null) {
6145                            r = new StringBuilder(256);
6146                        } else {
6147                            r.append(' ');
6148                        }
6149                        r.append("DUP:");
6150                        r.append(pg.info.name);
6151                    }
6152                }
6153            }
6154            if (r != null) {
6155                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6156            }
6157
6158            N = pkg.permissions.size();
6159            r = null;
6160            for (i=0; i<N; i++) {
6161                PackageParser.Permission p = pkg.permissions.get(i);
6162                HashMap<String, BasePermission> permissionMap =
6163                        p.tree ? mSettings.mPermissionTrees
6164                        : mSettings.mPermissions;
6165                p.group = mPermissionGroups.get(p.info.group);
6166                if (p.info.group == null || p.group != null) {
6167                    BasePermission bp = permissionMap.get(p.info.name);
6168
6169                    // Allow system apps to redefine non-system permissions
6170                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6171                        final boolean currentOwnerIsSystem = (bp.perm != null
6172                                && isSystemApp(bp.perm.owner));
6173                        if (isSystemApp(p.owner)) {
6174                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6175                                // It's a built-in permission and no owner, take ownership now
6176                                bp.packageSetting = pkgSetting;
6177                                bp.perm = p;
6178                                bp.uid = pkg.applicationInfo.uid;
6179                                bp.sourcePackage = p.info.packageName;
6180                            } else if (!currentOwnerIsSystem) {
6181                                String msg = "New decl " + p.owner + " of permission  "
6182                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6183                                reportSettingsProblem(Log.WARN, msg);
6184                                bp = null;
6185                            }
6186                        }
6187                    }
6188
6189                    if (bp == null) {
6190                        bp = new BasePermission(p.info.name, p.info.packageName,
6191                                BasePermission.TYPE_NORMAL);
6192                        permissionMap.put(p.info.name, bp);
6193                    }
6194
6195                    if (bp.perm == null) {
6196                        if (bp.sourcePackage == null
6197                                || bp.sourcePackage.equals(p.info.packageName)) {
6198                            BasePermission tree = findPermissionTreeLP(p.info.name);
6199                            if (tree == null
6200                                    || tree.sourcePackage.equals(p.info.packageName)) {
6201                                bp.packageSetting = pkgSetting;
6202                                bp.perm = p;
6203                                bp.uid = pkg.applicationInfo.uid;
6204                                bp.sourcePackage = p.info.packageName;
6205                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6206                                    if (r == null) {
6207                                        r = new StringBuilder(256);
6208                                    } else {
6209                                        r.append(' ');
6210                                    }
6211                                    r.append(p.info.name);
6212                                }
6213                            } else {
6214                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6215                                        + p.info.packageName + " ignored: base tree "
6216                                        + tree.name + " is from package "
6217                                        + tree.sourcePackage);
6218                            }
6219                        } else {
6220                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6221                                    + p.info.packageName + " ignored: original from "
6222                                    + bp.sourcePackage);
6223                        }
6224                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6225                        if (r == null) {
6226                            r = new StringBuilder(256);
6227                        } else {
6228                            r.append(' ');
6229                        }
6230                        r.append("DUP:");
6231                        r.append(p.info.name);
6232                    }
6233                    if (bp.perm == p) {
6234                        bp.protectionLevel = p.info.protectionLevel;
6235                    }
6236                } else {
6237                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6238                            + p.info.packageName + " ignored: no group "
6239                            + p.group);
6240                }
6241            }
6242            if (r != null) {
6243                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6244            }
6245
6246            N = pkg.instrumentation.size();
6247            r = null;
6248            for (i=0; i<N; i++) {
6249                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6250                a.info.packageName = pkg.applicationInfo.packageName;
6251                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6252                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6253                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6254                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6255                a.info.dataDir = pkg.applicationInfo.dataDir;
6256
6257                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6258                // need other information about the application, like the ABI and what not ?
6259                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6260                mInstrumentation.put(a.getComponentName(), a);
6261                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6262                    if (r == null) {
6263                        r = new StringBuilder(256);
6264                    } else {
6265                        r.append(' ');
6266                    }
6267                    r.append(a.info.name);
6268                }
6269            }
6270            if (r != null) {
6271                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6272            }
6273
6274            if (pkg.protectedBroadcasts != null) {
6275                N = pkg.protectedBroadcasts.size();
6276                for (i=0; i<N; i++) {
6277                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6278                }
6279            }
6280
6281            pkgSetting.setTimeStamp(scanFileTime);
6282
6283            // Create idmap files for pairs of (packages, overlay packages).
6284            // Note: "android", ie framework-res.apk, is handled by native layers.
6285            if (pkg.mOverlayTarget != null) {
6286                // This is an overlay package.
6287                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6288                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6289                        mOverlays.put(pkg.mOverlayTarget,
6290                                new HashMap<String, PackageParser.Package>());
6291                    }
6292                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6293                    map.put(pkg.packageName, pkg);
6294                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6295                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6296                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6297                                "scanPackageLI failed to createIdmap");
6298                    }
6299                }
6300            } else if (mOverlays.containsKey(pkg.packageName) &&
6301                    !pkg.packageName.equals("android")) {
6302                // This is a regular package, with one or more known overlay packages.
6303                createIdmapsForPackageLI(pkg);
6304            }
6305        }
6306
6307        return pkg;
6308    }
6309
6310    /**
6311     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6312     * i.e, so that all packages can be run inside a single process if required.
6313     *
6314     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6315     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6316     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6317     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6318     * updating a package that belongs to a shared user.
6319     *
6320     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6321     * adds unnecessary complexity.
6322     */
6323    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6324            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6325        String requiredInstructionSet = null;
6326        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6327            requiredInstructionSet = VMRuntime.getInstructionSet(
6328                     scannedPackage.applicationInfo.primaryCpuAbi);
6329        }
6330
6331        PackageSetting requirer = null;
6332        for (PackageSetting ps : packagesForUser) {
6333            // If packagesForUser contains scannedPackage, we skip it. This will happen
6334            // when scannedPackage is an update of an existing package. Without this check,
6335            // we will never be able to change the ABI of any package belonging to a shared
6336            // user, even if it's compatible with other packages.
6337            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6338                if (ps.primaryCpuAbiString == null) {
6339                    continue;
6340                }
6341
6342                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6343                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6344                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6345                    // this but there's not much we can do.
6346                    String errorMessage = "Instruction set mismatch, "
6347                            + ((requirer == null) ? "[caller]" : requirer)
6348                            + " requires " + requiredInstructionSet + " whereas " + ps
6349                            + " requires " + instructionSet;
6350                    Slog.w(TAG, errorMessage);
6351                }
6352
6353                if (requiredInstructionSet == null) {
6354                    requiredInstructionSet = instructionSet;
6355                    requirer = ps;
6356                }
6357            }
6358        }
6359
6360        if (requiredInstructionSet != null) {
6361            String adjustedAbi;
6362            if (requirer != null) {
6363                // requirer != null implies that either scannedPackage was null or that scannedPackage
6364                // did not require an ABI, in which case we have to adjust scannedPackage to match
6365                // the ABI of the set (which is the same as requirer's ABI)
6366                adjustedAbi = requirer.primaryCpuAbiString;
6367                if (scannedPackage != null) {
6368                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6369                }
6370            } else {
6371                // requirer == null implies that we're updating all ABIs in the set to
6372                // match scannedPackage.
6373                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6374            }
6375
6376            for (PackageSetting ps : packagesForUser) {
6377                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6378                    if (ps.primaryCpuAbiString != null) {
6379                        continue;
6380                    }
6381
6382                    ps.primaryCpuAbiString = adjustedAbi;
6383                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6384                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6385                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6386
6387                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6388                                deferDexOpt, true) == DEX_OPT_FAILED) {
6389                            ps.primaryCpuAbiString = null;
6390                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6391                            return;
6392                        } else {
6393                            mInstaller.rmdex(ps.codePathString,
6394                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6395                        }
6396                    }
6397                }
6398            }
6399        }
6400    }
6401
6402    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6403        synchronized (mPackages) {
6404            mResolverReplaced = true;
6405            // Set up information for custom user intent resolution activity.
6406            mResolveActivity.applicationInfo = pkg.applicationInfo;
6407            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6408            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6409            mResolveActivity.processName = null;
6410            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6411            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6412                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6413            mResolveActivity.theme = 0;
6414            mResolveActivity.exported = true;
6415            mResolveActivity.enabled = true;
6416            mResolveInfo.activityInfo = mResolveActivity;
6417            mResolveInfo.priority = 0;
6418            mResolveInfo.preferredOrder = 0;
6419            mResolveInfo.match = 0;
6420            mResolveComponentName = mCustomResolverComponentName;
6421            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6422                    mResolveComponentName);
6423        }
6424    }
6425
6426    private static String calculateBundledApkRoot(final String codePathString) {
6427        final File codePath = new File(codePathString);
6428        final File codeRoot;
6429        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6430            codeRoot = Environment.getRootDirectory();
6431        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6432            codeRoot = Environment.getOemDirectory();
6433        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6434            codeRoot = Environment.getVendorDirectory();
6435        } else {
6436            // Unrecognized code path; take its top real segment as the apk root:
6437            // e.g. /something/app/blah.apk => /something
6438            try {
6439                File f = codePath.getCanonicalFile();
6440                File parent = f.getParentFile();    // non-null because codePath is a file
6441                File tmp;
6442                while ((tmp = parent.getParentFile()) != null) {
6443                    f = parent;
6444                    parent = tmp;
6445                }
6446                codeRoot = f;
6447                Slog.w(TAG, "Unrecognized code path "
6448                        + codePath + " - using " + codeRoot);
6449            } catch (IOException e) {
6450                // Can't canonicalize the code path -- shenanigans?
6451                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6452                return Environment.getRootDirectory().getPath();
6453            }
6454        }
6455        return codeRoot.getPath();
6456    }
6457
6458    /**
6459     * Derive and set the location of native libraries for the given package,
6460     * which varies depending on where and how the package was installed.
6461     */
6462    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6463        final ApplicationInfo info = pkg.applicationInfo;
6464        final String codePath = pkg.codePath;
6465        final File codeFile = new File(codePath);
6466        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6467        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6468
6469        info.nativeLibraryRootDir = null;
6470        info.nativeLibraryRootRequiresIsa = false;
6471        info.nativeLibraryDir = null;
6472        info.secondaryNativeLibraryDir = null;
6473
6474        if (isApkFile(codeFile)) {
6475            // Monolithic install
6476            if (bundledApp) {
6477                // If "/system/lib64/apkname" exists, assume that is the per-package
6478                // native library directory to use; otherwise use "/system/lib/apkname".
6479                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6480                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6481                        getPrimaryInstructionSet(info));
6482
6483                // This is a bundled system app so choose the path based on the ABI.
6484                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6485                // is just the default path.
6486                final String apkName = deriveCodePathName(codePath);
6487                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6488                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6489                        apkName).getAbsolutePath();
6490
6491                if (info.secondaryCpuAbi != null) {
6492                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6493                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6494                            secondaryLibDir, apkName).getAbsolutePath();
6495                }
6496            } else if (asecApp) {
6497                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6498                        .getAbsolutePath();
6499            } else {
6500                final String apkName = deriveCodePathName(codePath);
6501                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6502                        .getAbsolutePath();
6503            }
6504
6505            info.nativeLibraryRootRequiresIsa = false;
6506            info.nativeLibraryDir = info.nativeLibraryRootDir;
6507        } else {
6508            // Cluster install
6509            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6510            info.nativeLibraryRootRequiresIsa = true;
6511
6512            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6513                    getPrimaryInstructionSet(info)).getAbsolutePath();
6514
6515            if (info.secondaryCpuAbi != null) {
6516                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6517                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6518            }
6519        }
6520    }
6521
6522    /**
6523     * Calculate the abis and roots for a bundled app. These can uniquely
6524     * be determined from the contents of the system partition, i.e whether
6525     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6526     * of this information, and instead assume that the system was built
6527     * sensibly.
6528     */
6529    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6530                                           PackageSetting pkgSetting) {
6531        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6532
6533        // If "/system/lib64/apkname" exists, assume that is the per-package
6534        // native library directory to use; otherwise use "/system/lib/apkname".
6535        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6536        setBundledAppAbi(pkg, apkRoot, apkName);
6537        // pkgSetting might be null during rescan following uninstall of updates
6538        // to a bundled app, so accommodate that possibility.  The settings in
6539        // that case will be established later from the parsed package.
6540        //
6541        // If the settings aren't null, sync them up with what we've just derived.
6542        // note that apkRoot isn't stored in the package settings.
6543        if (pkgSetting != null) {
6544            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6545            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6546        }
6547    }
6548
6549    /**
6550     * Deduces the ABI of a bundled app and sets the relevant fields on the
6551     * parsed pkg object.
6552     *
6553     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6554     *        under which system libraries are installed.
6555     * @param apkName the name of the installed package.
6556     */
6557    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6558        final File codeFile = new File(pkg.codePath);
6559
6560        final boolean has64BitLibs;
6561        final boolean has32BitLibs;
6562        if (isApkFile(codeFile)) {
6563            // Monolithic install
6564            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6565            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6566        } else {
6567            // Cluster install
6568            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6569            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6570                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6571                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6572                has64BitLibs = (new File(rootDir, isa)).exists();
6573            } else {
6574                has64BitLibs = false;
6575            }
6576            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6577                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6578                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6579                has32BitLibs = (new File(rootDir, isa)).exists();
6580            } else {
6581                has32BitLibs = false;
6582            }
6583        }
6584
6585        if (has64BitLibs && !has32BitLibs) {
6586            // The package has 64 bit libs, but not 32 bit libs. Its primary
6587            // ABI should be 64 bit. We can safely assume here that the bundled
6588            // native libraries correspond to the most preferred ABI in the list.
6589
6590            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6591            pkg.applicationInfo.secondaryCpuAbi = null;
6592        } else if (has32BitLibs && !has64BitLibs) {
6593            // The package has 32 bit libs but not 64 bit libs. Its primary
6594            // ABI should be 32 bit.
6595
6596            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6597            pkg.applicationInfo.secondaryCpuAbi = null;
6598        } else if (has32BitLibs && has64BitLibs) {
6599            // The application has both 64 and 32 bit bundled libraries. We check
6600            // here that the app declares multiArch support, and warn if it doesn't.
6601            //
6602            // We will be lenient here and record both ABIs. The primary will be the
6603            // ABI that's higher on the list, i.e, a device that's configured to prefer
6604            // 64 bit apps will see a 64 bit primary ABI,
6605
6606            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6607                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6608            }
6609
6610            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6611                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6612                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6613            } else {
6614                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6615                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6616            }
6617        } else {
6618            pkg.applicationInfo.primaryCpuAbi = null;
6619            pkg.applicationInfo.secondaryCpuAbi = null;
6620        }
6621    }
6622
6623    private void killApplication(String pkgName, int appId, String reason) {
6624        // Request the ActivityManager to kill the process(only for existing packages)
6625        // so that we do not end up in a confused state while the user is still using the older
6626        // version of the application while the new one gets installed.
6627        IActivityManager am = ActivityManagerNative.getDefault();
6628        if (am != null) {
6629            try {
6630                am.killApplicationWithAppId(pkgName, appId, reason);
6631            } catch (RemoteException e) {
6632            }
6633        }
6634    }
6635
6636    void removePackageLI(PackageSetting ps, boolean chatty) {
6637        if (DEBUG_INSTALL) {
6638            if (chatty)
6639                Log.d(TAG, "Removing package " + ps.name);
6640        }
6641
6642        // writer
6643        synchronized (mPackages) {
6644            mPackages.remove(ps.name);
6645            final PackageParser.Package pkg = ps.pkg;
6646            if (pkg != null) {
6647                cleanPackageDataStructuresLILPw(pkg, chatty);
6648            }
6649        }
6650    }
6651
6652    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6653        if (DEBUG_INSTALL) {
6654            if (chatty)
6655                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6656        }
6657
6658        // writer
6659        synchronized (mPackages) {
6660            mPackages.remove(pkg.applicationInfo.packageName);
6661            cleanPackageDataStructuresLILPw(pkg, chatty);
6662        }
6663    }
6664
6665    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6666        int N = pkg.providers.size();
6667        StringBuilder r = null;
6668        int i;
6669        for (i=0; i<N; i++) {
6670            PackageParser.Provider p = pkg.providers.get(i);
6671            mProviders.removeProvider(p);
6672            if (p.info.authority == null) {
6673
6674                /* There was another ContentProvider with this authority when
6675                 * this app was installed so this authority is null,
6676                 * Ignore it as we don't have to unregister the provider.
6677                 */
6678                continue;
6679            }
6680            String names[] = p.info.authority.split(";");
6681            for (int j = 0; j < names.length; j++) {
6682                if (mProvidersByAuthority.get(names[j]) == p) {
6683                    mProvidersByAuthority.remove(names[j]);
6684                    if (DEBUG_REMOVE) {
6685                        if (chatty)
6686                            Log.d(TAG, "Unregistered content provider: " + names[j]
6687                                    + ", className = " + p.info.name + ", isSyncable = "
6688                                    + p.info.isSyncable);
6689                    }
6690                }
6691            }
6692            if (DEBUG_REMOVE && chatty) {
6693                if (r == null) {
6694                    r = new StringBuilder(256);
6695                } else {
6696                    r.append(' ');
6697                }
6698                r.append(p.info.name);
6699            }
6700        }
6701        if (r != null) {
6702            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6703        }
6704
6705        N = pkg.services.size();
6706        r = null;
6707        for (i=0; i<N; i++) {
6708            PackageParser.Service s = pkg.services.get(i);
6709            mServices.removeService(s);
6710            if (chatty) {
6711                if (r == null) {
6712                    r = new StringBuilder(256);
6713                } else {
6714                    r.append(' ');
6715                }
6716                r.append(s.info.name);
6717            }
6718        }
6719        if (r != null) {
6720            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6721        }
6722
6723        N = pkg.receivers.size();
6724        r = null;
6725        for (i=0; i<N; i++) {
6726            PackageParser.Activity a = pkg.receivers.get(i);
6727            mReceivers.removeActivity(a, "receiver");
6728            if (DEBUG_REMOVE && chatty) {
6729                if (r == null) {
6730                    r = new StringBuilder(256);
6731                } else {
6732                    r.append(' ');
6733                }
6734                r.append(a.info.name);
6735            }
6736        }
6737        if (r != null) {
6738            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6739        }
6740
6741        N = pkg.activities.size();
6742        r = null;
6743        for (i=0; i<N; i++) {
6744            PackageParser.Activity a = pkg.activities.get(i);
6745            mActivities.removeActivity(a, "activity");
6746            if (DEBUG_REMOVE && chatty) {
6747                if (r == null) {
6748                    r = new StringBuilder(256);
6749                } else {
6750                    r.append(' ');
6751                }
6752                r.append(a.info.name);
6753            }
6754        }
6755        if (r != null) {
6756            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6757        }
6758
6759        N = pkg.permissions.size();
6760        r = null;
6761        for (i=0; i<N; i++) {
6762            PackageParser.Permission p = pkg.permissions.get(i);
6763            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6764            if (bp == null) {
6765                bp = mSettings.mPermissionTrees.get(p.info.name);
6766            }
6767            if (bp != null && bp.perm == p) {
6768                bp.perm = null;
6769                if (DEBUG_REMOVE && chatty) {
6770                    if (r == null) {
6771                        r = new StringBuilder(256);
6772                    } else {
6773                        r.append(' ');
6774                    }
6775                    r.append(p.info.name);
6776                }
6777            }
6778            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6779                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6780                if (appOpPerms != null) {
6781                    appOpPerms.remove(pkg.packageName);
6782                }
6783            }
6784        }
6785        if (r != null) {
6786            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6787        }
6788
6789        N = pkg.requestedPermissions.size();
6790        r = null;
6791        for (i=0; i<N; i++) {
6792            String perm = pkg.requestedPermissions.get(i);
6793            BasePermission bp = mSettings.mPermissions.get(perm);
6794            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6795                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6796                if (appOpPerms != null) {
6797                    appOpPerms.remove(pkg.packageName);
6798                    if (appOpPerms.isEmpty()) {
6799                        mAppOpPermissionPackages.remove(perm);
6800                    }
6801                }
6802            }
6803        }
6804        if (r != null) {
6805            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6806        }
6807
6808        N = pkg.instrumentation.size();
6809        r = null;
6810        for (i=0; i<N; i++) {
6811            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6812            mInstrumentation.remove(a.getComponentName());
6813            if (DEBUG_REMOVE && chatty) {
6814                if (r == null) {
6815                    r = new StringBuilder(256);
6816                } else {
6817                    r.append(' ');
6818                }
6819                r.append(a.info.name);
6820            }
6821        }
6822        if (r != null) {
6823            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6824        }
6825
6826        r = null;
6827        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6828            // Only system apps can hold shared libraries.
6829            if (pkg.libraryNames != null) {
6830                for (i=0; i<pkg.libraryNames.size(); i++) {
6831                    String name = pkg.libraryNames.get(i);
6832                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6833                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6834                        mSharedLibraries.remove(name);
6835                        if (DEBUG_REMOVE && chatty) {
6836                            if (r == null) {
6837                                r = new StringBuilder(256);
6838                            } else {
6839                                r.append(' ');
6840                            }
6841                            r.append(name);
6842                        }
6843                    }
6844                }
6845            }
6846        }
6847        if (r != null) {
6848            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6849        }
6850    }
6851
6852    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6853        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6854            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6855                return true;
6856            }
6857        }
6858        return false;
6859    }
6860
6861    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6862    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6863    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6864
6865    private void updatePermissionsLPw(String changingPkg,
6866            PackageParser.Package pkgInfo, int flags) {
6867        // Make sure there are no dangling permission trees.
6868        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6869        while (it.hasNext()) {
6870            final BasePermission bp = it.next();
6871            if (bp.packageSetting == null) {
6872                // We may not yet have parsed the package, so just see if
6873                // we still know about its settings.
6874                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6875            }
6876            if (bp.packageSetting == null) {
6877                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6878                        + " from package " + bp.sourcePackage);
6879                it.remove();
6880            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6881                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6882                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6883                            + " from package " + bp.sourcePackage);
6884                    flags |= UPDATE_PERMISSIONS_ALL;
6885                    it.remove();
6886                }
6887            }
6888        }
6889
6890        // Make sure all dynamic permissions have been assigned to a package,
6891        // and make sure there are no dangling permissions.
6892        it = mSettings.mPermissions.values().iterator();
6893        while (it.hasNext()) {
6894            final BasePermission bp = it.next();
6895            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6896                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6897                        + bp.name + " pkg=" + bp.sourcePackage
6898                        + " info=" + bp.pendingInfo);
6899                if (bp.packageSetting == null && bp.pendingInfo != null) {
6900                    final BasePermission tree = findPermissionTreeLP(bp.name);
6901                    if (tree != null && tree.perm != null) {
6902                        bp.packageSetting = tree.packageSetting;
6903                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6904                                new PermissionInfo(bp.pendingInfo));
6905                        bp.perm.info.packageName = tree.perm.info.packageName;
6906                        bp.perm.info.name = bp.name;
6907                        bp.uid = tree.uid;
6908                    }
6909                }
6910            }
6911            if (bp.packageSetting == null) {
6912                // We may not yet have parsed the package, so just see if
6913                // we still know about its settings.
6914                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6915            }
6916            if (bp.packageSetting == null) {
6917                Slog.w(TAG, "Removing dangling permission: " + bp.name
6918                        + " from package " + bp.sourcePackage);
6919                it.remove();
6920            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6921                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6922                    Slog.i(TAG, "Removing old permission: " + bp.name
6923                            + " from package " + bp.sourcePackage);
6924                    flags |= UPDATE_PERMISSIONS_ALL;
6925                    it.remove();
6926                }
6927            }
6928        }
6929
6930        // Now update the permissions for all packages, in particular
6931        // replace the granted permissions of the system packages.
6932        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6933            for (PackageParser.Package pkg : mPackages.values()) {
6934                if (pkg != pkgInfo) {
6935                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6936                            changingPkg);
6937                }
6938            }
6939        }
6940
6941        if (pkgInfo != null) {
6942            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6943        }
6944    }
6945
6946    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6947            String packageOfInterest) {
6948        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6949        if (ps == null) {
6950            return;
6951        }
6952        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6953        HashSet<String> origPermissions = gp.grantedPermissions;
6954        boolean changedPermission = false;
6955
6956        if (replace) {
6957            ps.permissionsFixed = false;
6958            if (gp == ps) {
6959                origPermissions = new HashSet<String>(gp.grantedPermissions);
6960                gp.grantedPermissions.clear();
6961                gp.gids = mGlobalGids;
6962            }
6963        }
6964
6965        if (gp.gids == null) {
6966            gp.gids = mGlobalGids;
6967        }
6968
6969        final int N = pkg.requestedPermissions.size();
6970        for (int i=0; i<N; i++) {
6971            final String name = pkg.requestedPermissions.get(i);
6972            final boolean required = pkg.requestedPermissionsRequired.get(i);
6973            final BasePermission bp = mSettings.mPermissions.get(name);
6974            if (DEBUG_INSTALL) {
6975                if (gp != ps) {
6976                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6977                }
6978            }
6979
6980            if (bp == null || bp.packageSetting == null) {
6981                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6982                    Slog.w(TAG, "Unknown permission " + name
6983                            + " in package " + pkg.packageName);
6984                }
6985                continue;
6986            }
6987
6988            final String perm = bp.name;
6989            boolean allowed;
6990            boolean allowedSig = false;
6991            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6992                // Keep track of app op permissions.
6993                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6994                if (pkgs == null) {
6995                    pkgs = new ArraySet<>();
6996                    mAppOpPermissionPackages.put(bp.name, pkgs);
6997                }
6998                pkgs.add(pkg.packageName);
6999            }
7000            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7001            if (level == PermissionInfo.PROTECTION_NORMAL
7002                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
7003                // We grant a normal or dangerous permission if any of the following
7004                // are true:
7005                // 1) The permission is required
7006                // 2) The permission is optional, but was granted in the past
7007                // 3) The permission is optional, but was requested by an
7008                //    app in /system (not /data)
7009                //
7010                // Otherwise, reject the permission.
7011                allowed = (required || origPermissions.contains(perm)
7012                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
7013            } else if (bp.packageSetting == null) {
7014                // This permission is invalid; skip it.
7015                allowed = false;
7016            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
7017                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
7018                if (allowed) {
7019                    allowedSig = true;
7020                }
7021            } else {
7022                allowed = false;
7023            }
7024            if (DEBUG_INSTALL) {
7025                if (gp != ps) {
7026                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7027                }
7028            }
7029            if (allowed) {
7030                if (!isSystemApp(ps) && ps.permissionsFixed) {
7031                    // If this is an existing, non-system package, then
7032                    // we can't add any new permissions to it.
7033                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7034                        // Except...  if this is a permission that was added
7035                        // to the platform (note: need to only do this when
7036                        // updating the platform).
7037                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7038                    }
7039                }
7040                if (allowed) {
7041                    if (!gp.grantedPermissions.contains(perm)) {
7042                        changedPermission = true;
7043                        gp.grantedPermissions.add(perm);
7044                        gp.gids = appendInts(gp.gids, bp.gids);
7045                    } else if (!ps.haveGids) {
7046                        gp.gids = appendInts(gp.gids, bp.gids);
7047                    }
7048                } else {
7049                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7050                        Slog.w(TAG, "Not granting permission " + perm
7051                                + " to package " + pkg.packageName
7052                                + " because it was previously installed without");
7053                    }
7054                }
7055            } else {
7056                if (gp.grantedPermissions.remove(perm)) {
7057                    changedPermission = true;
7058                    gp.gids = removeInts(gp.gids, bp.gids);
7059                    Slog.i(TAG, "Un-granting permission " + perm
7060                            + " from package " + pkg.packageName
7061                            + " (protectionLevel=" + bp.protectionLevel
7062                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7063                            + ")");
7064                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7065                    // Don't print warning for app op permissions, since it is fine for them
7066                    // not to be granted, there is a UI for the user to decide.
7067                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7068                        Slog.w(TAG, "Not granting permission " + perm
7069                                + " to package " + pkg.packageName
7070                                + " (protectionLevel=" + bp.protectionLevel
7071                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7072                                + ")");
7073                    }
7074                }
7075            }
7076        }
7077
7078        if ((changedPermission || replace) && !ps.permissionsFixed &&
7079                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7080            // This is the first that we have heard about this package, so the
7081            // permissions we have now selected are fixed until explicitly
7082            // changed.
7083            ps.permissionsFixed = true;
7084        }
7085        ps.haveGids = true;
7086    }
7087
7088    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7089        boolean allowed = false;
7090        final int NP = PackageParser.NEW_PERMISSIONS.length;
7091        for (int ip=0; ip<NP; ip++) {
7092            final PackageParser.NewPermissionInfo npi
7093                    = PackageParser.NEW_PERMISSIONS[ip];
7094            if (npi.name.equals(perm)
7095                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7096                allowed = true;
7097                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7098                        + pkg.packageName);
7099                break;
7100            }
7101        }
7102        return allowed;
7103    }
7104
7105    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7106                                          BasePermission bp, HashSet<String> origPermissions) {
7107        boolean allowed;
7108        allowed = (compareSignatures(
7109                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7110                        == PackageManager.SIGNATURE_MATCH)
7111                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7112                        == PackageManager.SIGNATURE_MATCH);
7113        if (!allowed && (bp.protectionLevel
7114                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7115            if (isSystemApp(pkg)) {
7116                // For updated system applications, a system permission
7117                // is granted only if it had been defined by the original application.
7118                if (isUpdatedSystemApp(pkg)) {
7119                    final PackageSetting sysPs = mSettings
7120                            .getDisabledSystemPkgLPr(pkg.packageName);
7121                    final GrantedPermissions origGp = sysPs.sharedUser != null
7122                            ? sysPs.sharedUser : sysPs;
7123
7124                    if (origGp.grantedPermissions.contains(perm)) {
7125                        // If the original was granted this permission, we take
7126                        // that grant decision as read and propagate it to the
7127                        // update.
7128                        if (sysPs.isPrivileged()) {
7129                            allowed = true;
7130                        }
7131                    } else {
7132                        // The system apk may have been updated with an older
7133                        // version of the one on the data partition, but which
7134                        // granted a new system permission that it didn't have
7135                        // before.  In this case we do want to allow the app to
7136                        // now get the new permission if the ancestral apk is
7137                        // privileged to get it.
7138                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7139                            for (int j=0;
7140                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7141                                if (perm.equals(
7142                                        sysPs.pkg.requestedPermissions.get(j))) {
7143                                    allowed = true;
7144                                    break;
7145                                }
7146                            }
7147                        }
7148                    }
7149                } else {
7150                    allowed = isPrivilegedApp(pkg);
7151                }
7152            }
7153        }
7154        if (!allowed && (bp.protectionLevel
7155                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7156            // For development permissions, a development permission
7157            // is granted only if it was already granted.
7158            allowed = origPermissions.contains(perm);
7159        }
7160        return allowed;
7161    }
7162
7163    final class ActivityIntentResolver
7164            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7165        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7166                boolean defaultOnly, int userId) {
7167            if (!sUserManager.exists(userId)) return null;
7168            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7169            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7170        }
7171
7172        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7173                int userId) {
7174            if (!sUserManager.exists(userId)) return null;
7175            mFlags = flags;
7176            return super.queryIntent(intent, resolvedType,
7177                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7178        }
7179
7180        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7181                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7182            if (!sUserManager.exists(userId)) return null;
7183            if (packageActivities == null) {
7184                return null;
7185            }
7186            mFlags = flags;
7187            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7188            final int N = packageActivities.size();
7189            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7190                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7191
7192            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7193            for (int i = 0; i < N; ++i) {
7194                intentFilters = packageActivities.get(i).intents;
7195                if (intentFilters != null && intentFilters.size() > 0) {
7196                    PackageParser.ActivityIntentInfo[] array =
7197                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7198                    intentFilters.toArray(array);
7199                    listCut.add(array);
7200                }
7201            }
7202            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7203        }
7204
7205        public final void addActivity(PackageParser.Activity a, String type) {
7206            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7207            mActivities.put(a.getComponentName(), a);
7208            if (DEBUG_SHOW_INFO)
7209                Log.v(
7210                TAG, "  " + type + " " +
7211                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7212            if (DEBUG_SHOW_INFO)
7213                Log.v(TAG, "    Class=" + a.info.name);
7214            final int NI = a.intents.size();
7215            for (int j=0; j<NI; j++) {
7216                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7217                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7218                    intent.setPriority(0);
7219                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7220                            + a.className + " with priority > 0, forcing to 0");
7221                }
7222                if (DEBUG_SHOW_INFO) {
7223                    Log.v(TAG, "    IntentFilter:");
7224                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7225                }
7226                if (!intent.debugCheck()) {
7227                    Log.w(TAG, "==> For Activity " + a.info.name);
7228                }
7229                addFilter(intent);
7230            }
7231        }
7232
7233        public final void removeActivity(PackageParser.Activity a, String type) {
7234            mActivities.remove(a.getComponentName());
7235            if (DEBUG_SHOW_INFO) {
7236                Log.v(TAG, "  " + type + " "
7237                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7238                                : a.info.name) + ":");
7239                Log.v(TAG, "    Class=" + a.info.name);
7240            }
7241            final int NI = a.intents.size();
7242            for (int j=0; j<NI; j++) {
7243                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7244                if (DEBUG_SHOW_INFO) {
7245                    Log.v(TAG, "    IntentFilter:");
7246                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7247                }
7248                removeFilter(intent);
7249            }
7250        }
7251
7252        @Override
7253        protected boolean allowFilterResult(
7254                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7255            ActivityInfo filterAi = filter.activity.info;
7256            for (int i=dest.size()-1; i>=0; i--) {
7257                ActivityInfo destAi = dest.get(i).activityInfo;
7258                if (destAi.name == filterAi.name
7259                        && destAi.packageName == filterAi.packageName) {
7260                    return false;
7261                }
7262            }
7263            return true;
7264        }
7265
7266        @Override
7267        protected ActivityIntentInfo[] newArray(int size) {
7268            return new ActivityIntentInfo[size];
7269        }
7270
7271        @Override
7272        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7273            if (!sUserManager.exists(userId)) return true;
7274            PackageParser.Package p = filter.activity.owner;
7275            if (p != null) {
7276                PackageSetting ps = (PackageSetting)p.mExtras;
7277                if (ps != null) {
7278                    // System apps are never considered stopped for purposes of
7279                    // filtering, because there may be no way for the user to
7280                    // actually re-launch them.
7281                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7282                            && ps.getStopped(userId);
7283                }
7284            }
7285            return false;
7286        }
7287
7288        @Override
7289        protected boolean isPackageForFilter(String packageName,
7290                PackageParser.ActivityIntentInfo info) {
7291            return packageName.equals(info.activity.owner.packageName);
7292        }
7293
7294        @Override
7295        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7296                int match, int userId) {
7297            if (!sUserManager.exists(userId)) return null;
7298            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7299                return null;
7300            }
7301            final PackageParser.Activity activity = info.activity;
7302            if (mSafeMode && (activity.info.applicationInfo.flags
7303                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7304                return null;
7305            }
7306            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7307            if (ps == null) {
7308                return null;
7309            }
7310            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7311                    ps.readUserState(userId), userId);
7312            if (ai == null) {
7313                return null;
7314            }
7315            final ResolveInfo res = new ResolveInfo();
7316            res.activityInfo = ai;
7317            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7318                res.filter = info;
7319            }
7320            res.priority = info.getPriority();
7321            res.preferredOrder = activity.owner.mPreferredOrder;
7322            //System.out.println("Result: " + res.activityInfo.className +
7323            //                   " = " + res.priority);
7324            res.match = match;
7325            res.isDefault = info.hasDefault;
7326            res.labelRes = info.labelRes;
7327            res.nonLocalizedLabel = info.nonLocalizedLabel;
7328            if (userNeedsBadging(userId)) {
7329                res.noResourceId = true;
7330            } else {
7331                res.icon = info.icon;
7332            }
7333            res.system = isSystemApp(res.activityInfo.applicationInfo);
7334            return res;
7335        }
7336
7337        @Override
7338        protected void sortResults(List<ResolveInfo> results) {
7339            Collections.sort(results, mResolvePrioritySorter);
7340        }
7341
7342        @Override
7343        protected void dumpFilter(PrintWriter out, String prefix,
7344                PackageParser.ActivityIntentInfo filter) {
7345            out.print(prefix); out.print(
7346                    Integer.toHexString(System.identityHashCode(filter.activity)));
7347                    out.print(' ');
7348                    filter.activity.printComponentShortName(out);
7349                    out.print(" filter ");
7350                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7351        }
7352
7353//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7354//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7355//            final List<ResolveInfo> retList = Lists.newArrayList();
7356//            while (i.hasNext()) {
7357//                final ResolveInfo resolveInfo = i.next();
7358//                if (isEnabledLP(resolveInfo.activityInfo)) {
7359//                    retList.add(resolveInfo);
7360//                }
7361//            }
7362//            return retList;
7363//        }
7364
7365        // Keys are String (activity class name), values are Activity.
7366        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7367                = new HashMap<ComponentName, PackageParser.Activity>();
7368        private int mFlags;
7369    }
7370
7371    private final class ServiceIntentResolver
7372            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7373        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7374                boolean defaultOnly, int userId) {
7375            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7376            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7377        }
7378
7379        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7380                int userId) {
7381            if (!sUserManager.exists(userId)) return null;
7382            mFlags = flags;
7383            return super.queryIntent(intent, resolvedType,
7384                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7385        }
7386
7387        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7388                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7389            if (!sUserManager.exists(userId)) return null;
7390            if (packageServices == null) {
7391                return null;
7392            }
7393            mFlags = flags;
7394            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7395            final int N = packageServices.size();
7396            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7397                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7398
7399            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7400            for (int i = 0; i < N; ++i) {
7401                intentFilters = packageServices.get(i).intents;
7402                if (intentFilters != null && intentFilters.size() > 0) {
7403                    PackageParser.ServiceIntentInfo[] array =
7404                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7405                    intentFilters.toArray(array);
7406                    listCut.add(array);
7407                }
7408            }
7409            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7410        }
7411
7412        public final void addService(PackageParser.Service s) {
7413            mServices.put(s.getComponentName(), s);
7414            if (DEBUG_SHOW_INFO) {
7415                Log.v(TAG, "  "
7416                        + (s.info.nonLocalizedLabel != null
7417                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7418                Log.v(TAG, "    Class=" + s.info.name);
7419            }
7420            final int NI = s.intents.size();
7421            int j;
7422            for (j=0; j<NI; j++) {
7423                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7424                if (DEBUG_SHOW_INFO) {
7425                    Log.v(TAG, "    IntentFilter:");
7426                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7427                }
7428                if (!intent.debugCheck()) {
7429                    Log.w(TAG, "==> For Service " + s.info.name);
7430                }
7431                addFilter(intent);
7432            }
7433        }
7434
7435        public final void removeService(PackageParser.Service s) {
7436            mServices.remove(s.getComponentName());
7437            if (DEBUG_SHOW_INFO) {
7438                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7439                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7440                Log.v(TAG, "    Class=" + s.info.name);
7441            }
7442            final int NI = s.intents.size();
7443            int j;
7444            for (j=0; j<NI; j++) {
7445                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7446                if (DEBUG_SHOW_INFO) {
7447                    Log.v(TAG, "    IntentFilter:");
7448                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7449                }
7450                removeFilter(intent);
7451            }
7452        }
7453
7454        @Override
7455        protected boolean allowFilterResult(
7456                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7457            ServiceInfo filterSi = filter.service.info;
7458            for (int i=dest.size()-1; i>=0; i--) {
7459                ServiceInfo destAi = dest.get(i).serviceInfo;
7460                if (destAi.name == filterSi.name
7461                        && destAi.packageName == filterSi.packageName) {
7462                    return false;
7463                }
7464            }
7465            return true;
7466        }
7467
7468        @Override
7469        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7470            return new PackageParser.ServiceIntentInfo[size];
7471        }
7472
7473        @Override
7474        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7475            if (!sUserManager.exists(userId)) return true;
7476            PackageParser.Package p = filter.service.owner;
7477            if (p != null) {
7478                PackageSetting ps = (PackageSetting)p.mExtras;
7479                if (ps != null) {
7480                    // System apps are never considered stopped for purposes of
7481                    // filtering, because there may be no way for the user to
7482                    // actually re-launch them.
7483                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7484                            && ps.getStopped(userId);
7485                }
7486            }
7487            return false;
7488        }
7489
7490        @Override
7491        protected boolean isPackageForFilter(String packageName,
7492                PackageParser.ServiceIntentInfo info) {
7493            return packageName.equals(info.service.owner.packageName);
7494        }
7495
7496        @Override
7497        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7498                int match, int userId) {
7499            if (!sUserManager.exists(userId)) return null;
7500            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7501            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7502                return null;
7503            }
7504            final PackageParser.Service service = info.service;
7505            if (mSafeMode && (service.info.applicationInfo.flags
7506                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7507                return null;
7508            }
7509            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7510            if (ps == null) {
7511                return null;
7512            }
7513            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7514                    ps.readUserState(userId), userId);
7515            if (si == null) {
7516                return null;
7517            }
7518            final ResolveInfo res = new ResolveInfo();
7519            res.serviceInfo = si;
7520            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7521                res.filter = filter;
7522            }
7523            res.priority = info.getPriority();
7524            res.preferredOrder = service.owner.mPreferredOrder;
7525            //System.out.println("Result: " + res.activityInfo.className +
7526            //                   " = " + res.priority);
7527            res.match = match;
7528            res.isDefault = info.hasDefault;
7529            res.labelRes = info.labelRes;
7530            res.nonLocalizedLabel = info.nonLocalizedLabel;
7531            res.icon = info.icon;
7532            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7533            return res;
7534        }
7535
7536        @Override
7537        protected void sortResults(List<ResolveInfo> results) {
7538            Collections.sort(results, mResolvePrioritySorter);
7539        }
7540
7541        @Override
7542        protected void dumpFilter(PrintWriter out, String prefix,
7543                PackageParser.ServiceIntentInfo filter) {
7544            out.print(prefix); out.print(
7545                    Integer.toHexString(System.identityHashCode(filter.service)));
7546                    out.print(' ');
7547                    filter.service.printComponentShortName(out);
7548                    out.print(" filter ");
7549                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7550        }
7551
7552//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7553//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7554//            final List<ResolveInfo> retList = Lists.newArrayList();
7555//            while (i.hasNext()) {
7556//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7557//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7558//                    retList.add(resolveInfo);
7559//                }
7560//            }
7561//            return retList;
7562//        }
7563
7564        // Keys are String (activity class name), values are Activity.
7565        private final HashMap<ComponentName, PackageParser.Service> mServices
7566                = new HashMap<ComponentName, PackageParser.Service>();
7567        private int mFlags;
7568    };
7569
7570    private final class ProviderIntentResolver
7571            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7572        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7573                boolean defaultOnly, int userId) {
7574            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7575            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7576        }
7577
7578        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7579                int userId) {
7580            if (!sUserManager.exists(userId))
7581                return null;
7582            mFlags = flags;
7583            return super.queryIntent(intent, resolvedType,
7584                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7585        }
7586
7587        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7588                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7589            if (!sUserManager.exists(userId))
7590                return null;
7591            if (packageProviders == null) {
7592                return null;
7593            }
7594            mFlags = flags;
7595            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7596            final int N = packageProviders.size();
7597            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7598                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7599
7600            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7601            for (int i = 0; i < N; ++i) {
7602                intentFilters = packageProviders.get(i).intents;
7603                if (intentFilters != null && intentFilters.size() > 0) {
7604                    PackageParser.ProviderIntentInfo[] array =
7605                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7606                    intentFilters.toArray(array);
7607                    listCut.add(array);
7608                }
7609            }
7610            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7611        }
7612
7613        public final void addProvider(PackageParser.Provider p) {
7614            if (mProviders.containsKey(p.getComponentName())) {
7615                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7616                return;
7617            }
7618
7619            mProviders.put(p.getComponentName(), p);
7620            if (DEBUG_SHOW_INFO) {
7621                Log.v(TAG, "  "
7622                        + (p.info.nonLocalizedLabel != null
7623                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7624                Log.v(TAG, "    Class=" + p.info.name);
7625            }
7626            final int NI = p.intents.size();
7627            int j;
7628            for (j = 0; j < NI; j++) {
7629                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7630                if (DEBUG_SHOW_INFO) {
7631                    Log.v(TAG, "    IntentFilter:");
7632                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7633                }
7634                if (!intent.debugCheck()) {
7635                    Log.w(TAG, "==> For Provider " + p.info.name);
7636                }
7637                addFilter(intent);
7638            }
7639        }
7640
7641        public final void removeProvider(PackageParser.Provider p) {
7642            mProviders.remove(p.getComponentName());
7643            if (DEBUG_SHOW_INFO) {
7644                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7645                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7646                Log.v(TAG, "    Class=" + p.info.name);
7647            }
7648            final int NI = p.intents.size();
7649            int j;
7650            for (j = 0; j < NI; j++) {
7651                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7652                if (DEBUG_SHOW_INFO) {
7653                    Log.v(TAG, "    IntentFilter:");
7654                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7655                }
7656                removeFilter(intent);
7657            }
7658        }
7659
7660        @Override
7661        protected boolean allowFilterResult(
7662                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7663            ProviderInfo filterPi = filter.provider.info;
7664            for (int i = dest.size() - 1; i >= 0; i--) {
7665                ProviderInfo destPi = dest.get(i).providerInfo;
7666                if (destPi.name == filterPi.name
7667                        && destPi.packageName == filterPi.packageName) {
7668                    return false;
7669                }
7670            }
7671            return true;
7672        }
7673
7674        @Override
7675        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7676            return new PackageParser.ProviderIntentInfo[size];
7677        }
7678
7679        @Override
7680        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7681            if (!sUserManager.exists(userId))
7682                return true;
7683            PackageParser.Package p = filter.provider.owner;
7684            if (p != null) {
7685                PackageSetting ps = (PackageSetting) p.mExtras;
7686                if (ps != null) {
7687                    // System apps are never considered stopped for purposes of
7688                    // filtering, because there may be no way for the user to
7689                    // actually re-launch them.
7690                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7691                            && ps.getStopped(userId);
7692                }
7693            }
7694            return false;
7695        }
7696
7697        @Override
7698        protected boolean isPackageForFilter(String packageName,
7699                PackageParser.ProviderIntentInfo info) {
7700            return packageName.equals(info.provider.owner.packageName);
7701        }
7702
7703        @Override
7704        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7705                int match, int userId) {
7706            if (!sUserManager.exists(userId))
7707                return null;
7708            final PackageParser.ProviderIntentInfo info = filter;
7709            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7710                return null;
7711            }
7712            final PackageParser.Provider provider = info.provider;
7713            if (mSafeMode && (provider.info.applicationInfo.flags
7714                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7715                return null;
7716            }
7717            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7718            if (ps == null) {
7719                return null;
7720            }
7721            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7722                    ps.readUserState(userId), userId);
7723            if (pi == null) {
7724                return null;
7725            }
7726            final ResolveInfo res = new ResolveInfo();
7727            res.providerInfo = pi;
7728            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7729                res.filter = filter;
7730            }
7731            res.priority = info.getPriority();
7732            res.preferredOrder = provider.owner.mPreferredOrder;
7733            res.match = match;
7734            res.isDefault = info.hasDefault;
7735            res.labelRes = info.labelRes;
7736            res.nonLocalizedLabel = info.nonLocalizedLabel;
7737            res.icon = info.icon;
7738            res.system = isSystemApp(res.providerInfo.applicationInfo);
7739            return res;
7740        }
7741
7742        @Override
7743        protected void sortResults(List<ResolveInfo> results) {
7744            Collections.sort(results, mResolvePrioritySorter);
7745        }
7746
7747        @Override
7748        protected void dumpFilter(PrintWriter out, String prefix,
7749                PackageParser.ProviderIntentInfo filter) {
7750            out.print(prefix);
7751            out.print(
7752                    Integer.toHexString(System.identityHashCode(filter.provider)));
7753            out.print(' ');
7754            filter.provider.printComponentShortName(out);
7755            out.print(" filter ");
7756            out.println(Integer.toHexString(System.identityHashCode(filter)));
7757        }
7758
7759        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7760                = new HashMap<ComponentName, PackageParser.Provider>();
7761        private int mFlags;
7762    };
7763
7764    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7765            new Comparator<ResolveInfo>() {
7766        public int compare(ResolveInfo r1, ResolveInfo r2) {
7767            int v1 = r1.priority;
7768            int v2 = r2.priority;
7769            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7770            if (v1 != v2) {
7771                return (v1 > v2) ? -1 : 1;
7772            }
7773            v1 = r1.preferredOrder;
7774            v2 = r2.preferredOrder;
7775            if (v1 != v2) {
7776                return (v1 > v2) ? -1 : 1;
7777            }
7778            if (r1.isDefault != r2.isDefault) {
7779                return r1.isDefault ? -1 : 1;
7780            }
7781            v1 = r1.match;
7782            v2 = r2.match;
7783            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7784            if (v1 != v2) {
7785                return (v1 > v2) ? -1 : 1;
7786            }
7787            if (r1.system != r2.system) {
7788                return r1.system ? -1 : 1;
7789            }
7790            return 0;
7791        }
7792    };
7793
7794    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7795            new Comparator<ProviderInfo>() {
7796        public int compare(ProviderInfo p1, ProviderInfo p2) {
7797            final int v1 = p1.initOrder;
7798            final int v2 = p2.initOrder;
7799            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7800        }
7801    };
7802
7803    static final void sendPackageBroadcast(String action, String pkg,
7804            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7805            int[] userIds) {
7806        IActivityManager am = ActivityManagerNative.getDefault();
7807        if (am != null) {
7808            try {
7809                if (userIds == null) {
7810                    userIds = am.getRunningUserIds();
7811                }
7812                for (int id : userIds) {
7813                    final Intent intent = new Intent(action,
7814                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7815                    if (extras != null) {
7816                        intent.putExtras(extras);
7817                    }
7818                    if (targetPkg != null) {
7819                        intent.setPackage(targetPkg);
7820                    }
7821                    // Modify the UID when posting to other users
7822                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7823                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7824                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7825                        intent.putExtra(Intent.EXTRA_UID, uid);
7826                    }
7827                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7828                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7829                    if (DEBUG_BROADCASTS) {
7830                        RuntimeException here = new RuntimeException("here");
7831                        here.fillInStackTrace();
7832                        Slog.d(TAG, "Sending to user " + id + ": "
7833                                + intent.toShortString(false, true, false, false)
7834                                + " " + intent.getExtras(), here);
7835                    }
7836                    am.broadcastIntent(null, intent, null, finishedReceiver,
7837                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7838                            finishedReceiver != null, false, id);
7839                }
7840            } catch (RemoteException ex) {
7841            }
7842        }
7843    }
7844
7845    /**
7846     * Check if the external storage media is available. This is true if there
7847     * is a mounted external storage medium or if the external storage is
7848     * emulated.
7849     */
7850    private boolean isExternalMediaAvailable() {
7851        return mMediaMounted || Environment.isExternalStorageEmulated();
7852    }
7853
7854    @Override
7855    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7856        // writer
7857        synchronized (mPackages) {
7858            if (!isExternalMediaAvailable()) {
7859                // If the external storage is no longer mounted at this point,
7860                // the caller may not have been able to delete all of this
7861                // packages files and can not delete any more.  Bail.
7862                return null;
7863            }
7864            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7865            if (lastPackage != null) {
7866                pkgs.remove(lastPackage);
7867            }
7868            if (pkgs.size() > 0) {
7869                return pkgs.get(0);
7870            }
7871        }
7872        return null;
7873    }
7874
7875    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7876        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7877                userId, andCode ? 1 : 0, packageName);
7878        if (mSystemReady) {
7879            msg.sendToTarget();
7880        } else {
7881            if (mPostSystemReadyMessages == null) {
7882                mPostSystemReadyMessages = new ArrayList<>();
7883            }
7884            mPostSystemReadyMessages.add(msg);
7885        }
7886    }
7887
7888    void startCleaningPackages() {
7889        // reader
7890        synchronized (mPackages) {
7891            if (!isExternalMediaAvailable()) {
7892                return;
7893            }
7894            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7895                return;
7896            }
7897        }
7898        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7899        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7900        IActivityManager am = ActivityManagerNative.getDefault();
7901        if (am != null) {
7902            try {
7903                am.startService(null, intent, null, UserHandle.USER_OWNER);
7904            } catch (RemoteException e) {
7905            }
7906        }
7907    }
7908
7909    @Override
7910    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7911            int installFlags, String installerPackageName, VerificationParams verificationParams,
7912            String packageAbiOverride) {
7913        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7914                packageAbiOverride, UserHandle.getCallingUserId());
7915    }
7916
7917    @Override
7918    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7919            int installFlags, String installerPackageName, VerificationParams verificationParams,
7920            String packageAbiOverride, int userId) {
7921        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7922
7923        final int callingUid = Binder.getCallingUid();
7924        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7925
7926        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7927            try {
7928                if (observer != null) {
7929                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7930                }
7931            } catch (RemoteException re) {
7932            }
7933            return;
7934        }
7935
7936        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7937            installFlags |= PackageManager.INSTALL_FROM_ADB;
7938
7939        } else {
7940            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7941            // about installerPackageName.
7942
7943            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7944            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7945        }
7946
7947        UserHandle user;
7948        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7949            user = UserHandle.ALL;
7950        } else {
7951            user = new UserHandle(userId);
7952        }
7953
7954        verificationParams.setInstallerUid(callingUid);
7955
7956        final File originFile = new File(originPath);
7957        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7958
7959        final Message msg = mHandler.obtainMessage(INIT_COPY);
7960        msg.obj = new InstallParams(origin, observer, installFlags,
7961                installerPackageName, verificationParams, user, packageAbiOverride);
7962        mHandler.sendMessage(msg);
7963    }
7964
7965    void installStage(String packageName, File stagedDir, String stagedCid,
7966            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7967            String installerPackageName, int installerUid, UserHandle user) {
7968        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7969                params.referrerUri, installerUid, null);
7970
7971        final OriginInfo origin;
7972        if (stagedDir != null) {
7973            origin = OriginInfo.fromStagedFile(stagedDir);
7974        } else {
7975            origin = OriginInfo.fromStagedContainer(stagedCid);
7976        }
7977
7978        final Message msg = mHandler.obtainMessage(INIT_COPY);
7979        msg.obj = new InstallParams(origin, observer, params.installFlags,
7980                installerPackageName, verifParams, user, params.abiOverride);
7981        mHandler.sendMessage(msg);
7982    }
7983
7984    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7985        Bundle extras = new Bundle(1);
7986        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7987
7988        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7989                packageName, extras, null, null, new int[] {userId});
7990        try {
7991            IActivityManager am = ActivityManagerNative.getDefault();
7992            final boolean isSystem =
7993                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7994            if (isSystem && am.isUserRunning(userId, false)) {
7995                // The just-installed/enabled app is bundled on the system, so presumed
7996                // to be able to run automatically without needing an explicit launch.
7997                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7998                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7999                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8000                        .setPackage(packageName);
8001                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8002                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8003            }
8004        } catch (RemoteException e) {
8005            // shouldn't happen
8006            Slog.w(TAG, "Unable to bootstrap installed package", e);
8007        }
8008    }
8009
8010    @Override
8011    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8012            int userId) {
8013        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8014        PackageSetting pkgSetting;
8015        final int uid = Binder.getCallingUid();
8016        enforceCrossUserPermission(uid, userId, true, true,
8017                "setApplicationHiddenSetting for user " + userId);
8018
8019        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8020            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8021            return false;
8022        }
8023
8024        long callingId = Binder.clearCallingIdentity();
8025        try {
8026            boolean sendAdded = false;
8027            boolean sendRemoved = false;
8028            // writer
8029            synchronized (mPackages) {
8030                pkgSetting = mSettings.mPackages.get(packageName);
8031                if (pkgSetting == null) {
8032                    return false;
8033                }
8034                if (pkgSetting.getHidden(userId) != hidden) {
8035                    pkgSetting.setHidden(hidden, userId);
8036                    mSettings.writePackageRestrictionsLPr(userId);
8037                    if (hidden) {
8038                        sendRemoved = true;
8039                    } else {
8040                        sendAdded = true;
8041                    }
8042                }
8043            }
8044            if (sendAdded) {
8045                sendPackageAddedForUser(packageName, pkgSetting, userId);
8046                return true;
8047            }
8048            if (sendRemoved) {
8049                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8050                        "hiding pkg");
8051                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8052            }
8053        } finally {
8054            Binder.restoreCallingIdentity(callingId);
8055        }
8056        return false;
8057    }
8058
8059    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8060            int userId) {
8061        final PackageRemovedInfo info = new PackageRemovedInfo();
8062        info.removedPackage = packageName;
8063        info.removedUsers = new int[] {userId};
8064        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8065        info.sendBroadcast(false, false, false);
8066    }
8067
8068    /**
8069     * Returns true if application is not found or there was an error. Otherwise it returns
8070     * the hidden state of the package for the given user.
8071     */
8072    @Override
8073    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8074        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8075        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8076                false, "getApplicationHidden for user " + userId);
8077        PackageSetting pkgSetting;
8078        long callingId = Binder.clearCallingIdentity();
8079        try {
8080            // writer
8081            synchronized (mPackages) {
8082                pkgSetting = mSettings.mPackages.get(packageName);
8083                if (pkgSetting == null) {
8084                    return true;
8085                }
8086                return pkgSetting.getHidden(userId);
8087            }
8088        } finally {
8089            Binder.restoreCallingIdentity(callingId);
8090        }
8091    }
8092
8093    /**
8094     * @hide
8095     */
8096    @Override
8097    public int installExistingPackageAsUser(String packageName, int userId) {
8098        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8099                null);
8100        PackageSetting pkgSetting;
8101        final int uid = Binder.getCallingUid();
8102        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8103                + userId);
8104        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8105            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8106        }
8107
8108        long callingId = Binder.clearCallingIdentity();
8109        try {
8110            boolean sendAdded = false;
8111            Bundle extras = new Bundle(1);
8112
8113            // writer
8114            synchronized (mPackages) {
8115                pkgSetting = mSettings.mPackages.get(packageName);
8116                if (pkgSetting == null) {
8117                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8118                }
8119                if (!pkgSetting.getInstalled(userId)) {
8120                    pkgSetting.setInstalled(true, userId);
8121                    pkgSetting.setHidden(false, userId);
8122                    mSettings.writePackageRestrictionsLPr(userId);
8123                    sendAdded = true;
8124                }
8125            }
8126
8127            if (sendAdded) {
8128                sendPackageAddedForUser(packageName, pkgSetting, userId);
8129            }
8130        } finally {
8131            Binder.restoreCallingIdentity(callingId);
8132        }
8133
8134        return PackageManager.INSTALL_SUCCEEDED;
8135    }
8136
8137    boolean isUserRestricted(int userId, String restrictionKey) {
8138        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8139        if (restrictions.getBoolean(restrictionKey, false)) {
8140            Log.w(TAG, "User is restricted: " + restrictionKey);
8141            return true;
8142        }
8143        return false;
8144    }
8145
8146    @Override
8147    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8148        mContext.enforceCallingOrSelfPermission(
8149                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8150                "Only package verification agents can verify applications");
8151
8152        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8153        final PackageVerificationResponse response = new PackageVerificationResponse(
8154                verificationCode, Binder.getCallingUid());
8155        msg.arg1 = id;
8156        msg.obj = response;
8157        mHandler.sendMessage(msg);
8158    }
8159
8160    @Override
8161    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8162            long millisecondsToDelay) {
8163        mContext.enforceCallingOrSelfPermission(
8164                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8165                "Only package verification agents can extend verification timeouts");
8166
8167        final PackageVerificationState state = mPendingVerification.get(id);
8168        final PackageVerificationResponse response = new PackageVerificationResponse(
8169                verificationCodeAtTimeout, Binder.getCallingUid());
8170
8171        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8172            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8173        }
8174        if (millisecondsToDelay < 0) {
8175            millisecondsToDelay = 0;
8176        }
8177        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8178                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8179            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8180        }
8181
8182        if ((state != null) && !state.timeoutExtended()) {
8183            state.extendTimeout();
8184
8185            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8186            msg.arg1 = id;
8187            msg.obj = response;
8188            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8189        }
8190    }
8191
8192    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8193            int verificationCode, UserHandle user) {
8194        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8195        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8196        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8197        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8198        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8199
8200        mContext.sendBroadcastAsUser(intent, user,
8201                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8202    }
8203
8204    private ComponentName matchComponentForVerifier(String packageName,
8205            List<ResolveInfo> receivers) {
8206        ActivityInfo targetReceiver = null;
8207
8208        final int NR = receivers.size();
8209        for (int i = 0; i < NR; i++) {
8210            final ResolveInfo info = receivers.get(i);
8211            if (info.activityInfo == null) {
8212                continue;
8213            }
8214
8215            if (packageName.equals(info.activityInfo.packageName)) {
8216                targetReceiver = info.activityInfo;
8217                break;
8218            }
8219        }
8220
8221        if (targetReceiver == null) {
8222            return null;
8223        }
8224
8225        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8226    }
8227
8228    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8229            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8230        if (pkgInfo.verifiers.length == 0) {
8231            return null;
8232        }
8233
8234        final int N = pkgInfo.verifiers.length;
8235        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8236        for (int i = 0; i < N; i++) {
8237            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8238
8239            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8240                    receivers);
8241            if (comp == null) {
8242                continue;
8243            }
8244
8245            final int verifierUid = getUidForVerifier(verifierInfo);
8246            if (verifierUid == -1) {
8247                continue;
8248            }
8249
8250            if (DEBUG_VERIFY) {
8251                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8252                        + " with the correct signature");
8253            }
8254            sufficientVerifiers.add(comp);
8255            verificationState.addSufficientVerifier(verifierUid);
8256        }
8257
8258        return sufficientVerifiers;
8259    }
8260
8261    private int getUidForVerifier(VerifierInfo verifierInfo) {
8262        synchronized (mPackages) {
8263            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8264            if (pkg == null) {
8265                return -1;
8266            } else if (pkg.mSignatures.length != 1) {
8267                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8268                        + " has more than one signature; ignoring");
8269                return -1;
8270            }
8271
8272            /*
8273             * If the public key of the package's signature does not match
8274             * our expected public key, then this is a different package and
8275             * we should skip.
8276             */
8277
8278            final byte[] expectedPublicKey;
8279            try {
8280                final Signature verifierSig = pkg.mSignatures[0];
8281                final PublicKey publicKey = verifierSig.getPublicKey();
8282                expectedPublicKey = publicKey.getEncoded();
8283            } catch (CertificateException e) {
8284                return -1;
8285            }
8286
8287            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8288
8289            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8290                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8291                        + " does not have the expected public key; ignoring");
8292                return -1;
8293            }
8294
8295            return pkg.applicationInfo.uid;
8296        }
8297    }
8298
8299    @Override
8300    public void finishPackageInstall(int token) {
8301        enforceSystemOrRoot("Only the system is allowed to finish installs");
8302
8303        if (DEBUG_INSTALL) {
8304            Slog.v(TAG, "BM finishing package install for " + token);
8305        }
8306
8307        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8308        mHandler.sendMessage(msg);
8309    }
8310
8311    /**
8312     * Get the verification agent timeout.
8313     *
8314     * @return verification timeout in milliseconds
8315     */
8316    private long getVerificationTimeout() {
8317        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8318                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8319                DEFAULT_VERIFICATION_TIMEOUT);
8320    }
8321
8322    /**
8323     * Get the default verification agent response code.
8324     *
8325     * @return default verification response code
8326     */
8327    private int getDefaultVerificationResponse() {
8328        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8329                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8330                DEFAULT_VERIFICATION_RESPONSE);
8331    }
8332
8333    /**
8334     * Check whether or not package verification has been enabled.
8335     *
8336     * @return true if verification should be performed
8337     */
8338    private boolean isVerificationEnabled(int userId, int installFlags) {
8339        if (!DEFAULT_VERIFY_ENABLE) {
8340            return false;
8341        }
8342
8343        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8344
8345        // Check if installing from ADB
8346        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8347            // Do not run verification in a test harness environment
8348            if (ActivityManager.isRunningInTestHarness()) {
8349                return false;
8350            }
8351            if (ensureVerifyAppsEnabled) {
8352                return true;
8353            }
8354            // Check if the developer does not want package verification for ADB installs
8355            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8356                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8357                return false;
8358            }
8359        }
8360
8361        if (ensureVerifyAppsEnabled) {
8362            return true;
8363        }
8364
8365        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8366                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8367    }
8368
8369    /**
8370     * Get the "allow unknown sources" setting.
8371     *
8372     * @return the current "allow unknown sources" setting
8373     */
8374    private int getUnknownSourcesSettings() {
8375        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8376                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8377                -1);
8378    }
8379
8380    @Override
8381    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8382        final int uid = Binder.getCallingUid();
8383        // writer
8384        synchronized (mPackages) {
8385            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8386            if (targetPackageSetting == null) {
8387                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8388            }
8389
8390            PackageSetting installerPackageSetting;
8391            if (installerPackageName != null) {
8392                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8393                if (installerPackageSetting == null) {
8394                    throw new IllegalArgumentException("Unknown installer package: "
8395                            + installerPackageName);
8396                }
8397            } else {
8398                installerPackageSetting = null;
8399            }
8400
8401            Signature[] callerSignature;
8402            Object obj = mSettings.getUserIdLPr(uid);
8403            if (obj != null) {
8404                if (obj instanceof SharedUserSetting) {
8405                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8406                } else if (obj instanceof PackageSetting) {
8407                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8408                } else {
8409                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8410                }
8411            } else {
8412                throw new SecurityException("Unknown calling uid " + uid);
8413            }
8414
8415            // Verify: can't set installerPackageName to a package that is
8416            // not signed with the same cert as the caller.
8417            if (installerPackageSetting != null) {
8418                if (compareSignatures(callerSignature,
8419                        installerPackageSetting.signatures.mSignatures)
8420                        != PackageManager.SIGNATURE_MATCH) {
8421                    throw new SecurityException(
8422                            "Caller does not have same cert as new installer package "
8423                            + installerPackageName);
8424                }
8425            }
8426
8427            // Verify: if target already has an installer package, it must
8428            // be signed with the same cert as the caller.
8429            if (targetPackageSetting.installerPackageName != null) {
8430                PackageSetting setting = mSettings.mPackages.get(
8431                        targetPackageSetting.installerPackageName);
8432                // If the currently set package isn't valid, then it's always
8433                // okay to change it.
8434                if (setting != null) {
8435                    if (compareSignatures(callerSignature,
8436                            setting.signatures.mSignatures)
8437                            != PackageManager.SIGNATURE_MATCH) {
8438                        throw new SecurityException(
8439                                "Caller does not have same cert as old installer package "
8440                                + targetPackageSetting.installerPackageName);
8441                    }
8442                }
8443            }
8444
8445            // Okay!
8446            targetPackageSetting.installerPackageName = installerPackageName;
8447            scheduleWriteSettingsLocked();
8448        }
8449    }
8450
8451    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8452        // Queue up an async operation since the package installation may take a little while.
8453        mHandler.post(new Runnable() {
8454            public void run() {
8455                mHandler.removeCallbacks(this);
8456                 // Result object to be returned
8457                PackageInstalledInfo res = new PackageInstalledInfo();
8458                res.returnCode = currentStatus;
8459                res.uid = -1;
8460                res.pkg = null;
8461                res.removedInfo = new PackageRemovedInfo();
8462                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8463                    args.doPreInstall(res.returnCode);
8464                    synchronized (mInstallLock) {
8465                        installPackageLI(args, res);
8466                    }
8467                    args.doPostInstall(res.returnCode, res.uid);
8468                }
8469
8470                // A restore should be performed at this point if (a) the install
8471                // succeeded, (b) the operation is not an update, and (c) the new
8472                // package has not opted out of backup participation.
8473                final boolean update = res.removedInfo.removedPackage != null;
8474                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8475                boolean doRestore = !update
8476                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8477
8478                // Set up the post-install work request bookkeeping.  This will be used
8479                // and cleaned up by the post-install event handling regardless of whether
8480                // there's a restore pass performed.  Token values are >= 1.
8481                int token;
8482                if (mNextInstallToken < 0) mNextInstallToken = 1;
8483                token = mNextInstallToken++;
8484
8485                PostInstallData data = new PostInstallData(args, res);
8486                mRunningInstalls.put(token, data);
8487                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8488
8489                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8490                    // Pass responsibility to the Backup Manager.  It will perform a
8491                    // restore if appropriate, then pass responsibility back to the
8492                    // Package Manager to run the post-install observer callbacks
8493                    // and broadcasts.
8494                    IBackupManager bm = IBackupManager.Stub.asInterface(
8495                            ServiceManager.getService(Context.BACKUP_SERVICE));
8496                    if (bm != null) {
8497                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8498                                + " to BM for possible restore");
8499                        try {
8500                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8501                        } catch (RemoteException e) {
8502                            // can't happen; the backup manager is local
8503                        } catch (Exception e) {
8504                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8505                            doRestore = false;
8506                        }
8507                    } else {
8508                        Slog.e(TAG, "Backup Manager not found!");
8509                        doRestore = false;
8510                    }
8511                }
8512
8513                if (!doRestore) {
8514                    // No restore possible, or the Backup Manager was mysteriously not
8515                    // available -- just fire the post-install work request directly.
8516                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8517                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8518                    mHandler.sendMessage(msg);
8519                }
8520            }
8521        });
8522    }
8523
8524    private abstract class HandlerParams {
8525        private static final int MAX_RETRIES = 4;
8526
8527        /**
8528         * Number of times startCopy() has been attempted and had a non-fatal
8529         * error.
8530         */
8531        private int mRetries = 0;
8532
8533        /** User handle for the user requesting the information or installation. */
8534        private final UserHandle mUser;
8535
8536        HandlerParams(UserHandle user) {
8537            mUser = user;
8538        }
8539
8540        UserHandle getUser() {
8541            return mUser;
8542        }
8543
8544        final boolean startCopy() {
8545            boolean res;
8546            try {
8547                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8548
8549                if (++mRetries > MAX_RETRIES) {
8550                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8551                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8552                    handleServiceError();
8553                    return false;
8554                } else {
8555                    handleStartCopy();
8556                    res = true;
8557                }
8558            } catch (RemoteException e) {
8559                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8560                mHandler.sendEmptyMessage(MCS_RECONNECT);
8561                res = false;
8562            }
8563            handleReturnCode();
8564            return res;
8565        }
8566
8567        final void serviceError() {
8568            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8569            handleServiceError();
8570            handleReturnCode();
8571        }
8572
8573        abstract void handleStartCopy() throws RemoteException;
8574        abstract void handleServiceError();
8575        abstract void handleReturnCode();
8576    }
8577
8578    class MeasureParams extends HandlerParams {
8579        private final PackageStats mStats;
8580        private boolean mSuccess;
8581
8582        private final IPackageStatsObserver mObserver;
8583
8584        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8585            super(new UserHandle(stats.userHandle));
8586            mObserver = observer;
8587            mStats = stats;
8588        }
8589
8590        @Override
8591        public String toString() {
8592            return "MeasureParams{"
8593                + Integer.toHexString(System.identityHashCode(this))
8594                + " " + mStats.packageName + "}";
8595        }
8596
8597        @Override
8598        void handleStartCopy() throws RemoteException {
8599            synchronized (mInstallLock) {
8600                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8601            }
8602
8603            if (mSuccess) {
8604                final boolean mounted;
8605                if (Environment.isExternalStorageEmulated()) {
8606                    mounted = true;
8607                } else {
8608                    final String status = Environment.getExternalStorageState();
8609                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8610                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8611                }
8612
8613                if (mounted) {
8614                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8615
8616                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8617                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8618
8619                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8620                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8621
8622                    // Always subtract cache size, since it's a subdirectory
8623                    mStats.externalDataSize -= mStats.externalCacheSize;
8624
8625                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8626                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8627
8628                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8629                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8630                }
8631            }
8632        }
8633
8634        @Override
8635        void handleReturnCode() {
8636            if (mObserver != null) {
8637                try {
8638                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8639                } catch (RemoteException e) {
8640                    Slog.i(TAG, "Observer no longer exists.");
8641                }
8642            }
8643        }
8644
8645        @Override
8646        void handleServiceError() {
8647            Slog.e(TAG, "Could not measure application " + mStats.packageName
8648                            + " external storage");
8649        }
8650    }
8651
8652    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8653            throws RemoteException {
8654        long result = 0;
8655        for (File path : paths) {
8656            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8657        }
8658        return result;
8659    }
8660
8661    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8662        for (File path : paths) {
8663            try {
8664                mcs.clearDirectory(path.getAbsolutePath());
8665            } catch (RemoteException e) {
8666            }
8667        }
8668    }
8669
8670    static class OriginInfo {
8671        /**
8672         * Location where install is coming from, before it has been
8673         * copied/renamed into place. This could be a single monolithic APK
8674         * file, or a cluster directory. This location may be untrusted.
8675         */
8676        final File file;
8677        final String cid;
8678
8679        /**
8680         * Flag indicating that {@link #file} or {@link #cid} has already been
8681         * staged, meaning downstream users don't need to defensively copy the
8682         * contents.
8683         */
8684        final boolean staged;
8685
8686        /**
8687         * Flag indicating that {@link #file} or {@link #cid} is an already
8688         * installed app that is being moved.
8689         */
8690        final boolean existing;
8691
8692        final String resolvedPath;
8693        final File resolvedFile;
8694
8695        static OriginInfo fromNothing() {
8696            return new OriginInfo(null, null, false, false);
8697        }
8698
8699        static OriginInfo fromUntrustedFile(File file) {
8700            return new OriginInfo(file, null, false, false);
8701        }
8702
8703        static OriginInfo fromExistingFile(File file) {
8704            return new OriginInfo(file, null, false, true);
8705        }
8706
8707        static OriginInfo fromStagedFile(File file) {
8708            return new OriginInfo(file, null, true, false);
8709        }
8710
8711        static OriginInfo fromStagedContainer(String cid) {
8712            return new OriginInfo(null, cid, true, false);
8713        }
8714
8715        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8716            this.file = file;
8717            this.cid = cid;
8718            this.staged = staged;
8719            this.existing = existing;
8720
8721            if (cid != null) {
8722                resolvedPath = PackageHelper.getSdDir(cid);
8723                resolvedFile = new File(resolvedPath);
8724            } else if (file != null) {
8725                resolvedPath = file.getAbsolutePath();
8726                resolvedFile = file;
8727            } else {
8728                resolvedPath = null;
8729                resolvedFile = null;
8730            }
8731        }
8732    }
8733
8734    class InstallParams extends HandlerParams {
8735        final OriginInfo origin;
8736        final IPackageInstallObserver2 observer;
8737        int installFlags;
8738        final String installerPackageName;
8739        final VerificationParams verificationParams;
8740        private InstallArgs mArgs;
8741        private int mRet;
8742        final String packageAbiOverride;
8743
8744        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8745                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8746                String packageAbiOverride) {
8747            super(user);
8748            this.origin = origin;
8749            this.observer = observer;
8750            this.installFlags = installFlags;
8751            this.installerPackageName = installerPackageName;
8752            this.verificationParams = verificationParams;
8753            this.packageAbiOverride = packageAbiOverride;
8754        }
8755
8756        @Override
8757        public String toString() {
8758            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8759                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8760        }
8761
8762        public ManifestDigest getManifestDigest() {
8763            if (verificationParams == null) {
8764                return null;
8765            }
8766            return verificationParams.getManifestDigest();
8767        }
8768
8769        private int installLocationPolicy(PackageInfoLite pkgLite) {
8770            String packageName = pkgLite.packageName;
8771            int installLocation = pkgLite.installLocation;
8772            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8773            // reader
8774            synchronized (mPackages) {
8775                PackageParser.Package pkg = mPackages.get(packageName);
8776                if (pkg != null) {
8777                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8778                        // Check for downgrading.
8779                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8780                            if (pkgLite.versionCode < pkg.mVersionCode) {
8781                                Slog.w(TAG, "Can't install update of " + packageName
8782                                        + " update version " + pkgLite.versionCode
8783                                        + " is older than installed version "
8784                                        + pkg.mVersionCode);
8785                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8786                            }
8787                        }
8788                        // Check for updated system application.
8789                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8790                            if (onSd) {
8791                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8792                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8793                            }
8794                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8795                        } else {
8796                            if (onSd) {
8797                                // Install flag overrides everything.
8798                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8799                            }
8800                            // If current upgrade specifies particular preference
8801                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8802                                // Application explicitly specified internal.
8803                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8804                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8805                                // App explictly prefers external. Let policy decide
8806                            } else {
8807                                // Prefer previous location
8808                                if (isExternal(pkg)) {
8809                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8810                                }
8811                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8812                            }
8813                        }
8814                    } else {
8815                        // Invalid install. Return error code
8816                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8817                    }
8818                }
8819            }
8820            // All the special cases have been taken care of.
8821            // Return result based on recommended install location.
8822            if (onSd) {
8823                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8824            }
8825            return pkgLite.recommendedInstallLocation;
8826        }
8827
8828        /*
8829         * Invoke remote method to get package information and install
8830         * location values. Override install location based on default
8831         * policy if needed and then create install arguments based
8832         * on the install location.
8833         */
8834        public void handleStartCopy() throws RemoteException {
8835            int ret = PackageManager.INSTALL_SUCCEEDED;
8836
8837            // If we're already staged, we've firmly committed to an install location
8838            if (origin.staged) {
8839                if (origin.file != null) {
8840                    installFlags |= PackageManager.INSTALL_INTERNAL;
8841                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8842                } else if (origin.cid != null) {
8843                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8844                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8845                } else {
8846                    throw new IllegalStateException("Invalid stage location");
8847                }
8848            }
8849
8850            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8851            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8852
8853            PackageInfoLite pkgLite = null;
8854
8855            if (onInt && onSd) {
8856                // Check if both bits are set.
8857                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8858                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8859            } else {
8860                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8861                        packageAbiOverride);
8862
8863                /*
8864                 * If we have too little free space, try to free cache
8865                 * before giving up.
8866                 */
8867                if (!origin.staged && pkgLite.recommendedInstallLocation
8868                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8869                    // TODO: focus freeing disk space on the target device
8870                    final StorageManager storage = StorageManager.from(mContext);
8871                    final long lowThreshold = storage.getStorageLowBytes(
8872                            Environment.getDataDirectory());
8873
8874                    final long sizeBytes = mContainerService.calculateInstalledSize(
8875                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8876
8877                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8878                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8879                                installFlags, packageAbiOverride);
8880                    }
8881
8882                    /*
8883                     * The cache free must have deleted the file we
8884                     * downloaded to install.
8885                     *
8886                     * TODO: fix the "freeCache" call to not delete
8887                     *       the file we care about.
8888                     */
8889                    if (pkgLite.recommendedInstallLocation
8890                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8891                        pkgLite.recommendedInstallLocation
8892                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8893                    }
8894                }
8895            }
8896
8897            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8898                int loc = pkgLite.recommendedInstallLocation;
8899                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8900                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8901                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8902                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8903                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8904                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8905                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8906                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8907                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8908                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8909                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8910                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8911                } else {
8912                    // Override with defaults if needed.
8913                    loc = installLocationPolicy(pkgLite);
8914                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8915                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8916                    } else if (!onSd && !onInt) {
8917                        // Override install location with flags
8918                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8919                            // Set the flag to install on external media.
8920                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8921                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8922                        } else {
8923                            // Make sure the flag for installing on external
8924                            // media is unset
8925                            installFlags |= PackageManager.INSTALL_INTERNAL;
8926                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8927                        }
8928                    }
8929                }
8930            }
8931
8932            final InstallArgs args = createInstallArgs(this);
8933            mArgs = args;
8934
8935            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8936                 /*
8937                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8938                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8939                 */
8940                int userIdentifier = getUser().getIdentifier();
8941                if (userIdentifier == UserHandle.USER_ALL
8942                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8943                    userIdentifier = UserHandle.USER_OWNER;
8944                }
8945
8946                /*
8947                 * Determine if we have any installed package verifiers. If we
8948                 * do, then we'll defer to them to verify the packages.
8949                 */
8950                final int requiredUid = mRequiredVerifierPackage == null ? -1
8951                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8952                if (!origin.existing && requiredUid != -1
8953                        && isVerificationEnabled(userIdentifier, installFlags)) {
8954                    final Intent verification = new Intent(
8955                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8956                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8957                            PACKAGE_MIME_TYPE);
8958                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8959
8960                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8961                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8962                            0 /* TODO: Which userId? */);
8963
8964                    if (DEBUG_VERIFY) {
8965                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8966                                + verification.toString() + " with " + pkgLite.verifiers.length
8967                                + " optional verifiers");
8968                    }
8969
8970                    final int verificationId = mPendingVerificationToken++;
8971
8972                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8973
8974                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8975                            installerPackageName);
8976
8977                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8978                            installFlags);
8979
8980                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8981                            pkgLite.packageName);
8982
8983                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8984                            pkgLite.versionCode);
8985
8986                    if (verificationParams != null) {
8987                        if (verificationParams.getVerificationURI() != null) {
8988                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8989                                 verificationParams.getVerificationURI());
8990                        }
8991                        if (verificationParams.getOriginatingURI() != null) {
8992                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8993                                  verificationParams.getOriginatingURI());
8994                        }
8995                        if (verificationParams.getReferrer() != null) {
8996                            verification.putExtra(Intent.EXTRA_REFERRER,
8997                                  verificationParams.getReferrer());
8998                        }
8999                        if (verificationParams.getOriginatingUid() >= 0) {
9000                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9001                                  verificationParams.getOriginatingUid());
9002                        }
9003                        if (verificationParams.getInstallerUid() >= 0) {
9004                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9005                                  verificationParams.getInstallerUid());
9006                        }
9007                    }
9008
9009                    final PackageVerificationState verificationState = new PackageVerificationState(
9010                            requiredUid, args);
9011
9012                    mPendingVerification.append(verificationId, verificationState);
9013
9014                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9015                            receivers, verificationState);
9016
9017                    /*
9018                     * If any sufficient verifiers were listed in the package
9019                     * manifest, attempt to ask them.
9020                     */
9021                    if (sufficientVerifiers != null) {
9022                        final int N = sufficientVerifiers.size();
9023                        if (N == 0) {
9024                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9025                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9026                        } else {
9027                            for (int i = 0; i < N; i++) {
9028                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9029
9030                                final Intent sufficientIntent = new Intent(verification);
9031                                sufficientIntent.setComponent(verifierComponent);
9032
9033                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9034                            }
9035                        }
9036                    }
9037
9038                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9039                            mRequiredVerifierPackage, receivers);
9040                    if (ret == PackageManager.INSTALL_SUCCEEDED
9041                            && mRequiredVerifierPackage != null) {
9042                        /*
9043                         * Send the intent to the required verification agent,
9044                         * but only start the verification timeout after the
9045                         * target BroadcastReceivers have run.
9046                         */
9047                        verification.setComponent(requiredVerifierComponent);
9048                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9049                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9050                                new BroadcastReceiver() {
9051                                    @Override
9052                                    public void onReceive(Context context, Intent intent) {
9053                                        final Message msg = mHandler
9054                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9055                                        msg.arg1 = verificationId;
9056                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9057                                    }
9058                                }, null, 0, null, null);
9059
9060                        /*
9061                         * We don't want the copy to proceed until verification
9062                         * succeeds, so null out this field.
9063                         */
9064                        mArgs = null;
9065                    }
9066                } else {
9067                    /*
9068                     * No package verification is enabled, so immediately start
9069                     * the remote call to initiate copy using temporary file.
9070                     */
9071                    ret = args.copyApk(mContainerService, true);
9072                }
9073            }
9074
9075            mRet = ret;
9076        }
9077
9078        @Override
9079        void handleReturnCode() {
9080            // If mArgs is null, then MCS couldn't be reached. When it
9081            // reconnects, it will try again to install. At that point, this
9082            // will succeed.
9083            if (mArgs != null) {
9084                processPendingInstall(mArgs, mRet);
9085            }
9086        }
9087
9088        @Override
9089        void handleServiceError() {
9090            mArgs = createInstallArgs(this);
9091            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9092        }
9093
9094        public boolean isForwardLocked() {
9095            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9096        }
9097    }
9098
9099    /**
9100     * Used during creation of InstallArgs
9101     *
9102     * @param installFlags package installation flags
9103     * @return true if should be installed on external storage
9104     */
9105    private static boolean installOnSd(int installFlags) {
9106        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9107            return false;
9108        }
9109        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9110            return true;
9111        }
9112        return false;
9113    }
9114
9115    /**
9116     * Used during creation of InstallArgs
9117     *
9118     * @param installFlags package installation flags
9119     * @return true if should be installed as forward locked
9120     */
9121    private static boolean installForwardLocked(int installFlags) {
9122        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9123    }
9124
9125    private InstallArgs createInstallArgs(InstallParams params) {
9126        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9127            return new AsecInstallArgs(params);
9128        } else {
9129            return new FileInstallArgs(params);
9130        }
9131    }
9132
9133    /**
9134     * Create args that describe an existing installed package. Typically used
9135     * when cleaning up old installs, or used as a move source.
9136     */
9137    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9138            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9139        final boolean isInAsec;
9140        if (installOnSd(installFlags)) {
9141            /* Apps on SD card are always in ASEC containers. */
9142            isInAsec = true;
9143        } else if (installForwardLocked(installFlags)
9144                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9145            /*
9146             * Forward-locked apps are only in ASEC containers if they're the
9147             * new style
9148             */
9149            isInAsec = true;
9150        } else {
9151            isInAsec = false;
9152        }
9153
9154        if (isInAsec) {
9155            return new AsecInstallArgs(codePath, instructionSets,
9156                    installOnSd(installFlags), installForwardLocked(installFlags));
9157        } else {
9158            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9159                    instructionSets);
9160        }
9161    }
9162
9163    static abstract class InstallArgs {
9164        /** @see InstallParams#origin */
9165        final OriginInfo origin;
9166
9167        final IPackageInstallObserver2 observer;
9168        // Always refers to PackageManager flags only
9169        final int installFlags;
9170        final String installerPackageName;
9171        final ManifestDigest manifestDigest;
9172        final UserHandle user;
9173        final String abiOverride;
9174
9175        // The list of instruction sets supported by this app. This is currently
9176        // only used during the rmdex() phase to clean up resources. We can get rid of this
9177        // if we move dex files under the common app path.
9178        /* nullable */ String[] instructionSets;
9179
9180        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9181                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9182                String[] instructionSets, String abiOverride) {
9183            this.origin = origin;
9184            this.installFlags = installFlags;
9185            this.observer = observer;
9186            this.installerPackageName = installerPackageName;
9187            this.manifestDigest = manifestDigest;
9188            this.user = user;
9189            this.instructionSets = instructionSets;
9190            this.abiOverride = abiOverride;
9191        }
9192
9193        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9194        abstract int doPreInstall(int status);
9195
9196        /**
9197         * Rename package into final resting place. All paths on the given
9198         * scanned package should be updated to reflect the rename.
9199         */
9200        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9201        abstract int doPostInstall(int status, int uid);
9202
9203        /** @see PackageSettingBase#codePathString */
9204        abstract String getCodePath();
9205        /** @see PackageSettingBase#resourcePathString */
9206        abstract String getResourcePath();
9207        abstract String getLegacyNativeLibraryPath();
9208
9209        // Need installer lock especially for dex file removal.
9210        abstract void cleanUpResourcesLI();
9211        abstract boolean doPostDeleteLI(boolean delete);
9212        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9213
9214        /**
9215         * Called before the source arguments are copied. This is used mostly
9216         * for MoveParams when it needs to read the source file to put it in the
9217         * destination.
9218         */
9219        int doPreCopy() {
9220            return PackageManager.INSTALL_SUCCEEDED;
9221        }
9222
9223        /**
9224         * Called after the source arguments are copied. This is used mostly for
9225         * MoveParams when it needs to read the source file to put it in the
9226         * destination.
9227         *
9228         * @return
9229         */
9230        int doPostCopy(int uid) {
9231            return PackageManager.INSTALL_SUCCEEDED;
9232        }
9233
9234        protected boolean isFwdLocked() {
9235            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9236        }
9237
9238        protected boolean isExternal() {
9239            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9240        }
9241
9242        UserHandle getUser() {
9243            return user;
9244        }
9245    }
9246
9247    /**
9248     * Logic to handle installation of non-ASEC applications, including copying
9249     * and renaming logic.
9250     */
9251    class FileInstallArgs extends InstallArgs {
9252        private File codeFile;
9253        private File resourceFile;
9254        private File legacyNativeLibraryPath;
9255
9256        // Example topology:
9257        // /data/app/com.example/base.apk
9258        // /data/app/com.example/split_foo.apk
9259        // /data/app/com.example/lib/arm/libfoo.so
9260        // /data/app/com.example/lib/arm64/libfoo.so
9261        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9262
9263        /** New install */
9264        FileInstallArgs(InstallParams params) {
9265            super(params.origin, params.observer, params.installFlags,
9266                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9267                    null /* instruction sets */, params.packageAbiOverride);
9268            if (isFwdLocked()) {
9269                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9270            }
9271        }
9272
9273        /** Existing install */
9274        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9275                String[] instructionSets) {
9276            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9277            this.codeFile = (codePath != null) ? new File(codePath) : null;
9278            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9279            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9280                    new File(legacyNativeLibraryPath) : null;
9281        }
9282
9283        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9284            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9285                    isFwdLocked(), abiOverride);
9286
9287            final StorageManager storage = StorageManager.from(mContext);
9288            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9289        }
9290
9291        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9292            if (origin.staged) {
9293                Slog.d(TAG, origin.file + " already staged; skipping copy");
9294                codeFile = origin.file;
9295                resourceFile = origin.file;
9296                return PackageManager.INSTALL_SUCCEEDED;
9297            }
9298
9299            try {
9300                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9301                codeFile = tempDir;
9302                resourceFile = tempDir;
9303            } catch (IOException e) {
9304                Slog.w(TAG, "Failed to create copy file: " + e);
9305                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9306            }
9307
9308            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9309                @Override
9310                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9311                    if (!FileUtils.isValidExtFilename(name)) {
9312                        throw new IllegalArgumentException("Invalid filename: " + name);
9313                    }
9314                    try {
9315                        final File file = new File(codeFile, name);
9316                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9317                                O_RDWR | O_CREAT, 0644);
9318                        Os.chmod(file.getAbsolutePath(), 0644);
9319                        return new ParcelFileDescriptor(fd);
9320                    } catch (ErrnoException e) {
9321                        throw new RemoteException("Failed to open: " + e.getMessage());
9322                    }
9323                }
9324            };
9325
9326            int ret = PackageManager.INSTALL_SUCCEEDED;
9327            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9328            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9329                Slog.e(TAG, "Failed to copy package");
9330                return ret;
9331            }
9332
9333            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9334            NativeLibraryHelper.Handle handle = null;
9335            try {
9336                handle = NativeLibraryHelper.Handle.create(codeFile);
9337                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9338                        abiOverride);
9339            } catch (IOException e) {
9340                Slog.e(TAG, "Copying native libraries failed", e);
9341                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9342            } finally {
9343                IoUtils.closeQuietly(handle);
9344            }
9345
9346            return ret;
9347        }
9348
9349        int doPreInstall(int status) {
9350            if (status != PackageManager.INSTALL_SUCCEEDED) {
9351                cleanUp();
9352            }
9353            return status;
9354        }
9355
9356        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9357            if (status != PackageManager.INSTALL_SUCCEEDED) {
9358                cleanUp();
9359                return false;
9360            } else {
9361                final File beforeCodeFile = codeFile;
9362                final File afterCodeFile = getNextCodePath(pkg.packageName);
9363
9364                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9365                try {
9366                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9367                } catch (ErrnoException e) {
9368                    Slog.d(TAG, "Failed to rename", e);
9369                    return false;
9370                }
9371
9372                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9373                    Slog.d(TAG, "Failed to restorecon");
9374                    return false;
9375                }
9376
9377                // Reflect the rename internally
9378                codeFile = afterCodeFile;
9379                resourceFile = afterCodeFile;
9380
9381                // Reflect the rename in scanned details
9382                pkg.codePath = afterCodeFile.getAbsolutePath();
9383                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9384                        pkg.baseCodePath);
9385                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9386                        pkg.splitCodePaths);
9387
9388                // Reflect the rename in app info
9389                pkg.applicationInfo.setCodePath(pkg.codePath);
9390                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9391                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9392                pkg.applicationInfo.setResourcePath(pkg.codePath);
9393                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9394                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9395
9396                return true;
9397            }
9398        }
9399
9400        int doPostInstall(int status, int uid) {
9401            if (status != PackageManager.INSTALL_SUCCEEDED) {
9402                cleanUp();
9403            }
9404            return status;
9405        }
9406
9407        @Override
9408        String getCodePath() {
9409            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9410        }
9411
9412        @Override
9413        String getResourcePath() {
9414            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9415        }
9416
9417        @Override
9418        String getLegacyNativeLibraryPath() {
9419            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9420        }
9421
9422        private boolean cleanUp() {
9423            if (codeFile == null || !codeFile.exists()) {
9424                return false;
9425            }
9426
9427            if (codeFile.isDirectory()) {
9428                FileUtils.deleteContents(codeFile);
9429            }
9430            codeFile.delete();
9431
9432            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9433                resourceFile.delete();
9434            }
9435
9436            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9437                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9438                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9439                }
9440                legacyNativeLibraryPath.delete();
9441            }
9442
9443            return true;
9444        }
9445
9446        void cleanUpResourcesLI() {
9447            // Try enumerating all code paths before deleting
9448            List<String> allCodePaths = Collections.EMPTY_LIST;
9449            if (codeFile != null && codeFile.exists()) {
9450                try {
9451                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9452                    allCodePaths = pkg.getAllCodePaths();
9453                } catch (PackageParserException e) {
9454                    // Ignored; we tried our best
9455                }
9456            }
9457
9458            cleanUp();
9459
9460            if (!allCodePaths.isEmpty()) {
9461                if (instructionSets == null) {
9462                    throw new IllegalStateException("instructionSet == null");
9463                }
9464                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9465                for (String codePath : allCodePaths) {
9466                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9467                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9468                        if (retCode < 0) {
9469                            Slog.w(TAG, "Couldn't remove dex file for package: "
9470                                    + " at location " + codePath + ", retcode=" + retCode);
9471                            // we don't consider this to be a failure of the core package deletion
9472                        }
9473                    }
9474                }
9475            }
9476        }
9477
9478        boolean doPostDeleteLI(boolean delete) {
9479            // XXX err, shouldn't we respect the delete flag?
9480            cleanUpResourcesLI();
9481            return true;
9482        }
9483    }
9484
9485    private boolean isAsecExternal(String cid) {
9486        final String asecPath = PackageHelper.getSdFilesystem(cid);
9487        return !asecPath.startsWith(mAsecInternalPath);
9488    }
9489
9490    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9491            PackageManagerException {
9492        if (copyRet < 0) {
9493            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9494                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9495                throw new PackageManagerException(copyRet, message);
9496            }
9497        }
9498    }
9499
9500    /**
9501     * Extract the MountService "container ID" from the full code path of an
9502     * .apk.
9503     */
9504    static String cidFromCodePath(String fullCodePath) {
9505        int eidx = fullCodePath.lastIndexOf("/");
9506        String subStr1 = fullCodePath.substring(0, eidx);
9507        int sidx = subStr1.lastIndexOf("/");
9508        return subStr1.substring(sidx+1, eidx);
9509    }
9510
9511    /**
9512     * Logic to handle installation of ASEC applications, including copying and
9513     * renaming logic.
9514     */
9515    class AsecInstallArgs extends InstallArgs {
9516        static final String RES_FILE_NAME = "pkg.apk";
9517        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9518
9519        String cid;
9520        String packagePath;
9521        String resourcePath;
9522        String legacyNativeLibraryDir;
9523
9524        /** New install */
9525        AsecInstallArgs(InstallParams params) {
9526            super(params.origin, params.observer, params.installFlags,
9527                    params.installerPackageName, params.getManifestDigest(),
9528                    params.getUser(), null /* instruction sets */,
9529                    params.packageAbiOverride);
9530        }
9531
9532        /** Existing install */
9533        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9534                        boolean isExternal, boolean isForwardLocked) {
9535            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9536                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9537                    instructionSets, null);
9538            // Hackily pretend we're still looking at a full code path
9539            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9540                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9541            }
9542
9543            // Extract cid from fullCodePath
9544            int eidx = fullCodePath.lastIndexOf("/");
9545            String subStr1 = fullCodePath.substring(0, eidx);
9546            int sidx = subStr1.lastIndexOf("/");
9547            cid = subStr1.substring(sidx+1, eidx);
9548            setMountPath(subStr1);
9549        }
9550
9551        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9552            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9553                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9554                    instructionSets, null);
9555            this.cid = cid;
9556            setMountPath(PackageHelper.getSdDir(cid));
9557        }
9558
9559        void createCopyFile() {
9560            cid = mInstallerService.allocateExternalStageCidLegacy();
9561        }
9562
9563        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9564            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9565                    abiOverride);
9566
9567            final File target;
9568            if (isExternal()) {
9569                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9570            } else {
9571                target = Environment.getDataDirectory();
9572            }
9573
9574            final StorageManager storage = StorageManager.from(mContext);
9575            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9576        }
9577
9578        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9579            if (origin.staged) {
9580                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9581                cid = origin.cid;
9582                setMountPath(PackageHelper.getSdDir(cid));
9583                return PackageManager.INSTALL_SUCCEEDED;
9584            }
9585
9586            if (temp) {
9587                createCopyFile();
9588            } else {
9589                /*
9590                 * Pre-emptively destroy the container since it's destroyed if
9591                 * copying fails due to it existing anyway.
9592                 */
9593                PackageHelper.destroySdDir(cid);
9594            }
9595
9596            final String newMountPath = imcs.copyPackageToContainer(
9597                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9598                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9599
9600            if (newMountPath != null) {
9601                setMountPath(newMountPath);
9602                return PackageManager.INSTALL_SUCCEEDED;
9603            } else {
9604                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9605            }
9606        }
9607
9608        @Override
9609        String getCodePath() {
9610            return packagePath;
9611        }
9612
9613        @Override
9614        String getResourcePath() {
9615            return resourcePath;
9616        }
9617
9618        @Override
9619        String getLegacyNativeLibraryPath() {
9620            return legacyNativeLibraryDir;
9621        }
9622
9623        int doPreInstall(int status) {
9624            if (status != PackageManager.INSTALL_SUCCEEDED) {
9625                // Destroy container
9626                PackageHelper.destroySdDir(cid);
9627            } else {
9628                boolean mounted = PackageHelper.isContainerMounted(cid);
9629                if (!mounted) {
9630                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9631                            Process.SYSTEM_UID);
9632                    if (newMountPath != null) {
9633                        setMountPath(newMountPath);
9634                    } else {
9635                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9636                    }
9637                }
9638            }
9639            return status;
9640        }
9641
9642        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9643            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9644            String newMountPath = null;
9645            if (PackageHelper.isContainerMounted(cid)) {
9646                // Unmount the container
9647                if (!PackageHelper.unMountSdDir(cid)) {
9648                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9649                    return false;
9650                }
9651            }
9652            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9653                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9654                        " which might be stale. Will try to clean up.");
9655                // Clean up the stale container and proceed to recreate.
9656                if (!PackageHelper.destroySdDir(newCacheId)) {
9657                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9658                    return false;
9659                }
9660                // Successfully cleaned up stale container. Try to rename again.
9661                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9662                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9663                            + " inspite of cleaning it up.");
9664                    return false;
9665                }
9666            }
9667            if (!PackageHelper.isContainerMounted(newCacheId)) {
9668                Slog.w(TAG, "Mounting container " + newCacheId);
9669                newMountPath = PackageHelper.mountSdDir(newCacheId,
9670                        getEncryptKey(), Process.SYSTEM_UID);
9671            } else {
9672                newMountPath = PackageHelper.getSdDir(newCacheId);
9673            }
9674            if (newMountPath == null) {
9675                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9676                return false;
9677            }
9678            Log.i(TAG, "Succesfully renamed " + cid +
9679                    " to " + newCacheId +
9680                    " at new path: " + newMountPath);
9681            cid = newCacheId;
9682
9683            final File beforeCodeFile = new File(packagePath);
9684            setMountPath(newMountPath);
9685            final File afterCodeFile = new File(packagePath);
9686
9687            // Reflect the rename in scanned details
9688            pkg.codePath = afterCodeFile.getAbsolutePath();
9689            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9690                    pkg.baseCodePath);
9691            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9692                    pkg.splitCodePaths);
9693
9694            // Reflect the rename in app info
9695            pkg.applicationInfo.setCodePath(pkg.codePath);
9696            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9697            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9698            pkg.applicationInfo.setResourcePath(pkg.codePath);
9699            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9700            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9701
9702            return true;
9703        }
9704
9705        private void setMountPath(String mountPath) {
9706            final File mountFile = new File(mountPath);
9707
9708            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9709            if (monolithicFile.exists()) {
9710                packagePath = monolithicFile.getAbsolutePath();
9711                if (isFwdLocked()) {
9712                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9713                } else {
9714                    resourcePath = packagePath;
9715                }
9716            } else {
9717                packagePath = mountFile.getAbsolutePath();
9718                resourcePath = packagePath;
9719            }
9720
9721            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9722        }
9723
9724        int doPostInstall(int status, int uid) {
9725            if (status != PackageManager.INSTALL_SUCCEEDED) {
9726                cleanUp();
9727            } else {
9728                final int groupOwner;
9729                final String protectedFile;
9730                if (isFwdLocked()) {
9731                    groupOwner = UserHandle.getSharedAppGid(uid);
9732                    protectedFile = RES_FILE_NAME;
9733                } else {
9734                    groupOwner = -1;
9735                    protectedFile = null;
9736                }
9737
9738                if (uid < Process.FIRST_APPLICATION_UID
9739                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9740                    Slog.e(TAG, "Failed to finalize " + cid);
9741                    PackageHelper.destroySdDir(cid);
9742                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9743                }
9744
9745                boolean mounted = PackageHelper.isContainerMounted(cid);
9746                if (!mounted) {
9747                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9748                }
9749            }
9750            return status;
9751        }
9752
9753        private void cleanUp() {
9754            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9755
9756            // Destroy secure container
9757            PackageHelper.destroySdDir(cid);
9758        }
9759
9760        private List<String> getAllCodePaths() {
9761            final File codeFile = new File(getCodePath());
9762            if (codeFile != null && codeFile.exists()) {
9763                try {
9764                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9765                    return pkg.getAllCodePaths();
9766                } catch (PackageParserException e) {
9767                    // Ignored; we tried our best
9768                }
9769            }
9770            return Collections.EMPTY_LIST;
9771        }
9772
9773        void cleanUpResourcesLI() {
9774            // Enumerate all code paths before deleting
9775            cleanUpResourcesLI(getAllCodePaths());
9776        }
9777
9778        private void cleanUpResourcesLI(List<String> allCodePaths) {
9779            cleanUp();
9780
9781            if (!allCodePaths.isEmpty()) {
9782                if (instructionSets == null) {
9783                    throw new IllegalStateException("instructionSet == null");
9784                }
9785                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9786                for (String codePath : allCodePaths) {
9787                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9788                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9789                        if (retCode < 0) {
9790                            Slog.w(TAG, "Couldn't remove dex file for package: "
9791                                    + " at location " + codePath + ", retcode=" + retCode);
9792                            // we don't consider this to be a failure of the core package deletion
9793                        }
9794                    }
9795                }
9796            }
9797        }
9798
9799        boolean matchContainer(String app) {
9800            if (cid.startsWith(app)) {
9801                return true;
9802            }
9803            return false;
9804        }
9805
9806        String getPackageName() {
9807            return getAsecPackageName(cid);
9808        }
9809
9810        boolean doPostDeleteLI(boolean delete) {
9811            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9812            final List<String> allCodePaths = getAllCodePaths();
9813            boolean mounted = PackageHelper.isContainerMounted(cid);
9814            if (mounted) {
9815                // Unmount first
9816                if (PackageHelper.unMountSdDir(cid)) {
9817                    mounted = false;
9818                }
9819            }
9820            if (!mounted && delete) {
9821                cleanUpResourcesLI(allCodePaths);
9822            }
9823            return !mounted;
9824        }
9825
9826        @Override
9827        int doPreCopy() {
9828            if (isFwdLocked()) {
9829                if (!PackageHelper.fixSdPermissions(cid,
9830                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9831                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9832                }
9833            }
9834
9835            return PackageManager.INSTALL_SUCCEEDED;
9836        }
9837
9838        @Override
9839        int doPostCopy(int uid) {
9840            if (isFwdLocked()) {
9841                if (uid < Process.FIRST_APPLICATION_UID
9842                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9843                                RES_FILE_NAME)) {
9844                    Slog.e(TAG, "Failed to finalize " + cid);
9845                    PackageHelper.destroySdDir(cid);
9846                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9847                }
9848            }
9849
9850            return PackageManager.INSTALL_SUCCEEDED;
9851        }
9852    }
9853
9854    static String getAsecPackageName(String packageCid) {
9855        int idx = packageCid.lastIndexOf("-");
9856        if (idx == -1) {
9857            return packageCid;
9858        }
9859        return packageCid.substring(0, idx);
9860    }
9861
9862    // Utility method used to create code paths based on package name and available index.
9863    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9864        String idxStr = "";
9865        int idx = 1;
9866        // Fall back to default value of idx=1 if prefix is not
9867        // part of oldCodePath
9868        if (oldCodePath != null) {
9869            String subStr = oldCodePath;
9870            // Drop the suffix right away
9871            if (suffix != null && subStr.endsWith(suffix)) {
9872                subStr = subStr.substring(0, subStr.length() - suffix.length());
9873            }
9874            // If oldCodePath already contains prefix find out the
9875            // ending index to either increment or decrement.
9876            int sidx = subStr.lastIndexOf(prefix);
9877            if (sidx != -1) {
9878                subStr = subStr.substring(sidx + prefix.length());
9879                if (subStr != null) {
9880                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9881                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9882                    }
9883                    try {
9884                        idx = Integer.parseInt(subStr);
9885                        if (idx <= 1) {
9886                            idx++;
9887                        } else {
9888                            idx--;
9889                        }
9890                    } catch(NumberFormatException e) {
9891                    }
9892                }
9893            }
9894        }
9895        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9896        return prefix + idxStr;
9897    }
9898
9899    private File getNextCodePath(String packageName) {
9900        int suffix = 1;
9901        File result;
9902        do {
9903            result = new File(mAppInstallDir, packageName + "-" + suffix);
9904            suffix++;
9905        } while (result.exists());
9906        return result;
9907    }
9908
9909    // Utility method used to ignore ADD/REMOVE events
9910    // by directory observer.
9911    private static boolean ignoreCodePath(String fullPathStr) {
9912        String apkName = deriveCodePathName(fullPathStr);
9913        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9914        if (idx != -1 && ((idx+1) < apkName.length())) {
9915            // Make sure the package ends with a numeral
9916            String version = apkName.substring(idx+1);
9917            try {
9918                Integer.parseInt(version);
9919                return true;
9920            } catch (NumberFormatException e) {}
9921        }
9922        return false;
9923    }
9924
9925    // Utility method that returns the relative package path with respect
9926    // to the installation directory. Like say for /data/data/com.test-1.apk
9927    // string com.test-1 is returned.
9928    static String deriveCodePathName(String codePath) {
9929        if (codePath == null) {
9930            return null;
9931        }
9932        final File codeFile = new File(codePath);
9933        final String name = codeFile.getName();
9934        if (codeFile.isDirectory()) {
9935            return name;
9936        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9937            final int lastDot = name.lastIndexOf('.');
9938            return name.substring(0, lastDot);
9939        } else {
9940            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9941            return null;
9942        }
9943    }
9944
9945    class PackageInstalledInfo {
9946        String name;
9947        int uid;
9948        // The set of users that originally had this package installed.
9949        int[] origUsers;
9950        // The set of users that now have this package installed.
9951        int[] newUsers;
9952        PackageParser.Package pkg;
9953        int returnCode;
9954        String returnMsg;
9955        PackageRemovedInfo removedInfo;
9956
9957        public void setError(int code, String msg) {
9958            returnCode = code;
9959            returnMsg = msg;
9960            Slog.w(TAG, msg);
9961        }
9962
9963        public void setError(String msg, PackageParserException e) {
9964            returnCode = e.error;
9965            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9966            Slog.w(TAG, msg, e);
9967        }
9968
9969        public void setError(String msg, PackageManagerException e) {
9970            returnCode = e.error;
9971            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9972            Slog.w(TAG, msg, e);
9973        }
9974
9975        // In some error cases we want to convey more info back to the observer
9976        String origPackage;
9977        String origPermission;
9978    }
9979
9980    /*
9981     * Install a non-existing package.
9982     */
9983    private void installNewPackageLI(PackageParser.Package pkg,
9984            int parseFlags, int scanFlags, UserHandle user,
9985            String installerPackageName, PackageInstalledInfo res) {
9986        // Remember this for later, in case we need to rollback this install
9987        String pkgName = pkg.packageName;
9988
9989        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9990        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9991        synchronized(mPackages) {
9992            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9993                // A package with the same name is already installed, though
9994                // it has been renamed to an older name.  The package we
9995                // are trying to install should be installed as an update to
9996                // the existing one, but that has not been requested, so bail.
9997                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9998                        + " without first uninstalling package running as "
9999                        + mSettings.mRenamedPackages.get(pkgName));
10000                return;
10001            }
10002            if (mPackages.containsKey(pkgName)) {
10003                // Don't allow installation over an existing package with the same name.
10004                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10005                        + " without first uninstalling.");
10006                return;
10007            }
10008        }
10009
10010        try {
10011            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10012                    System.currentTimeMillis(), user);
10013
10014            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10015            // delete the partially installed application. the data directory will have to be
10016            // restored if it was already existing
10017            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10018                // remove package from internal structures.  Note that we want deletePackageX to
10019                // delete the package data and cache directories that it created in
10020                // scanPackageLocked, unless those directories existed before we even tried to
10021                // install.
10022                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10023                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10024                                res.removedInfo, true);
10025            }
10026
10027        } catch (PackageManagerException e) {
10028            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10029        }
10030    }
10031
10032    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10033        // Upgrade keysets are being used.  Determine if new package has a superset of the
10034        // required keys.
10035        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10036        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10037        for (int i = 0; i < upgradeKeySets.length; i++) {
10038            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10039            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10040                return true;
10041            }
10042        }
10043        return false;
10044    }
10045
10046    private void replacePackageLI(PackageParser.Package pkg,
10047            int parseFlags, int scanFlags, UserHandle user,
10048            String installerPackageName, PackageInstalledInfo res) {
10049        PackageParser.Package oldPackage;
10050        String pkgName = pkg.packageName;
10051        int[] allUsers;
10052        boolean[] perUserInstalled;
10053
10054        // First find the old package info and check signatures
10055        synchronized(mPackages) {
10056            oldPackage = mPackages.get(pkgName);
10057            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10058            PackageSetting ps = mSettings.mPackages.get(pkgName);
10059            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10060                // default to original signature matching
10061                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10062                    != PackageManager.SIGNATURE_MATCH) {
10063                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10064                            "New package has a different signature: " + pkgName);
10065                    return;
10066                }
10067            } else {
10068                if(!checkUpgradeKeySetLP(ps, pkg)) {
10069                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10070                            "New package not signed by keys specified by upgrade-keysets: "
10071                            + pkgName);
10072                    return;
10073                }
10074            }
10075
10076            // In case of rollback, remember per-user/profile install state
10077            allUsers = sUserManager.getUserIds();
10078            perUserInstalled = new boolean[allUsers.length];
10079            for (int i = 0; i < allUsers.length; i++) {
10080                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10081            }
10082        }
10083
10084        boolean sysPkg = (isSystemApp(oldPackage));
10085        if (sysPkg) {
10086            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10087                    user, allUsers, perUserInstalled, installerPackageName, res);
10088        } else {
10089            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10090                    user, allUsers, perUserInstalled, installerPackageName, res);
10091        }
10092    }
10093
10094    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10095            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10096            int[] allUsers, boolean[] perUserInstalled,
10097            String installerPackageName, PackageInstalledInfo res) {
10098        String pkgName = deletedPackage.packageName;
10099        boolean deletedPkg = true;
10100        boolean updatedSettings = false;
10101
10102        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10103                + deletedPackage);
10104        long origUpdateTime;
10105        if (pkg.mExtras != null) {
10106            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10107        } else {
10108            origUpdateTime = 0;
10109        }
10110
10111        // First delete the existing package while retaining the data directory
10112        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10113                res.removedInfo, true)) {
10114            // If the existing package wasn't successfully deleted
10115            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10116            deletedPkg = false;
10117        } else {
10118            // Successfully deleted the old package; proceed with replace.
10119
10120            // If deleted package lived in a container, give users a chance to
10121            // relinquish resources before killing.
10122            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10123                if (DEBUG_INSTALL) {
10124                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10125                }
10126                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10127                final ArrayList<String> pkgList = new ArrayList<String>(1);
10128                pkgList.add(deletedPackage.applicationInfo.packageName);
10129                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10130            }
10131
10132            deleteCodeCacheDirsLI(pkgName);
10133            try {
10134                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10135                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10136                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10137                updatedSettings = true;
10138            } catch (PackageManagerException e) {
10139                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10140            }
10141        }
10142
10143        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10144            // remove package from internal structures.  Note that we want deletePackageX to
10145            // delete the package data and cache directories that it created in
10146            // scanPackageLocked, unless those directories existed before we even tried to
10147            // install.
10148            if(updatedSettings) {
10149                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10150                deletePackageLI(
10151                        pkgName, null, true, allUsers, perUserInstalled,
10152                        PackageManager.DELETE_KEEP_DATA,
10153                                res.removedInfo, true);
10154            }
10155            // Since we failed to install the new package we need to restore the old
10156            // package that we deleted.
10157            if (deletedPkg) {
10158                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10159                File restoreFile = new File(deletedPackage.codePath);
10160                // Parse old package
10161                boolean oldOnSd = isExternal(deletedPackage);
10162                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10163                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10164                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10165                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10166                try {
10167                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10168                } catch (PackageManagerException e) {
10169                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10170                            + e.getMessage());
10171                    return;
10172                }
10173                // Restore of old package succeeded. Update permissions.
10174                // writer
10175                synchronized (mPackages) {
10176                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10177                            UPDATE_PERMISSIONS_ALL);
10178                    // can downgrade to reader
10179                    mSettings.writeLPr();
10180                }
10181                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10182            }
10183        }
10184    }
10185
10186    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10187            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10188            int[] allUsers, boolean[] perUserInstalled,
10189            String installerPackageName, PackageInstalledInfo res) {
10190        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10191                + ", old=" + deletedPackage);
10192        boolean disabledSystem = false;
10193        boolean updatedSettings = false;
10194        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10195        if ((deletedPackage.applicationInfo.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
10196                != 0) {
10197            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10198        }
10199        String packageName = deletedPackage.packageName;
10200        if (packageName == null) {
10201            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10202                    "Attempt to delete null packageName.");
10203            return;
10204        }
10205        PackageParser.Package oldPkg;
10206        PackageSetting oldPkgSetting;
10207        // reader
10208        synchronized (mPackages) {
10209            oldPkg = mPackages.get(packageName);
10210            oldPkgSetting = mSettings.mPackages.get(packageName);
10211            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10212                    (oldPkgSetting == null)) {
10213                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10214                        "Couldn't find package:" + packageName + " information");
10215                return;
10216            }
10217        }
10218
10219        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10220
10221        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10222        res.removedInfo.removedPackage = packageName;
10223        // Remove existing system package
10224        removePackageLI(oldPkgSetting, true);
10225        // writer
10226        synchronized (mPackages) {
10227            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10228            if (!disabledSystem && deletedPackage != null) {
10229                // We didn't need to disable the .apk as a current system package,
10230                // which means we are replacing another update that is already
10231                // installed.  We need to make sure to delete the older one's .apk.
10232                res.removedInfo.args = createInstallArgsForExisting(0,
10233                        deletedPackage.applicationInfo.getCodePath(),
10234                        deletedPackage.applicationInfo.getResourcePath(),
10235                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10236                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10237            } else {
10238                res.removedInfo.args = null;
10239            }
10240        }
10241
10242        // Successfully disabled the old package. Now proceed with re-installation
10243        deleteCodeCacheDirsLI(packageName);
10244
10245        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10246        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10247
10248        PackageParser.Package newPackage = null;
10249        try {
10250            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10251            if (newPackage.mExtras != null) {
10252                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10253                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10254                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10255
10256                // is the update attempting to change shared user? that isn't going to work...
10257                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10258                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10259                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10260                            + " to " + newPkgSetting.sharedUser);
10261                    updatedSettings = true;
10262                }
10263            }
10264
10265            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10266                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10267                updatedSettings = true;
10268            }
10269
10270        } catch (PackageManagerException e) {
10271            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10272        }
10273
10274        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10275            // Re installation failed. Restore old information
10276            // Remove new pkg information
10277            if (newPackage != null) {
10278                removeInstalledPackageLI(newPackage, true);
10279            }
10280            // Add back the old system package
10281            try {
10282                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10283            } catch (PackageManagerException e) {
10284                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10285            }
10286            // Restore the old system information in Settings
10287            synchronized (mPackages) {
10288                if (disabledSystem) {
10289                    mSettings.enableSystemPackageLPw(packageName);
10290                }
10291                if (updatedSettings) {
10292                    mSettings.setInstallerPackageName(packageName,
10293                            oldPkgSetting.installerPackageName);
10294                }
10295                mSettings.writeLPr();
10296            }
10297        }
10298    }
10299
10300    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10301            int[] allUsers, boolean[] perUserInstalled,
10302            PackageInstalledInfo res) {
10303        String pkgName = newPackage.packageName;
10304        synchronized (mPackages) {
10305            //write settings. the installStatus will be incomplete at this stage.
10306            //note that the new package setting would have already been
10307            //added to mPackages. It hasn't been persisted yet.
10308            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10309            mSettings.writeLPr();
10310        }
10311
10312        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10313
10314        synchronized (mPackages) {
10315            updatePermissionsLPw(newPackage.packageName, newPackage,
10316                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10317                            ? UPDATE_PERMISSIONS_ALL : 0));
10318            // For system-bundled packages, we assume that installing an upgraded version
10319            // of the package implies that the user actually wants to run that new code,
10320            // so we enable the package.
10321            if (isSystemApp(newPackage)) {
10322                // NB: implicit assumption that system package upgrades apply to all users
10323                if (DEBUG_INSTALL) {
10324                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10325                }
10326                PackageSetting ps = mSettings.mPackages.get(pkgName);
10327                if (ps != null) {
10328                    if (res.origUsers != null) {
10329                        for (int userHandle : res.origUsers) {
10330                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10331                                    userHandle, installerPackageName);
10332                        }
10333                    }
10334                    // Also convey the prior install/uninstall state
10335                    if (allUsers != null && perUserInstalled != null) {
10336                        for (int i = 0; i < allUsers.length; i++) {
10337                            if (DEBUG_INSTALL) {
10338                                Slog.d(TAG, "    user " + allUsers[i]
10339                                        + " => " + perUserInstalled[i]);
10340                            }
10341                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10342                        }
10343                        // these install state changes will be persisted in the
10344                        // upcoming call to mSettings.writeLPr().
10345                    }
10346                }
10347            }
10348            res.name = pkgName;
10349            res.uid = newPackage.applicationInfo.uid;
10350            res.pkg = newPackage;
10351            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10352            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10353            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10354            //to update install status
10355            mSettings.writeLPr();
10356        }
10357    }
10358
10359    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10360        final int installFlags = args.installFlags;
10361        String installerPackageName = args.installerPackageName;
10362        File tmpPackageFile = new File(args.getCodePath());
10363        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10364        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10365        boolean replace = false;
10366        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10367        // Result object to be returned
10368        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10369
10370        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10371        // Retrieve PackageSettings and parse package
10372        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10373                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10374                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10375        PackageParser pp = new PackageParser();
10376        pp.setSeparateProcesses(mSeparateProcesses);
10377        pp.setDisplayMetrics(mMetrics);
10378
10379        final PackageParser.Package pkg;
10380        try {
10381            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10382        } catch (PackageParserException e) {
10383            res.setError("Failed parse during installPackageLI", e);
10384            return;
10385        }
10386
10387        // Mark that we have an install time CPU ABI override.
10388        pkg.cpuAbiOverride = args.abiOverride;
10389
10390        String pkgName = res.name = pkg.packageName;
10391        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10392            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10393                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10394                return;
10395            }
10396        }
10397
10398        try {
10399            pp.collectCertificates(pkg, parseFlags);
10400            pp.collectManifestDigest(pkg);
10401        } catch (PackageParserException e) {
10402            res.setError("Failed collect during installPackageLI", e);
10403            return;
10404        }
10405
10406        /* If the installer passed in a manifest digest, compare it now. */
10407        if (args.manifestDigest != null) {
10408            if (DEBUG_INSTALL) {
10409                final String parsedManifest = pkg.manifestDigest == null ? "null"
10410                        : pkg.manifestDigest.toString();
10411                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10412                        + parsedManifest);
10413            }
10414
10415            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10416                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10417                return;
10418            }
10419        } else if (DEBUG_INSTALL) {
10420            final String parsedManifest = pkg.manifestDigest == null
10421                    ? "null" : pkg.manifestDigest.toString();
10422            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10423        }
10424
10425        // Get rid of all references to package scan path via parser.
10426        pp = null;
10427        String oldCodePath = null;
10428        boolean systemApp = false;
10429        synchronized (mPackages) {
10430            // Check whether the newly-scanned package wants to define an already-defined perm
10431            int N = pkg.permissions.size();
10432            for (int i = N-1; i >= 0; i--) {
10433                PackageParser.Permission perm = pkg.permissions.get(i);
10434                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10435                if (bp != null) {
10436                    // If the defining package is signed with our cert, it's okay.  This
10437                    // also includes the "updating the same package" case, of course.
10438                    // "updating same package" could also involve key-rotation.
10439                    final boolean sigsOk;
10440                    if (!bp.sourcePackage.equals(pkg.packageName)
10441                            || !(bp.packageSetting instanceof PackageSetting)
10442                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10443                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10444                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10445                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10446                    } else {
10447                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10448                    }
10449                    if (!sigsOk) {
10450                        // If the owning package is the system itself, we log but allow
10451                        // install to proceed; we fail the install on all other permission
10452                        // redefinitions.
10453                        if (!bp.sourcePackage.equals("android")) {
10454                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10455                                    + pkg.packageName + " attempting to redeclare permission "
10456                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10457                            res.origPermission = perm.info.name;
10458                            res.origPackage = bp.sourcePackage;
10459                            return;
10460                        } else {
10461                            Slog.w(TAG, "Package " + pkg.packageName
10462                                    + " attempting to redeclare system permission "
10463                                    + perm.info.name + "; ignoring new declaration");
10464                            pkg.permissions.remove(i);
10465                        }
10466                    }
10467                }
10468            }
10469
10470            // Check if installing already existing package
10471            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10472                String oldName = mSettings.mRenamedPackages.get(pkgName);
10473                if (pkg.mOriginalPackages != null
10474                        && pkg.mOriginalPackages.contains(oldName)
10475                        && mPackages.containsKey(oldName)) {
10476                    // This package is derived from an original package,
10477                    // and this device has been updating from that original
10478                    // name.  We must continue using the original name, so
10479                    // rename the new package here.
10480                    pkg.setPackageName(oldName);
10481                    pkgName = pkg.packageName;
10482                    replace = true;
10483                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10484                            + oldName + " pkgName=" + pkgName);
10485                } else if (mPackages.containsKey(pkgName)) {
10486                    // This package, under its official name, already exists
10487                    // on the device; we should replace it.
10488                    replace = true;
10489                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10490                }
10491            }
10492            PackageSetting ps = mSettings.mPackages.get(pkgName);
10493            if (ps != null) {
10494                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10495                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10496                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10497                    systemApp = (ps.pkg.applicationInfo.flags &
10498                            ApplicationInfo.FLAG_SYSTEM) != 0;
10499                }
10500                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10501            }
10502        }
10503
10504        if (systemApp && onSd) {
10505            // Disable updates to system apps on sdcard
10506            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10507                    "Cannot install updates to system apps on sdcard");
10508            return;
10509        }
10510
10511        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10512            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10513            return;
10514        }
10515
10516        if (replace) {
10517            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10518                    installerPackageName, res);
10519        } else {
10520            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10521                    args.user, installerPackageName, res);
10522        }
10523        synchronized (mPackages) {
10524            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10525            if (ps != null) {
10526                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10527            }
10528        }
10529    }
10530
10531    private static boolean isForwardLocked(PackageParser.Package pkg) {
10532        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0;
10533    }
10534
10535    private static boolean isForwardLocked(ApplicationInfo info) {
10536        return (info.privateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0;
10537    }
10538
10539    private boolean isForwardLocked(PackageSetting ps) {
10540        return (ps.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_FORWARD_LOCK) != 0;
10541    }
10542
10543    private static boolean isMultiArch(PackageSetting ps) {
10544        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10545    }
10546
10547    private static boolean isMultiArch(ApplicationInfo info) {
10548        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10549    }
10550
10551    private static boolean isExternal(PackageParser.Package pkg) {
10552        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10553    }
10554
10555    private static boolean isExternal(PackageSetting ps) {
10556        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10557    }
10558
10559    private static boolean isExternal(ApplicationInfo info) {
10560        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10561    }
10562
10563    private static boolean isSystemApp(PackageParser.Package pkg) {
10564        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10565    }
10566
10567    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10568        return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0;
10569    }
10570
10571    private static boolean isSystemApp(ApplicationInfo info) {
10572        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10573    }
10574
10575    private static boolean isSystemApp(PackageSetting ps) {
10576        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10577    }
10578
10579    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10580        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10581    }
10582
10583    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10584        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10585    }
10586
10587    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10588        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10589    }
10590
10591    private int packageFlagsToInstallFlags(PackageSetting ps) {
10592        int installFlags = 0;
10593        if (isExternal(ps)) {
10594            installFlags |= PackageManager.INSTALL_EXTERNAL;
10595        }
10596        if (isForwardLocked(ps)) {
10597            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10598        }
10599        return installFlags;
10600    }
10601
10602    private void deleteTempPackageFiles() {
10603        final FilenameFilter filter = new FilenameFilter() {
10604            public boolean accept(File dir, String name) {
10605                return name.startsWith("vmdl") && name.endsWith(".tmp");
10606            }
10607        };
10608        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10609            file.delete();
10610        }
10611    }
10612
10613    @Override
10614    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10615            int flags) {
10616        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10617                flags);
10618    }
10619
10620    @Override
10621    public void deletePackage(final String packageName,
10622            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10623        mContext.enforceCallingOrSelfPermission(
10624                android.Manifest.permission.DELETE_PACKAGES, null);
10625        final int uid = Binder.getCallingUid();
10626        if (UserHandle.getUserId(uid) != userId) {
10627            mContext.enforceCallingPermission(
10628                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10629                    "deletePackage for user " + userId);
10630        }
10631        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10632            try {
10633                observer.onPackageDeleted(packageName,
10634                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10635            } catch (RemoteException re) {
10636            }
10637            return;
10638        }
10639
10640        boolean uninstallBlocked = false;
10641        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10642            int[] users = sUserManager.getUserIds();
10643            for (int i = 0; i < users.length; ++i) {
10644                if (getBlockUninstallForUser(packageName, users[i])) {
10645                    uninstallBlocked = true;
10646                    break;
10647                }
10648            }
10649        } else {
10650            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10651        }
10652        if (uninstallBlocked) {
10653            try {
10654                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10655                        null);
10656            } catch (RemoteException re) {
10657            }
10658            return;
10659        }
10660
10661        if (DEBUG_REMOVE) {
10662            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10663        }
10664        // Queue up an async operation since the package deletion may take a little while.
10665        mHandler.post(new Runnable() {
10666            public void run() {
10667                mHandler.removeCallbacks(this);
10668                final int returnCode = deletePackageX(packageName, userId, flags);
10669                if (observer != null) {
10670                    try {
10671                        observer.onPackageDeleted(packageName, returnCode, null);
10672                    } catch (RemoteException e) {
10673                        Log.i(TAG, "Observer no longer exists.");
10674                    } //end catch
10675                } //end if
10676            } //end run
10677        });
10678    }
10679
10680    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10681        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10682                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10683        try {
10684            if (dpm != null) {
10685                if (dpm.isDeviceOwner(packageName)) {
10686                    return true;
10687                }
10688                int[] users;
10689                if (userId == UserHandle.USER_ALL) {
10690                    users = sUserManager.getUserIds();
10691                } else {
10692                    users = new int[]{userId};
10693                }
10694                for (int i = 0; i < users.length; ++i) {
10695                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10696                        return true;
10697                    }
10698                }
10699            }
10700        } catch (RemoteException e) {
10701        }
10702        return false;
10703    }
10704
10705    /**
10706     *  This method is an internal method that could be get invoked either
10707     *  to delete an installed package or to clean up a failed installation.
10708     *  After deleting an installed package, a broadcast is sent to notify any
10709     *  listeners that the package has been installed. For cleaning up a failed
10710     *  installation, the broadcast is not necessary since the package's
10711     *  installation wouldn't have sent the initial broadcast either
10712     *  The key steps in deleting a package are
10713     *  deleting the package information in internal structures like mPackages,
10714     *  deleting the packages base directories through installd
10715     *  updating mSettings to reflect current status
10716     *  persisting settings for later use
10717     *  sending a broadcast if necessary
10718     */
10719    private int deletePackageX(String packageName, int userId, int flags) {
10720        final PackageRemovedInfo info = new PackageRemovedInfo();
10721        final boolean res;
10722
10723        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10724                ? UserHandle.ALL : new UserHandle(userId);
10725
10726        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10727            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10728            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10729        }
10730
10731        boolean removedForAllUsers = false;
10732        boolean systemUpdate = false;
10733
10734        // for the uninstall-updates case and restricted profiles, remember the per-
10735        // userhandle installed state
10736        int[] allUsers;
10737        boolean[] perUserInstalled;
10738        synchronized (mPackages) {
10739            PackageSetting ps = mSettings.mPackages.get(packageName);
10740            allUsers = sUserManager.getUserIds();
10741            perUserInstalled = new boolean[allUsers.length];
10742            for (int i = 0; i < allUsers.length; i++) {
10743                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10744            }
10745        }
10746
10747        synchronized (mInstallLock) {
10748            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10749            res = deletePackageLI(packageName, removeForUser,
10750                    true, allUsers, perUserInstalled,
10751                    flags | REMOVE_CHATTY, info, true);
10752            systemUpdate = info.isRemovedPackageSystemUpdate;
10753            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10754                removedForAllUsers = true;
10755            }
10756            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10757                    + " removedForAllUsers=" + removedForAllUsers);
10758        }
10759
10760        if (res) {
10761            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10762
10763            // If the removed package was a system update, the old system package
10764            // was re-enabled; we need to broadcast this information
10765            if (systemUpdate) {
10766                Bundle extras = new Bundle(1);
10767                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10768                        ? info.removedAppId : info.uid);
10769                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10770
10771                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10772                        extras, null, null, null);
10773                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10774                        extras, null, null, null);
10775                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10776                        null, packageName, null, null);
10777            }
10778        }
10779        // Force a gc here.
10780        Runtime.getRuntime().gc();
10781        // Delete the resources here after sending the broadcast to let
10782        // other processes clean up before deleting resources.
10783        if (info.args != null) {
10784            synchronized (mInstallLock) {
10785                info.args.doPostDeleteLI(true);
10786            }
10787        }
10788
10789        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10790    }
10791
10792    static class PackageRemovedInfo {
10793        String removedPackage;
10794        int uid = -1;
10795        int removedAppId = -1;
10796        int[] removedUsers = null;
10797        boolean isRemovedPackageSystemUpdate = false;
10798        // Clean up resources deleted packages.
10799        InstallArgs args = null;
10800
10801        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10802            Bundle extras = new Bundle(1);
10803            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10804            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10805            if (replacing) {
10806                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10807            }
10808            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10809            if (removedPackage != null) {
10810                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10811                        extras, null, null, removedUsers);
10812                if (fullRemove && !replacing) {
10813                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10814                            extras, null, null, removedUsers);
10815                }
10816            }
10817            if (removedAppId >= 0) {
10818                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10819                        removedUsers);
10820            }
10821        }
10822    }
10823
10824    /*
10825     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10826     * flag is not set, the data directory is removed as well.
10827     * make sure this flag is set for partially installed apps. If not its meaningless to
10828     * delete a partially installed application.
10829     */
10830    private void removePackageDataLI(PackageSetting ps,
10831            int[] allUserHandles, boolean[] perUserInstalled,
10832            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10833        String packageName = ps.name;
10834        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10835        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10836        // Retrieve object to delete permissions for shared user later on
10837        final PackageSetting deletedPs;
10838        // reader
10839        synchronized (mPackages) {
10840            deletedPs = mSettings.mPackages.get(packageName);
10841            if (outInfo != null) {
10842                outInfo.removedPackage = packageName;
10843                outInfo.removedUsers = deletedPs != null
10844                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10845                        : null;
10846            }
10847        }
10848        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10849            removeDataDirsLI(packageName);
10850            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10851        }
10852        // writer
10853        synchronized (mPackages) {
10854            if (deletedPs != null) {
10855                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10856                    if (outInfo != null) {
10857                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10858                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10859                    }
10860                    if (deletedPs != null) {
10861                        updatePermissionsLPw(deletedPs.name, null, 0);
10862                        if (deletedPs.sharedUser != null) {
10863                            // remove permissions associated with package
10864                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10865                        }
10866                    }
10867                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10868                }
10869                // make sure to preserve per-user disabled state if this removal was just
10870                // a downgrade of a system app to the factory package
10871                if (allUserHandles != null && perUserInstalled != null) {
10872                    if (DEBUG_REMOVE) {
10873                        Slog.d(TAG, "Propagating install state across downgrade");
10874                    }
10875                    for (int i = 0; i < allUserHandles.length; i++) {
10876                        if (DEBUG_REMOVE) {
10877                            Slog.d(TAG, "    user " + allUserHandles[i]
10878                                    + " => " + perUserInstalled[i]);
10879                        }
10880                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10881                    }
10882                }
10883            }
10884            // can downgrade to reader
10885            if (writeSettings) {
10886                // Save settings now
10887                mSettings.writeLPr();
10888            }
10889        }
10890        if (outInfo != null) {
10891            // A user ID was deleted here. Go through all users and remove it
10892            // from KeyStore.
10893            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10894        }
10895    }
10896
10897    static boolean locationIsPrivileged(File path) {
10898        try {
10899            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10900                    .getCanonicalPath();
10901            return path.getCanonicalPath().startsWith(privilegedAppDir);
10902        } catch (IOException e) {
10903            Slog.e(TAG, "Unable to access code path " + path);
10904        }
10905        return false;
10906    }
10907
10908    /*
10909     * Tries to delete system package.
10910     */
10911    private boolean deleteSystemPackageLI(PackageSetting newPs,
10912            int[] allUserHandles, boolean[] perUserInstalled,
10913            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10914        final boolean applyUserRestrictions
10915                = (allUserHandles != null) && (perUserInstalled != null);
10916        PackageSetting disabledPs = null;
10917        // Confirm if the system package has been updated
10918        // An updated system app can be deleted. This will also have to restore
10919        // the system pkg from system partition
10920        // reader
10921        synchronized (mPackages) {
10922            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10923        }
10924        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10925                + " disabledPs=" + disabledPs);
10926        if (disabledPs == null) {
10927            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10928            return false;
10929        } else if (DEBUG_REMOVE) {
10930            Slog.d(TAG, "Deleting system pkg from data partition");
10931        }
10932        if (DEBUG_REMOVE) {
10933            if (applyUserRestrictions) {
10934                Slog.d(TAG, "Remembering install states:");
10935                for (int i = 0; i < allUserHandles.length; i++) {
10936                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10937                }
10938            }
10939        }
10940        // Delete the updated package
10941        outInfo.isRemovedPackageSystemUpdate = true;
10942        if (disabledPs.versionCode < newPs.versionCode) {
10943            // Delete data for downgrades
10944            flags &= ~PackageManager.DELETE_KEEP_DATA;
10945        } else {
10946            // Preserve data by setting flag
10947            flags |= PackageManager.DELETE_KEEP_DATA;
10948        }
10949        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10950                allUserHandles, perUserInstalled, outInfo, writeSettings);
10951        if (!ret) {
10952            return false;
10953        }
10954        // writer
10955        synchronized (mPackages) {
10956            // Reinstate the old system package
10957            mSettings.enableSystemPackageLPw(newPs.name);
10958            // Remove any native libraries from the upgraded package.
10959            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10960        }
10961        // Install the system package
10962        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10963        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10964        if (locationIsPrivileged(disabledPs.codePath)) {
10965            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10966        }
10967
10968        final PackageParser.Package newPkg;
10969        try {
10970            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10971        } catch (PackageManagerException e) {
10972            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10973            return false;
10974        }
10975
10976        // writer
10977        synchronized (mPackages) {
10978            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10979            updatePermissionsLPw(newPkg.packageName, newPkg,
10980                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10981            if (applyUserRestrictions) {
10982                if (DEBUG_REMOVE) {
10983                    Slog.d(TAG, "Propagating install state across reinstall");
10984                }
10985                for (int i = 0; i < allUserHandles.length; i++) {
10986                    if (DEBUG_REMOVE) {
10987                        Slog.d(TAG, "    user " + allUserHandles[i]
10988                                + " => " + perUserInstalled[i]);
10989                    }
10990                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10991                }
10992                // Regardless of writeSettings we need to ensure that this restriction
10993                // state propagation is persisted
10994                mSettings.writeAllUsersPackageRestrictionsLPr();
10995            }
10996            // can downgrade to reader here
10997            if (writeSettings) {
10998                mSettings.writeLPr();
10999            }
11000        }
11001        return true;
11002    }
11003
11004    private boolean deleteInstalledPackageLI(PackageSetting ps,
11005            boolean deleteCodeAndResources, int flags,
11006            int[] allUserHandles, boolean[] perUserInstalled,
11007            PackageRemovedInfo outInfo, boolean writeSettings) {
11008        if (outInfo != null) {
11009            outInfo.uid = ps.appId;
11010        }
11011
11012        // Delete package data from internal structures and also remove data if flag is set
11013        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11014
11015        // Delete application code and resources
11016        if (deleteCodeAndResources && (outInfo != null)) {
11017            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11018                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11019                    getAppDexInstructionSets(ps));
11020            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11021        }
11022        return true;
11023    }
11024
11025    @Override
11026    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11027            int userId) {
11028        mContext.enforceCallingOrSelfPermission(
11029                android.Manifest.permission.DELETE_PACKAGES, null);
11030        synchronized (mPackages) {
11031            PackageSetting ps = mSettings.mPackages.get(packageName);
11032            if (ps == null) {
11033                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11034                return false;
11035            }
11036            if (!ps.getInstalled(userId)) {
11037                // Can't block uninstall for an app that is not installed or enabled.
11038                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11039                return false;
11040            }
11041            ps.setBlockUninstall(blockUninstall, userId);
11042            mSettings.writePackageRestrictionsLPr(userId);
11043        }
11044        return true;
11045    }
11046
11047    @Override
11048    public boolean getBlockUninstallForUser(String packageName, int userId) {
11049        synchronized (mPackages) {
11050            PackageSetting ps = mSettings.mPackages.get(packageName);
11051            if (ps == null) {
11052                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11053                return false;
11054            }
11055            return ps.getBlockUninstall(userId);
11056        }
11057    }
11058
11059    /*
11060     * This method handles package deletion in general
11061     */
11062    private boolean deletePackageLI(String packageName, UserHandle user,
11063            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11064            int flags, PackageRemovedInfo outInfo,
11065            boolean writeSettings) {
11066        if (packageName == null) {
11067            Slog.w(TAG, "Attempt to delete null packageName.");
11068            return false;
11069        }
11070        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11071        PackageSetting ps;
11072        boolean dataOnly = false;
11073        int removeUser = -1;
11074        int appId = -1;
11075        synchronized (mPackages) {
11076            ps = mSettings.mPackages.get(packageName);
11077            if (ps == null) {
11078                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11079                return false;
11080            }
11081            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11082                    && user.getIdentifier() != UserHandle.USER_ALL) {
11083                // The caller is asking that the package only be deleted for a single
11084                // user.  To do this, we just mark its uninstalled state and delete
11085                // its data.  If this is a system app, we only allow this to happen if
11086                // they have set the special DELETE_SYSTEM_APP which requests different
11087                // semantics than normal for uninstalling system apps.
11088                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11089                ps.setUserState(user.getIdentifier(),
11090                        COMPONENT_ENABLED_STATE_DEFAULT,
11091                        false, //installed
11092                        true,  //stopped
11093                        true,  //notLaunched
11094                        false, //hidden
11095                        null, null, null,
11096                        false // blockUninstall
11097                        );
11098                if (!isSystemApp(ps)) {
11099                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11100                        // Other user still have this package installed, so all
11101                        // we need to do is clear this user's data and save that
11102                        // it is uninstalled.
11103                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11104                        removeUser = user.getIdentifier();
11105                        appId = ps.appId;
11106                        mSettings.writePackageRestrictionsLPr(removeUser);
11107                    } else {
11108                        // We need to set it back to 'installed' so the uninstall
11109                        // broadcasts will be sent correctly.
11110                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11111                        ps.setInstalled(true, user.getIdentifier());
11112                    }
11113                } else {
11114                    // This is a system app, so we assume that the
11115                    // other users still have this package installed, so all
11116                    // we need to do is clear this user's data and save that
11117                    // it is uninstalled.
11118                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11119                    removeUser = user.getIdentifier();
11120                    appId = ps.appId;
11121                    mSettings.writePackageRestrictionsLPr(removeUser);
11122                }
11123            }
11124        }
11125
11126        if (removeUser >= 0) {
11127            // From above, we determined that we are deleting this only
11128            // for a single user.  Continue the work here.
11129            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11130            if (outInfo != null) {
11131                outInfo.removedPackage = packageName;
11132                outInfo.removedAppId = appId;
11133                outInfo.removedUsers = new int[] {removeUser};
11134            }
11135            mInstaller.clearUserData(packageName, removeUser);
11136            removeKeystoreDataIfNeeded(removeUser, appId);
11137            schedulePackageCleaning(packageName, removeUser, false);
11138            return true;
11139        }
11140
11141        if (dataOnly) {
11142            // Delete application data first
11143            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11144            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11145            return true;
11146        }
11147
11148        boolean ret = false;
11149        if (isSystemApp(ps)) {
11150            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11151            // When an updated system application is deleted we delete the existing resources as well and
11152            // fall back to existing code in system partition
11153            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11154                    flags, outInfo, writeSettings);
11155        } else {
11156            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11157            // Kill application pre-emptively especially for apps on sd.
11158            killApplication(packageName, ps.appId, "uninstall pkg");
11159            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11160                    allUserHandles, perUserInstalled,
11161                    outInfo, writeSettings);
11162        }
11163
11164        return ret;
11165    }
11166
11167    private final class ClearStorageConnection implements ServiceConnection {
11168        IMediaContainerService mContainerService;
11169
11170        @Override
11171        public void onServiceConnected(ComponentName name, IBinder service) {
11172            synchronized (this) {
11173                mContainerService = IMediaContainerService.Stub.asInterface(service);
11174                notifyAll();
11175            }
11176        }
11177
11178        @Override
11179        public void onServiceDisconnected(ComponentName name) {
11180        }
11181    }
11182
11183    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11184        final boolean mounted;
11185        if (Environment.isExternalStorageEmulated()) {
11186            mounted = true;
11187        } else {
11188            final String status = Environment.getExternalStorageState();
11189
11190            mounted = status.equals(Environment.MEDIA_MOUNTED)
11191                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11192        }
11193
11194        if (!mounted) {
11195            return;
11196        }
11197
11198        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11199        int[] users;
11200        if (userId == UserHandle.USER_ALL) {
11201            users = sUserManager.getUserIds();
11202        } else {
11203            users = new int[] { userId };
11204        }
11205        final ClearStorageConnection conn = new ClearStorageConnection();
11206        if (mContext.bindServiceAsUser(
11207                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11208            try {
11209                for (int curUser : users) {
11210                    long timeout = SystemClock.uptimeMillis() + 5000;
11211                    synchronized (conn) {
11212                        long now = SystemClock.uptimeMillis();
11213                        while (conn.mContainerService == null && now < timeout) {
11214                            try {
11215                                conn.wait(timeout - now);
11216                            } catch (InterruptedException e) {
11217                            }
11218                        }
11219                    }
11220                    if (conn.mContainerService == null) {
11221                        return;
11222                    }
11223
11224                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11225                    clearDirectory(conn.mContainerService,
11226                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11227                    if (allData) {
11228                        clearDirectory(conn.mContainerService,
11229                                userEnv.buildExternalStorageAppDataDirs(packageName));
11230                        clearDirectory(conn.mContainerService,
11231                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11232                    }
11233                }
11234            } finally {
11235                mContext.unbindService(conn);
11236            }
11237        }
11238    }
11239
11240    @Override
11241    public void clearApplicationUserData(final String packageName,
11242            final IPackageDataObserver observer, final int userId) {
11243        mContext.enforceCallingOrSelfPermission(
11244                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11245        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11246        // Queue up an async operation since the package deletion may take a little while.
11247        mHandler.post(new Runnable() {
11248            public void run() {
11249                mHandler.removeCallbacks(this);
11250                final boolean succeeded;
11251                synchronized (mInstallLock) {
11252                    succeeded = clearApplicationUserDataLI(packageName, userId);
11253                }
11254                clearExternalStorageDataSync(packageName, userId, true);
11255                if (succeeded) {
11256                    // invoke DeviceStorageMonitor's update method to clear any notifications
11257                    DeviceStorageMonitorInternal
11258                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11259                    if (dsm != null) {
11260                        dsm.checkMemory();
11261                    }
11262                }
11263                if(observer != null) {
11264                    try {
11265                        observer.onRemoveCompleted(packageName, succeeded);
11266                    } catch (RemoteException e) {
11267                        Log.i(TAG, "Observer no longer exists.");
11268                    }
11269                } //end if observer
11270            } //end run
11271        });
11272    }
11273
11274    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11275        if (packageName == null) {
11276            Slog.w(TAG, "Attempt to delete null packageName.");
11277            return false;
11278        }
11279
11280        // Try finding details about the requested package
11281        PackageParser.Package pkg;
11282        synchronized (mPackages) {
11283            pkg = mPackages.get(packageName);
11284            if (pkg == null) {
11285                final PackageSetting ps = mSettings.mPackages.get(packageName);
11286                if (ps != null) {
11287                    pkg = ps.pkg;
11288                }
11289            }
11290        }
11291
11292        if (pkg == null) {
11293            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11294        }
11295
11296        // Always delete data directories for package, even if we found no other
11297        // record of app. This helps users recover from UID mismatches without
11298        // resorting to a full data wipe.
11299        int retCode = mInstaller.clearUserData(packageName, userId);
11300        if (retCode < 0) {
11301            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11302            return false;
11303        }
11304
11305        if (pkg == null) {
11306            return false;
11307        }
11308
11309        if (pkg != null && pkg.applicationInfo != null) {
11310            final int appId = pkg.applicationInfo.uid;
11311            removeKeystoreDataIfNeeded(userId, appId);
11312        }
11313
11314        // Create a native library symlink only if we have native libraries
11315        // and if the native libraries are 32 bit libraries. We do not provide
11316        // this symlink for 64 bit libraries.
11317        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11318                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11319            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11320            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11321                Slog.w(TAG, "Failed linking native library dir");
11322                return false;
11323            }
11324        }
11325
11326        return true;
11327    }
11328
11329    /**
11330     * Remove entries from the keystore daemon. Will only remove it if the
11331     * {@code appId} is valid.
11332     */
11333    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11334        if (appId < 0) {
11335            return;
11336        }
11337
11338        final KeyStore keyStore = KeyStore.getInstance();
11339        if (keyStore != null) {
11340            if (userId == UserHandle.USER_ALL) {
11341                for (final int individual : sUserManager.getUserIds()) {
11342                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11343                }
11344            } else {
11345                keyStore.clearUid(UserHandle.getUid(userId, appId));
11346            }
11347        } else {
11348            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11349        }
11350    }
11351
11352    @Override
11353    public void deleteApplicationCacheFiles(final String packageName,
11354            final IPackageDataObserver observer) {
11355        mContext.enforceCallingOrSelfPermission(
11356                android.Manifest.permission.DELETE_CACHE_FILES, null);
11357        // Queue up an async operation since the package deletion may take a little while.
11358        final int userId = UserHandle.getCallingUserId();
11359        mHandler.post(new Runnable() {
11360            public void run() {
11361                mHandler.removeCallbacks(this);
11362                final boolean succeded;
11363                synchronized (mInstallLock) {
11364                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11365                }
11366                clearExternalStorageDataSync(packageName, userId, false);
11367                if(observer != null) {
11368                    try {
11369                        observer.onRemoveCompleted(packageName, succeded);
11370                    } catch (RemoteException e) {
11371                        Log.i(TAG, "Observer no longer exists.");
11372                    }
11373                } //end if observer
11374            } //end run
11375        });
11376    }
11377
11378    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11379        if (packageName == null) {
11380            Slog.w(TAG, "Attempt to delete null packageName.");
11381            return false;
11382        }
11383        PackageParser.Package p;
11384        synchronized (mPackages) {
11385            p = mPackages.get(packageName);
11386        }
11387        if (p == null) {
11388            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11389            return false;
11390        }
11391        final ApplicationInfo applicationInfo = p.applicationInfo;
11392        if (applicationInfo == null) {
11393            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11394            return false;
11395        }
11396        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11397        if (retCode < 0) {
11398            Slog.w(TAG, "Couldn't remove cache files for package: "
11399                       + packageName + " u" + userId);
11400            return false;
11401        }
11402        return true;
11403    }
11404
11405    @Override
11406    public void getPackageSizeInfo(final String packageName, int userHandle,
11407            final IPackageStatsObserver observer) {
11408        mContext.enforceCallingOrSelfPermission(
11409                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11410        if (packageName == null) {
11411            throw new IllegalArgumentException("Attempt to get size of null packageName");
11412        }
11413
11414        PackageStats stats = new PackageStats(packageName, userHandle);
11415
11416        /*
11417         * Queue up an async operation since the package measurement may take a
11418         * little while.
11419         */
11420        Message msg = mHandler.obtainMessage(INIT_COPY);
11421        msg.obj = new MeasureParams(stats, observer);
11422        mHandler.sendMessage(msg);
11423    }
11424
11425    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11426            PackageStats pStats) {
11427        if (packageName == null) {
11428            Slog.w(TAG, "Attempt to get size of null packageName.");
11429            return false;
11430        }
11431        PackageParser.Package p;
11432        boolean dataOnly = false;
11433        String libDirRoot = null;
11434        String asecPath = null;
11435        PackageSetting ps = null;
11436        synchronized (mPackages) {
11437            p = mPackages.get(packageName);
11438            ps = mSettings.mPackages.get(packageName);
11439            if(p == null) {
11440                dataOnly = true;
11441                if((ps == null) || (ps.pkg == null)) {
11442                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11443                    return false;
11444                }
11445                p = ps.pkg;
11446            }
11447            if (ps != null) {
11448                libDirRoot = ps.legacyNativeLibraryPathString;
11449            }
11450            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11451                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11452                if (secureContainerId != null) {
11453                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11454                }
11455            }
11456        }
11457        String publicSrcDir = null;
11458        if(!dataOnly) {
11459            final ApplicationInfo applicationInfo = p.applicationInfo;
11460            if (applicationInfo == null) {
11461                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11462                return false;
11463            }
11464            if (isForwardLocked(p)) {
11465                publicSrcDir = applicationInfo.getBaseResourcePath();
11466            }
11467        }
11468        // TODO: extend to measure size of split APKs
11469        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11470        // not just the first level.
11471        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11472        // just the primary.
11473        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11474        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11475                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11476        if (res < 0) {
11477            return false;
11478        }
11479
11480        // Fix-up for forward-locked applications in ASEC containers.
11481        if (!isExternal(p)) {
11482            pStats.codeSize += pStats.externalCodeSize;
11483            pStats.externalCodeSize = 0L;
11484        }
11485
11486        return true;
11487    }
11488
11489
11490    @Override
11491    public void addPackageToPreferred(String packageName) {
11492        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11493    }
11494
11495    @Override
11496    public void removePackageFromPreferred(String packageName) {
11497        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11498    }
11499
11500    @Override
11501    public List<PackageInfo> getPreferredPackages(int flags) {
11502        return new ArrayList<PackageInfo>();
11503    }
11504
11505    private int getUidTargetSdkVersionLockedLPr(int uid) {
11506        Object obj = mSettings.getUserIdLPr(uid);
11507        if (obj instanceof SharedUserSetting) {
11508            final SharedUserSetting sus = (SharedUserSetting) obj;
11509            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11510            final Iterator<PackageSetting> it = sus.packages.iterator();
11511            while (it.hasNext()) {
11512                final PackageSetting ps = it.next();
11513                if (ps.pkg != null) {
11514                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11515                    if (v < vers) vers = v;
11516                }
11517            }
11518            return vers;
11519        } else if (obj instanceof PackageSetting) {
11520            final PackageSetting ps = (PackageSetting) obj;
11521            if (ps.pkg != null) {
11522                return ps.pkg.applicationInfo.targetSdkVersion;
11523            }
11524        }
11525        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11526    }
11527
11528    @Override
11529    public void addPreferredActivity(IntentFilter filter, int match,
11530            ComponentName[] set, ComponentName activity, int userId) {
11531        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11532                "Adding preferred");
11533    }
11534
11535    private void addPreferredActivityInternal(IntentFilter filter, int match,
11536            ComponentName[] set, ComponentName activity, boolean always, int userId,
11537            String opname) {
11538        // writer
11539        int callingUid = Binder.getCallingUid();
11540        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11541        if (filter.countActions() == 0) {
11542            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11543            return;
11544        }
11545        synchronized (mPackages) {
11546            if (mContext.checkCallingOrSelfPermission(
11547                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11548                    != PackageManager.PERMISSION_GRANTED) {
11549                if (getUidTargetSdkVersionLockedLPr(callingUid)
11550                        < Build.VERSION_CODES.FROYO) {
11551                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11552                            + callingUid);
11553                    return;
11554                }
11555                mContext.enforceCallingOrSelfPermission(
11556                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11557            }
11558
11559            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11560            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11561                    + userId + ":");
11562            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11563            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11564            mSettings.writePackageRestrictionsLPr(userId);
11565        }
11566    }
11567
11568    @Override
11569    public void replacePreferredActivity(IntentFilter filter, int match,
11570            ComponentName[] set, ComponentName activity, int userId) {
11571        if (filter.countActions() != 1) {
11572            throw new IllegalArgumentException(
11573                    "replacePreferredActivity expects filter to have only 1 action.");
11574        }
11575        if (filter.countDataAuthorities() != 0
11576                || filter.countDataPaths() != 0
11577                || filter.countDataSchemes() > 1
11578                || filter.countDataTypes() != 0) {
11579            throw new IllegalArgumentException(
11580                    "replacePreferredActivity expects filter to have no data authorities, " +
11581                    "paths, or types; and at most one scheme.");
11582        }
11583
11584        final int callingUid = Binder.getCallingUid();
11585        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11586        synchronized (mPackages) {
11587            if (mContext.checkCallingOrSelfPermission(
11588                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11589                    != PackageManager.PERMISSION_GRANTED) {
11590                if (getUidTargetSdkVersionLockedLPr(callingUid)
11591                        < Build.VERSION_CODES.FROYO) {
11592                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11593                            + Binder.getCallingUid());
11594                    return;
11595                }
11596                mContext.enforceCallingOrSelfPermission(
11597                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11598            }
11599
11600            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11601            if (pir != null) {
11602                // Get all of the existing entries that exactly match this filter.
11603                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11604                if (existing != null && existing.size() == 1) {
11605                    PreferredActivity cur = existing.get(0);
11606                    if (DEBUG_PREFERRED) {
11607                        Slog.i(TAG, "Checking replace of preferred:");
11608                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11609                        if (!cur.mPref.mAlways) {
11610                            Slog.i(TAG, "  -- CUR; not mAlways!");
11611                        } else {
11612                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11613                            Slog.i(TAG, "  -- CUR: mSet="
11614                                    + Arrays.toString(cur.mPref.mSetComponents));
11615                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11616                            Slog.i(TAG, "  -- NEW: mMatch="
11617                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11618                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11619                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11620                        }
11621                    }
11622                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11623                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11624                            && cur.mPref.sameSet(set)) {
11625                        // Setting the preferred activity to what it happens to be already
11626                        if (DEBUG_PREFERRED) {
11627                            Slog.i(TAG, "Replacing with same preferred activity "
11628                                    + cur.mPref.mShortComponent + " for user "
11629                                    + userId + ":");
11630                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11631                        }
11632                        return;
11633                    }
11634                }
11635
11636                if (existing != null) {
11637                    if (DEBUG_PREFERRED) {
11638                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11639                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11640                    }
11641                    for (int i = 0; i < existing.size(); i++) {
11642                        PreferredActivity pa = existing.get(i);
11643                        if (DEBUG_PREFERRED) {
11644                            Slog.i(TAG, "Removing existing preferred activity "
11645                                    + pa.mPref.mComponent + ":");
11646                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11647                        }
11648                        pir.removeFilter(pa);
11649                    }
11650                }
11651            }
11652            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11653                    "Replacing preferred");
11654        }
11655    }
11656
11657    @Override
11658    public void clearPackagePreferredActivities(String packageName) {
11659        final int uid = Binder.getCallingUid();
11660        // writer
11661        synchronized (mPackages) {
11662            PackageParser.Package pkg = mPackages.get(packageName);
11663            if (pkg == null || pkg.applicationInfo.uid != uid) {
11664                if (mContext.checkCallingOrSelfPermission(
11665                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11666                        != PackageManager.PERMISSION_GRANTED) {
11667                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11668                            < Build.VERSION_CODES.FROYO) {
11669                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11670                                + Binder.getCallingUid());
11671                        return;
11672                    }
11673                    mContext.enforceCallingOrSelfPermission(
11674                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11675                }
11676            }
11677
11678            int user = UserHandle.getCallingUserId();
11679            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11680                mSettings.writePackageRestrictionsLPr(user);
11681                scheduleWriteSettingsLocked();
11682            }
11683        }
11684    }
11685
11686    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11687    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11688        ArrayList<PreferredActivity> removed = null;
11689        boolean changed = false;
11690        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11691            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11692            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11693            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11694                continue;
11695            }
11696            Iterator<PreferredActivity> it = pir.filterIterator();
11697            while (it.hasNext()) {
11698                PreferredActivity pa = it.next();
11699                // Mark entry for removal only if it matches the package name
11700                // and the entry is of type "always".
11701                if (packageName == null ||
11702                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11703                                && pa.mPref.mAlways)) {
11704                    if (removed == null) {
11705                        removed = new ArrayList<PreferredActivity>();
11706                    }
11707                    removed.add(pa);
11708                }
11709            }
11710            if (removed != null) {
11711                for (int j=0; j<removed.size(); j++) {
11712                    PreferredActivity pa = removed.get(j);
11713                    pir.removeFilter(pa);
11714                }
11715                changed = true;
11716            }
11717        }
11718        return changed;
11719    }
11720
11721    @Override
11722    public void resetPreferredActivities(int userId) {
11723        /* TODO: Actually use userId. Why is it being passed in? */
11724        mContext.enforceCallingOrSelfPermission(
11725                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11726        // writer
11727        synchronized (mPackages) {
11728            int user = UserHandle.getCallingUserId();
11729            clearPackagePreferredActivitiesLPw(null, user);
11730            mSettings.readDefaultPreferredAppsLPw(this, user);
11731            mSettings.writePackageRestrictionsLPr(user);
11732            scheduleWriteSettingsLocked();
11733        }
11734    }
11735
11736    @Override
11737    public int getPreferredActivities(List<IntentFilter> outFilters,
11738            List<ComponentName> outActivities, String packageName) {
11739
11740        int num = 0;
11741        final int userId = UserHandle.getCallingUserId();
11742        // reader
11743        synchronized (mPackages) {
11744            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11745            if (pir != null) {
11746                final Iterator<PreferredActivity> it = pir.filterIterator();
11747                while (it.hasNext()) {
11748                    final PreferredActivity pa = it.next();
11749                    if (packageName == null
11750                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11751                                    && pa.mPref.mAlways)) {
11752                        if (outFilters != null) {
11753                            outFilters.add(new IntentFilter(pa));
11754                        }
11755                        if (outActivities != null) {
11756                            outActivities.add(pa.mPref.mComponent);
11757                        }
11758                    }
11759                }
11760            }
11761        }
11762
11763        return num;
11764    }
11765
11766    @Override
11767    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11768            int userId) {
11769        int callingUid = Binder.getCallingUid();
11770        if (callingUid != Process.SYSTEM_UID) {
11771            throw new SecurityException(
11772                    "addPersistentPreferredActivity can only be run by the system");
11773        }
11774        if (filter.countActions() == 0) {
11775            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11776            return;
11777        }
11778        synchronized (mPackages) {
11779            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11780                    " :");
11781            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11782            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11783                    new PersistentPreferredActivity(filter, activity));
11784            mSettings.writePackageRestrictionsLPr(userId);
11785        }
11786    }
11787
11788    @Override
11789    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11790        int callingUid = Binder.getCallingUid();
11791        if (callingUid != Process.SYSTEM_UID) {
11792            throw new SecurityException(
11793                    "clearPackagePersistentPreferredActivities can only be run by the system");
11794        }
11795        ArrayList<PersistentPreferredActivity> removed = null;
11796        boolean changed = false;
11797        synchronized (mPackages) {
11798            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11799                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11800                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11801                        .valueAt(i);
11802                if (userId != thisUserId) {
11803                    continue;
11804                }
11805                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11806                while (it.hasNext()) {
11807                    PersistentPreferredActivity ppa = it.next();
11808                    // Mark entry for removal only if it matches the package name.
11809                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11810                        if (removed == null) {
11811                            removed = new ArrayList<PersistentPreferredActivity>();
11812                        }
11813                        removed.add(ppa);
11814                    }
11815                }
11816                if (removed != null) {
11817                    for (int j=0; j<removed.size(); j++) {
11818                        PersistentPreferredActivity ppa = removed.get(j);
11819                        ppir.removeFilter(ppa);
11820                    }
11821                    changed = true;
11822                }
11823            }
11824
11825            if (changed) {
11826                mSettings.writePackageRestrictionsLPr(userId);
11827            }
11828        }
11829    }
11830
11831    @Override
11832    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11833            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11834        mContext.enforceCallingOrSelfPermission(
11835                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11836        int callingUid = Binder.getCallingUid();
11837        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11838        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11839        if (intentFilter.countActions() == 0) {
11840            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11841            return;
11842        }
11843        synchronized (mPackages) {
11844            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11845                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11846            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11847            mSettings.writePackageRestrictionsLPr(sourceUserId);
11848        }
11849    }
11850
11851    @Override
11852    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11853            int ownerUserId) {
11854        mContext.enforceCallingOrSelfPermission(
11855                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11856        int callingUid = Binder.getCallingUid();
11857        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11858        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11859        int callingUserId = UserHandle.getUserId(callingUid);
11860        synchronized (mPackages) {
11861            CrossProfileIntentResolver resolver =
11862                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11863            HashSet<CrossProfileIntentFilter> set =
11864                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11865            for (CrossProfileIntentFilter filter : set) {
11866                if (filter.getOwnerPackage().equals(ownerPackage)
11867                        && filter.getOwnerUserId() == callingUserId) {
11868                    resolver.removeFilter(filter);
11869                }
11870            }
11871            mSettings.writePackageRestrictionsLPr(sourceUserId);
11872        }
11873    }
11874
11875    // Enforcing that callingUid is owning pkg on userId
11876    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11877        // The system owns everything.
11878        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11879            return;
11880        }
11881        int callingUserId = UserHandle.getUserId(callingUid);
11882        if (callingUserId != userId) {
11883            throw new SecurityException("calling uid " + callingUid
11884                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11885                    + callingUserId);
11886        }
11887        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11888        if (pi == null) {
11889            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11890                    + callingUserId);
11891        }
11892        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11893            throw new SecurityException("Calling uid " + callingUid
11894                    + " does not own package " + pkg);
11895        }
11896    }
11897
11898    @Override
11899    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11900        Intent intent = new Intent(Intent.ACTION_MAIN);
11901        intent.addCategory(Intent.CATEGORY_HOME);
11902
11903        final int callingUserId = UserHandle.getCallingUserId();
11904        List<ResolveInfo> list = queryIntentActivities(intent, null,
11905                PackageManager.GET_META_DATA, callingUserId);
11906        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11907                true, false, false, callingUserId);
11908
11909        allHomeCandidates.clear();
11910        if (list != null) {
11911            for (ResolveInfo ri : list) {
11912                allHomeCandidates.add(ri);
11913            }
11914        }
11915        return (preferred == null || preferred.activityInfo == null)
11916                ? null
11917                : new ComponentName(preferred.activityInfo.packageName,
11918                        preferred.activityInfo.name);
11919    }
11920
11921    @Override
11922    public void setApplicationEnabledSetting(String appPackageName,
11923            int newState, int flags, int userId, String callingPackage) {
11924        if (!sUserManager.exists(userId)) return;
11925        if (callingPackage == null) {
11926            callingPackage = Integer.toString(Binder.getCallingUid());
11927        }
11928        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11929    }
11930
11931    @Override
11932    public void setComponentEnabledSetting(ComponentName componentName,
11933            int newState, int flags, int userId) {
11934        if (!sUserManager.exists(userId)) return;
11935        setEnabledSetting(componentName.getPackageName(),
11936                componentName.getClassName(), newState, flags, userId, null);
11937    }
11938
11939    private void setEnabledSetting(final String packageName, String className, int newState,
11940            final int flags, int userId, String callingPackage) {
11941        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11942              || newState == COMPONENT_ENABLED_STATE_ENABLED
11943              || newState == COMPONENT_ENABLED_STATE_DISABLED
11944              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11945              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11946            throw new IllegalArgumentException("Invalid new component state: "
11947                    + newState);
11948        }
11949        PackageSetting pkgSetting;
11950        final int uid = Binder.getCallingUid();
11951        final int permission = mContext.checkCallingOrSelfPermission(
11952                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11953        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11954        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11955        boolean sendNow = false;
11956        boolean isApp = (className == null);
11957        String componentName = isApp ? packageName : className;
11958        int packageUid = -1;
11959        ArrayList<String> components;
11960
11961        // writer
11962        synchronized (mPackages) {
11963            pkgSetting = mSettings.mPackages.get(packageName);
11964            if (pkgSetting == null) {
11965                if (className == null) {
11966                    throw new IllegalArgumentException(
11967                            "Unknown package: " + packageName);
11968                }
11969                throw new IllegalArgumentException(
11970                        "Unknown component: " + packageName
11971                        + "/" + className);
11972            }
11973            // Allow root and verify that userId is not being specified by a different user
11974            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11975                throw new SecurityException(
11976                        "Permission Denial: attempt to change component state from pid="
11977                        + Binder.getCallingPid()
11978                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11979            }
11980            if (className == null) {
11981                // We're dealing with an application/package level state change
11982                if (pkgSetting.getEnabled(userId) == newState) {
11983                    // Nothing to do
11984                    return;
11985                }
11986                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11987                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11988                    // Don't care about who enables an app.
11989                    callingPackage = null;
11990                }
11991                pkgSetting.setEnabled(newState, userId, callingPackage);
11992                // pkgSetting.pkg.mSetEnabled = newState;
11993            } else {
11994                // We're dealing with a component level state change
11995                // First, verify that this is a valid class name.
11996                PackageParser.Package pkg = pkgSetting.pkg;
11997                if (pkg == null || !pkg.hasComponentClassName(className)) {
11998                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11999                        throw new IllegalArgumentException("Component class " + className
12000                                + " does not exist in " + packageName);
12001                    } else {
12002                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12003                                + className + " does not exist in " + packageName);
12004                    }
12005                }
12006                switch (newState) {
12007                case COMPONENT_ENABLED_STATE_ENABLED:
12008                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12009                        return;
12010                    }
12011                    break;
12012                case COMPONENT_ENABLED_STATE_DISABLED:
12013                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12014                        return;
12015                    }
12016                    break;
12017                case COMPONENT_ENABLED_STATE_DEFAULT:
12018                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12019                        return;
12020                    }
12021                    break;
12022                default:
12023                    Slog.e(TAG, "Invalid new component state: " + newState);
12024                    return;
12025                }
12026            }
12027            mSettings.writePackageRestrictionsLPr(userId);
12028            components = mPendingBroadcasts.get(userId, packageName);
12029            final boolean newPackage = components == null;
12030            if (newPackage) {
12031                components = new ArrayList<String>();
12032            }
12033            if (!components.contains(componentName)) {
12034                components.add(componentName);
12035            }
12036            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12037                sendNow = true;
12038                // Purge entry from pending broadcast list if another one exists already
12039                // since we are sending one right away.
12040                mPendingBroadcasts.remove(userId, packageName);
12041            } else {
12042                if (newPackage) {
12043                    mPendingBroadcasts.put(userId, packageName, components);
12044                }
12045                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12046                    // Schedule a message
12047                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12048                }
12049            }
12050        }
12051
12052        long callingId = Binder.clearCallingIdentity();
12053        try {
12054            if (sendNow) {
12055                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12056                sendPackageChangedBroadcast(packageName,
12057                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12058            }
12059        } finally {
12060            Binder.restoreCallingIdentity(callingId);
12061        }
12062    }
12063
12064    private void sendPackageChangedBroadcast(String packageName,
12065            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12066        if (DEBUG_INSTALL)
12067            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12068                    + componentNames);
12069        Bundle extras = new Bundle(4);
12070        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12071        String nameList[] = new String[componentNames.size()];
12072        componentNames.toArray(nameList);
12073        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12074        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12075        extras.putInt(Intent.EXTRA_UID, packageUid);
12076        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12077                new int[] {UserHandle.getUserId(packageUid)});
12078    }
12079
12080    @Override
12081    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12082        if (!sUserManager.exists(userId)) return;
12083        final int uid = Binder.getCallingUid();
12084        final int permission = mContext.checkCallingOrSelfPermission(
12085                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12086        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12087        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12088        // writer
12089        synchronized (mPackages) {
12090            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12091                    uid, userId)) {
12092                scheduleWritePackageRestrictionsLocked(userId);
12093            }
12094        }
12095    }
12096
12097    @Override
12098    public String getInstallerPackageName(String packageName) {
12099        // reader
12100        synchronized (mPackages) {
12101            return mSettings.getInstallerPackageNameLPr(packageName);
12102        }
12103    }
12104
12105    @Override
12106    public int getApplicationEnabledSetting(String packageName, int userId) {
12107        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12108        int uid = Binder.getCallingUid();
12109        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12110        // reader
12111        synchronized (mPackages) {
12112            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12113        }
12114    }
12115
12116    @Override
12117    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12118        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12119        int uid = Binder.getCallingUid();
12120        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12121        // reader
12122        synchronized (mPackages) {
12123            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12124        }
12125    }
12126
12127    @Override
12128    public void enterSafeMode() {
12129        enforceSystemOrRoot("Only the system can request entering safe mode");
12130
12131        if (!mSystemReady) {
12132            mSafeMode = true;
12133        }
12134    }
12135
12136    @Override
12137    public void systemReady() {
12138        mSystemReady = true;
12139
12140        // Read the compatibilty setting when the system is ready.
12141        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12142                mContext.getContentResolver(),
12143                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12144        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12145        if (DEBUG_SETTINGS) {
12146            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12147        }
12148
12149        synchronized (mPackages) {
12150            // Verify that all of the preferred activity components actually
12151            // exist.  It is possible for applications to be updated and at
12152            // that point remove a previously declared activity component that
12153            // had been set as a preferred activity.  We try to clean this up
12154            // the next time we encounter that preferred activity, but it is
12155            // possible for the user flow to never be able to return to that
12156            // situation so here we do a sanity check to make sure we haven't
12157            // left any junk around.
12158            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12159            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12160                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12161                removed.clear();
12162                for (PreferredActivity pa : pir.filterSet()) {
12163                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12164                        removed.add(pa);
12165                    }
12166                }
12167                if (removed.size() > 0) {
12168                    for (int r=0; r<removed.size(); r++) {
12169                        PreferredActivity pa = removed.get(r);
12170                        Slog.w(TAG, "Removing dangling preferred activity: "
12171                                + pa.mPref.mComponent);
12172                        pir.removeFilter(pa);
12173                    }
12174                    mSettings.writePackageRestrictionsLPr(
12175                            mSettings.mPreferredActivities.keyAt(i));
12176                }
12177            }
12178        }
12179        sUserManager.systemReady();
12180
12181        // Kick off any messages waiting for system ready
12182        if (mPostSystemReadyMessages != null) {
12183            for (Message msg : mPostSystemReadyMessages) {
12184                msg.sendToTarget();
12185            }
12186            mPostSystemReadyMessages = null;
12187        }
12188    }
12189
12190    @Override
12191    public boolean isSafeMode() {
12192        return mSafeMode;
12193    }
12194
12195    @Override
12196    public boolean hasSystemUidErrors() {
12197        return mHasSystemUidErrors;
12198    }
12199
12200    static String arrayToString(int[] array) {
12201        StringBuffer buf = new StringBuffer(128);
12202        buf.append('[');
12203        if (array != null) {
12204            for (int i=0; i<array.length; i++) {
12205                if (i > 0) buf.append(", ");
12206                buf.append(array[i]);
12207            }
12208        }
12209        buf.append(']');
12210        return buf.toString();
12211    }
12212
12213    static class DumpState {
12214        public static final int DUMP_LIBS = 1 << 0;
12215        public static final int DUMP_FEATURES = 1 << 1;
12216        public static final int DUMP_RESOLVERS = 1 << 2;
12217        public static final int DUMP_PERMISSIONS = 1 << 3;
12218        public static final int DUMP_PACKAGES = 1 << 4;
12219        public static final int DUMP_SHARED_USERS = 1 << 5;
12220        public static final int DUMP_MESSAGES = 1 << 6;
12221        public static final int DUMP_PROVIDERS = 1 << 7;
12222        public static final int DUMP_VERIFIERS = 1 << 8;
12223        public static final int DUMP_PREFERRED = 1 << 9;
12224        public static final int DUMP_PREFERRED_XML = 1 << 10;
12225        public static final int DUMP_KEYSETS = 1 << 11;
12226        public static final int DUMP_VERSION = 1 << 12;
12227        public static final int DUMP_INSTALLS = 1 << 13;
12228
12229        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12230
12231        private int mTypes;
12232
12233        private int mOptions;
12234
12235        private boolean mTitlePrinted;
12236
12237        private SharedUserSetting mSharedUser;
12238
12239        public boolean isDumping(int type) {
12240            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12241                return true;
12242            }
12243
12244            return (mTypes & type) != 0;
12245        }
12246
12247        public void setDump(int type) {
12248            mTypes |= type;
12249        }
12250
12251        public boolean isOptionEnabled(int option) {
12252            return (mOptions & option) != 0;
12253        }
12254
12255        public void setOptionEnabled(int option) {
12256            mOptions |= option;
12257        }
12258
12259        public boolean onTitlePrinted() {
12260            final boolean printed = mTitlePrinted;
12261            mTitlePrinted = true;
12262            return printed;
12263        }
12264
12265        public boolean getTitlePrinted() {
12266            return mTitlePrinted;
12267        }
12268
12269        public void setTitlePrinted(boolean enabled) {
12270            mTitlePrinted = enabled;
12271        }
12272
12273        public SharedUserSetting getSharedUser() {
12274            return mSharedUser;
12275        }
12276
12277        public void setSharedUser(SharedUserSetting user) {
12278            mSharedUser = user;
12279        }
12280    }
12281
12282    @Override
12283    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12284        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12285                != PackageManager.PERMISSION_GRANTED) {
12286            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12287                    + Binder.getCallingPid()
12288                    + ", uid=" + Binder.getCallingUid()
12289                    + " without permission "
12290                    + android.Manifest.permission.DUMP);
12291            return;
12292        }
12293
12294        DumpState dumpState = new DumpState();
12295        boolean fullPreferred = false;
12296        boolean checkin = false;
12297
12298        String packageName = null;
12299
12300        int opti = 0;
12301        while (opti < args.length) {
12302            String opt = args[opti];
12303            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12304                break;
12305            }
12306            opti++;
12307
12308            if ("-a".equals(opt)) {
12309                // Right now we only know how to print all.
12310            } else if ("-h".equals(opt)) {
12311                pw.println("Package manager dump options:");
12312                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12313                pw.println("    --checkin: dump for a checkin");
12314                pw.println("    -f: print details of intent filters");
12315                pw.println("    -h: print this help");
12316                pw.println("  cmd may be one of:");
12317                pw.println("    l[ibraries]: list known shared libraries");
12318                pw.println("    f[ibraries]: list device features");
12319                pw.println("    k[eysets]: print known keysets");
12320                pw.println("    r[esolvers]: dump intent resolvers");
12321                pw.println("    perm[issions]: dump permissions");
12322                pw.println("    pref[erred]: print preferred package settings");
12323                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12324                pw.println("    prov[iders]: dump content providers");
12325                pw.println("    p[ackages]: dump installed packages");
12326                pw.println("    s[hared-users]: dump shared user IDs");
12327                pw.println("    m[essages]: print collected runtime messages");
12328                pw.println("    v[erifiers]: print package verifier info");
12329                pw.println("    version: print database version info");
12330                pw.println("    write: write current settings now");
12331                pw.println("    <package.name>: info about given package");
12332                pw.println("    installs: details about install sessions");
12333                return;
12334            } else if ("--checkin".equals(opt)) {
12335                checkin = true;
12336            } else if ("-f".equals(opt)) {
12337                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12338            } else {
12339                pw.println("Unknown argument: " + opt + "; use -h for help");
12340            }
12341        }
12342
12343        // Is the caller requesting to dump a particular piece of data?
12344        if (opti < args.length) {
12345            String cmd = args[opti];
12346            opti++;
12347            // Is this a package name?
12348            if ("android".equals(cmd) || cmd.contains(".")) {
12349                packageName = cmd;
12350                // When dumping a single package, we always dump all of its
12351                // filter information since the amount of data will be reasonable.
12352                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12353            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12354                dumpState.setDump(DumpState.DUMP_LIBS);
12355            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12356                dumpState.setDump(DumpState.DUMP_FEATURES);
12357            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12358                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12359            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12360                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12361            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12362                dumpState.setDump(DumpState.DUMP_PREFERRED);
12363            } else if ("preferred-xml".equals(cmd)) {
12364                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12365                if (opti < args.length && "--full".equals(args[opti])) {
12366                    fullPreferred = true;
12367                    opti++;
12368                }
12369            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12370                dumpState.setDump(DumpState.DUMP_PACKAGES);
12371            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12372                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12373            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12374                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12375            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12376                dumpState.setDump(DumpState.DUMP_MESSAGES);
12377            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12378                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12379            } else if ("version".equals(cmd)) {
12380                dumpState.setDump(DumpState.DUMP_VERSION);
12381            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12382                dumpState.setDump(DumpState.DUMP_KEYSETS);
12383            } else if ("installs".equals(cmd)) {
12384                dumpState.setDump(DumpState.DUMP_INSTALLS);
12385            } else if ("write".equals(cmd)) {
12386                synchronized (mPackages) {
12387                    mSettings.writeLPr();
12388                    pw.println("Settings written.");
12389                    return;
12390                }
12391            }
12392        }
12393
12394        if (checkin) {
12395            pw.println("vers,1");
12396        }
12397
12398        // reader
12399        synchronized (mPackages) {
12400            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12401                if (!checkin) {
12402                    if (dumpState.onTitlePrinted())
12403                        pw.println();
12404                    pw.println("Database versions:");
12405                    pw.print("  SDK Version:");
12406                    pw.print(" internal=");
12407                    pw.print(mSettings.mInternalSdkPlatform);
12408                    pw.print(" external=");
12409                    pw.println(mSettings.mExternalSdkPlatform);
12410                    pw.print("  DB Version:");
12411                    pw.print(" internal=");
12412                    pw.print(mSettings.mInternalDatabaseVersion);
12413                    pw.print(" external=");
12414                    pw.println(mSettings.mExternalDatabaseVersion);
12415                }
12416            }
12417
12418            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12419                if (!checkin) {
12420                    if (dumpState.onTitlePrinted())
12421                        pw.println();
12422                    pw.println("Verifiers:");
12423                    pw.print("  Required: ");
12424                    pw.print(mRequiredVerifierPackage);
12425                    pw.print(" (uid=");
12426                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12427                    pw.println(")");
12428                } else if (mRequiredVerifierPackage != null) {
12429                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12430                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12431                }
12432            }
12433
12434            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12435                boolean printedHeader = false;
12436                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12437                while (it.hasNext()) {
12438                    String name = it.next();
12439                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12440                    if (!checkin) {
12441                        if (!printedHeader) {
12442                            if (dumpState.onTitlePrinted())
12443                                pw.println();
12444                            pw.println("Libraries:");
12445                            printedHeader = true;
12446                        }
12447                        pw.print("  ");
12448                    } else {
12449                        pw.print("lib,");
12450                    }
12451                    pw.print(name);
12452                    if (!checkin) {
12453                        pw.print(" -> ");
12454                    }
12455                    if (ent.path != null) {
12456                        if (!checkin) {
12457                            pw.print("(jar) ");
12458                            pw.print(ent.path);
12459                        } else {
12460                            pw.print(",jar,");
12461                            pw.print(ent.path);
12462                        }
12463                    } else {
12464                        if (!checkin) {
12465                            pw.print("(apk) ");
12466                            pw.print(ent.apk);
12467                        } else {
12468                            pw.print(",apk,");
12469                            pw.print(ent.apk);
12470                        }
12471                    }
12472                    pw.println();
12473                }
12474            }
12475
12476            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12477                if (dumpState.onTitlePrinted())
12478                    pw.println();
12479                if (!checkin) {
12480                    pw.println("Features:");
12481                }
12482                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12483                while (it.hasNext()) {
12484                    String name = it.next();
12485                    if (!checkin) {
12486                        pw.print("  ");
12487                    } else {
12488                        pw.print("feat,");
12489                    }
12490                    pw.println(name);
12491                }
12492            }
12493
12494            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12495                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12496                        : "Activity Resolver Table:", "  ", packageName,
12497                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12498                    dumpState.setTitlePrinted(true);
12499                }
12500                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12501                        : "Receiver Resolver Table:", "  ", packageName,
12502                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12503                    dumpState.setTitlePrinted(true);
12504                }
12505                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12506                        : "Service Resolver Table:", "  ", packageName,
12507                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12508                    dumpState.setTitlePrinted(true);
12509                }
12510                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12511                        : "Provider Resolver Table:", "  ", packageName,
12512                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12513                    dumpState.setTitlePrinted(true);
12514                }
12515            }
12516
12517            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12518                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12519                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12520                    int user = mSettings.mPreferredActivities.keyAt(i);
12521                    if (pir.dump(pw,
12522                            dumpState.getTitlePrinted()
12523                                ? "\nPreferred Activities User " + user + ":"
12524                                : "Preferred Activities User " + user + ":", "  ",
12525                            packageName, true)) {
12526                        dumpState.setTitlePrinted(true);
12527                    }
12528                }
12529            }
12530
12531            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12532                pw.flush();
12533                FileOutputStream fout = new FileOutputStream(fd);
12534                BufferedOutputStream str = new BufferedOutputStream(fout);
12535                XmlSerializer serializer = new FastXmlSerializer();
12536                try {
12537                    serializer.setOutput(str, "utf-8");
12538                    serializer.startDocument(null, true);
12539                    serializer.setFeature(
12540                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12541                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12542                    serializer.endDocument();
12543                    serializer.flush();
12544                } catch (IllegalArgumentException e) {
12545                    pw.println("Failed writing: " + e);
12546                } catch (IllegalStateException e) {
12547                    pw.println("Failed writing: " + e);
12548                } catch (IOException e) {
12549                    pw.println("Failed writing: " + e);
12550                }
12551            }
12552
12553            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12554                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12555                if (packageName == null) {
12556                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12557                        if (iperm == 0) {
12558                            if (dumpState.onTitlePrinted())
12559                                pw.println();
12560                            pw.println("AppOp Permissions:");
12561                        }
12562                        pw.print("  AppOp Permission ");
12563                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12564                        pw.println(":");
12565                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12566                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12567                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12568                        }
12569                    }
12570                }
12571            }
12572
12573            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12574                boolean printedSomething = false;
12575                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12576                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12577                        continue;
12578                    }
12579                    if (!printedSomething) {
12580                        if (dumpState.onTitlePrinted())
12581                            pw.println();
12582                        pw.println("Registered ContentProviders:");
12583                        printedSomething = true;
12584                    }
12585                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12586                    pw.print("    "); pw.println(p.toString());
12587                }
12588                printedSomething = false;
12589                for (Map.Entry<String, PackageParser.Provider> entry :
12590                        mProvidersByAuthority.entrySet()) {
12591                    PackageParser.Provider p = entry.getValue();
12592                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12593                        continue;
12594                    }
12595                    if (!printedSomething) {
12596                        if (dumpState.onTitlePrinted())
12597                            pw.println();
12598                        pw.println("ContentProvider Authorities:");
12599                        printedSomething = true;
12600                    }
12601                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12602                    pw.print("    "); pw.println(p.toString());
12603                    if (p.info != null && p.info.applicationInfo != null) {
12604                        final String appInfo = p.info.applicationInfo.toString();
12605                        pw.print("      applicationInfo="); pw.println(appInfo);
12606                    }
12607                }
12608            }
12609
12610            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12611                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12612            }
12613
12614            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12615                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12616            }
12617
12618            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12619                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12620            }
12621
12622            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12623                // XXX should handle packageName != null by dumping only install data that
12624                // the given package is involved with.
12625                if (dumpState.onTitlePrinted()) pw.println();
12626                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12627            }
12628
12629            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12630                if (dumpState.onTitlePrinted()) pw.println();
12631                mSettings.dumpReadMessagesLPr(pw, dumpState);
12632
12633                pw.println();
12634                pw.println("Package warning messages:");
12635                final File fname = getSettingsProblemFile();
12636                FileInputStream in = null;
12637                try {
12638                    in = new FileInputStream(fname);
12639                    final int avail = in.available();
12640                    final byte[] data = new byte[avail];
12641                    in.read(data);
12642                    pw.print(new String(data));
12643                } catch (FileNotFoundException e) {
12644                } catch (IOException e) {
12645                } finally {
12646                    if (in != null) {
12647                        try {
12648                            in.close();
12649                        } catch (IOException e) {
12650                        }
12651                    }
12652                }
12653            }
12654
12655            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12656                BufferedReader in = null;
12657                String line = null;
12658                try {
12659                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12660                    while ((line = in.readLine()) != null) {
12661                        pw.print("msg,");
12662                        pw.println(line);
12663                    }
12664                } catch (IOException ignored) {
12665                } finally {
12666                    IoUtils.closeQuietly(in);
12667                }
12668            }
12669        }
12670    }
12671
12672    // ------- apps on sdcard specific code -------
12673    static final boolean DEBUG_SD_INSTALL = false;
12674
12675    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12676
12677    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12678
12679    private boolean mMediaMounted = false;
12680
12681    static String getEncryptKey() {
12682        try {
12683            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12684                    SD_ENCRYPTION_KEYSTORE_NAME);
12685            if (sdEncKey == null) {
12686                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12687                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12688                if (sdEncKey == null) {
12689                    Slog.e(TAG, "Failed to create encryption keys");
12690                    return null;
12691                }
12692            }
12693            return sdEncKey;
12694        } catch (NoSuchAlgorithmException nsae) {
12695            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12696            return null;
12697        } catch (IOException ioe) {
12698            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12699            return null;
12700        }
12701    }
12702
12703    /*
12704     * Update media status on PackageManager.
12705     */
12706    @Override
12707    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12708        int callingUid = Binder.getCallingUid();
12709        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12710            throw new SecurityException("Media status can only be updated by the system");
12711        }
12712        // reader; this apparently protects mMediaMounted, but should probably
12713        // be a different lock in that case.
12714        synchronized (mPackages) {
12715            Log.i(TAG, "Updating external media status from "
12716                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12717                    + (mediaStatus ? "mounted" : "unmounted"));
12718            if (DEBUG_SD_INSTALL)
12719                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12720                        + ", mMediaMounted=" + mMediaMounted);
12721            if (mediaStatus == mMediaMounted) {
12722                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12723                        : 0, -1);
12724                mHandler.sendMessage(msg);
12725                return;
12726            }
12727            mMediaMounted = mediaStatus;
12728        }
12729        // Queue up an async operation since the package installation may take a
12730        // little while.
12731        mHandler.post(new Runnable() {
12732            public void run() {
12733                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12734            }
12735        });
12736    }
12737
12738    /**
12739     * Called by MountService when the initial ASECs to scan are available.
12740     * Should block until all the ASEC containers are finished being scanned.
12741     */
12742    public void scanAvailableAsecs() {
12743        updateExternalMediaStatusInner(true, false, false);
12744        if (mShouldRestoreconData) {
12745            SELinuxMMAC.setRestoreconDone();
12746            mShouldRestoreconData = false;
12747        }
12748    }
12749
12750    /*
12751     * Collect information of applications on external media, map them against
12752     * existing containers and update information based on current mount status.
12753     * Please note that we always have to report status if reportStatus has been
12754     * set to true especially when unloading packages.
12755     */
12756    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12757            boolean externalStorage) {
12758        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12759        int[] uidArr = EmptyArray.INT;
12760
12761        final String[] list = PackageHelper.getSecureContainerList();
12762        if (ArrayUtils.isEmpty(list)) {
12763            Log.i(TAG, "No secure containers found");
12764        } else {
12765            // Process list of secure containers and categorize them
12766            // as active or stale based on their package internal state.
12767
12768            // reader
12769            synchronized (mPackages) {
12770                for (String cid : list) {
12771                    // Leave stages untouched for now; installer service owns them
12772                    if (PackageInstallerService.isStageName(cid)) continue;
12773
12774                    if (DEBUG_SD_INSTALL)
12775                        Log.i(TAG, "Processing container " + cid);
12776                    String pkgName = getAsecPackageName(cid);
12777                    if (pkgName == null) {
12778                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12779                        continue;
12780                    }
12781                    if (DEBUG_SD_INSTALL)
12782                        Log.i(TAG, "Looking for pkg : " + pkgName);
12783
12784                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12785                    if (ps == null) {
12786                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12787                        continue;
12788                    }
12789
12790                    /*
12791                     * Skip packages that are not external if we're unmounting
12792                     * external storage.
12793                     */
12794                    if (externalStorage && !isMounted && !isExternal(ps)) {
12795                        continue;
12796                    }
12797
12798                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12799                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12800                    // The package status is changed only if the code path
12801                    // matches between settings and the container id.
12802                    if (ps.codePathString != null
12803                            && ps.codePathString.startsWith(args.getCodePath())) {
12804                        if (DEBUG_SD_INSTALL) {
12805                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12806                                    + " at code path: " + ps.codePathString);
12807                        }
12808
12809                        // We do have a valid package installed on sdcard
12810                        processCids.put(args, ps.codePathString);
12811                        final int uid = ps.appId;
12812                        if (uid != -1) {
12813                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12814                        }
12815                    } else {
12816                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12817                                + ps.codePathString);
12818                    }
12819                }
12820            }
12821
12822            Arrays.sort(uidArr);
12823        }
12824
12825        // Process packages with valid entries.
12826        if (isMounted) {
12827            if (DEBUG_SD_INSTALL)
12828                Log.i(TAG, "Loading packages");
12829            loadMediaPackages(processCids, uidArr);
12830            startCleaningPackages();
12831            mInstallerService.onSecureContainersAvailable();
12832        } else {
12833            if (DEBUG_SD_INSTALL)
12834                Log.i(TAG, "Unloading packages");
12835            unloadMediaPackages(processCids, uidArr, reportStatus);
12836        }
12837    }
12838
12839    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12840            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12841        int size = pkgList.size();
12842        if (size > 0) {
12843            // Send broadcasts here
12844            Bundle extras = new Bundle();
12845            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12846                    .toArray(new String[size]));
12847            if (uidArr != null) {
12848                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12849            }
12850            if (replacing) {
12851                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12852            }
12853            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12854                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12855            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12856        }
12857    }
12858
12859   /*
12860     * Look at potentially valid container ids from processCids If package
12861     * information doesn't match the one on record or package scanning fails,
12862     * the cid is added to list of removeCids. We currently don't delete stale
12863     * containers.
12864     */
12865    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12866        ArrayList<String> pkgList = new ArrayList<String>();
12867        Set<AsecInstallArgs> keys = processCids.keySet();
12868
12869        for (AsecInstallArgs args : keys) {
12870            String codePath = processCids.get(args);
12871            if (DEBUG_SD_INSTALL)
12872                Log.i(TAG, "Loading container : " + args.cid);
12873            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12874            try {
12875                // Make sure there are no container errors first.
12876                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12877                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12878                            + " when installing from sdcard");
12879                    continue;
12880                }
12881                // Check code path here.
12882                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12883                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12884                            + " does not match one in settings " + codePath);
12885                    continue;
12886                }
12887                // Parse package
12888                int parseFlags = mDefParseFlags;
12889                if (args.isExternal()) {
12890                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12891                }
12892                if (args.isFwdLocked()) {
12893                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12894                }
12895
12896                synchronized (mInstallLock) {
12897                    PackageParser.Package pkg = null;
12898                    try {
12899                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12900                    } catch (PackageManagerException e) {
12901                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12902                    }
12903                    // Scan the package
12904                    if (pkg != null) {
12905                        /*
12906                         * TODO why is the lock being held? doPostInstall is
12907                         * called in other places without the lock. This needs
12908                         * to be straightened out.
12909                         */
12910                        // writer
12911                        synchronized (mPackages) {
12912                            retCode = PackageManager.INSTALL_SUCCEEDED;
12913                            pkgList.add(pkg.packageName);
12914                            // Post process args
12915                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12916                                    pkg.applicationInfo.uid);
12917                        }
12918                    } else {
12919                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12920                    }
12921                }
12922
12923            } finally {
12924                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12925                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12926                }
12927            }
12928        }
12929        // writer
12930        synchronized (mPackages) {
12931            // If the platform SDK has changed since the last time we booted,
12932            // we need to re-grant app permission to catch any new ones that
12933            // appear. This is really a hack, and means that apps can in some
12934            // cases get permissions that the user didn't initially explicitly
12935            // allow... it would be nice to have some better way to handle
12936            // this situation.
12937            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12938            if (regrantPermissions)
12939                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12940                        + mSdkVersion + "; regranting permissions for external storage");
12941            mSettings.mExternalSdkPlatform = mSdkVersion;
12942
12943            // Make sure group IDs have been assigned, and any permission
12944            // changes in other apps are accounted for
12945            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12946                    | (regrantPermissions
12947                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12948                            : 0));
12949
12950            mSettings.updateExternalDatabaseVersion();
12951
12952            // can downgrade to reader
12953            // Persist settings
12954            mSettings.writeLPr();
12955        }
12956        // Send a broadcast to let everyone know we are done processing
12957        if (pkgList.size() > 0) {
12958            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12959        }
12960    }
12961
12962   /*
12963     * Utility method to unload a list of specified containers
12964     */
12965    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12966        // Just unmount all valid containers.
12967        for (AsecInstallArgs arg : cidArgs) {
12968            synchronized (mInstallLock) {
12969                arg.doPostDeleteLI(false);
12970           }
12971       }
12972   }
12973
12974    /*
12975     * Unload packages mounted on external media. This involves deleting package
12976     * data from internal structures, sending broadcasts about diabled packages,
12977     * gc'ing to free up references, unmounting all secure containers
12978     * corresponding to packages on external media, and posting a
12979     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12980     * that we always have to post this message if status has been requested no
12981     * matter what.
12982     */
12983    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12984            final boolean reportStatus) {
12985        if (DEBUG_SD_INSTALL)
12986            Log.i(TAG, "unloading media packages");
12987        ArrayList<String> pkgList = new ArrayList<String>();
12988        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12989        final Set<AsecInstallArgs> keys = processCids.keySet();
12990        for (AsecInstallArgs args : keys) {
12991            String pkgName = args.getPackageName();
12992            if (DEBUG_SD_INSTALL)
12993                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12994            // Delete package internally
12995            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12996            synchronized (mInstallLock) {
12997                boolean res = deletePackageLI(pkgName, null, false, null, null,
12998                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12999                if (res) {
13000                    pkgList.add(pkgName);
13001                } else {
13002                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13003                    failedList.add(args);
13004                }
13005            }
13006        }
13007
13008        // reader
13009        synchronized (mPackages) {
13010            // We didn't update the settings after removing each package;
13011            // write them now for all packages.
13012            mSettings.writeLPr();
13013        }
13014
13015        // We have to absolutely send UPDATED_MEDIA_STATUS only
13016        // after confirming that all the receivers processed the ordered
13017        // broadcast when packages get disabled, force a gc to clean things up.
13018        // and unload all the containers.
13019        if (pkgList.size() > 0) {
13020            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13021                    new IIntentReceiver.Stub() {
13022                public void performReceive(Intent intent, int resultCode, String data,
13023                        Bundle extras, boolean ordered, boolean sticky,
13024                        int sendingUser) throws RemoteException {
13025                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13026                            reportStatus ? 1 : 0, 1, keys);
13027                    mHandler.sendMessage(msg);
13028                }
13029            });
13030        } else {
13031            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13032                    keys);
13033            mHandler.sendMessage(msg);
13034        }
13035    }
13036
13037    /** Binder call */
13038    @Override
13039    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13040            final int flags) {
13041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13042        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13043        int returnCode = PackageManager.MOVE_SUCCEEDED;
13044        int currInstallFlags = 0;
13045        int newInstallFlags = 0;
13046
13047        File codeFile = null;
13048        String installerPackageName = null;
13049        String packageAbiOverride = null;
13050
13051        // reader
13052        synchronized (mPackages) {
13053            final PackageParser.Package pkg = mPackages.get(packageName);
13054            final PackageSetting ps = mSettings.mPackages.get(packageName);
13055            if (pkg == null || ps == null) {
13056                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13057            } else {
13058                // Disable moving fwd locked apps and system packages
13059                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13060                    Slog.w(TAG, "Cannot move system application");
13061                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13062                } else if (pkg.mOperationPending) {
13063                    Slog.w(TAG, "Attempt to move package which has pending operations");
13064                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13065                } else {
13066                    // Find install location first
13067                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13068                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13069                        Slog.w(TAG, "Ambigous flags specified for move location.");
13070                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13071                    } else {
13072                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13073                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13074                        currInstallFlags = isExternal(pkg)
13075                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13076
13077                        if (newInstallFlags == currInstallFlags) {
13078                            Slog.w(TAG, "No move required. Trying to move to same location");
13079                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13080                        } else {
13081                            if (isForwardLocked(pkg)) {
13082                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13083                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13084                            }
13085                        }
13086                    }
13087                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13088                        pkg.mOperationPending = true;
13089                    }
13090                }
13091
13092                codeFile = new File(pkg.codePath);
13093                installerPackageName = ps.installerPackageName;
13094                packageAbiOverride = ps.cpuAbiOverrideString;
13095            }
13096        }
13097
13098        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13099            try {
13100                observer.packageMoved(packageName, returnCode);
13101            } catch (RemoteException ignored) {
13102            }
13103            return;
13104        }
13105
13106        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13107            @Override
13108            public void onUserActionRequired(Intent intent) throws RemoteException {
13109                throw new IllegalStateException();
13110            }
13111
13112            @Override
13113            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13114                    Bundle extras) throws RemoteException {
13115                Slog.d(TAG, "Install result for move: "
13116                        + PackageManager.installStatusToString(returnCode, msg));
13117
13118                // We usually have a new package now after the install, but if
13119                // we failed we need to clear the pending flag on the original
13120                // package object.
13121                synchronized (mPackages) {
13122                    final PackageParser.Package pkg = mPackages.get(packageName);
13123                    if (pkg != null) {
13124                        pkg.mOperationPending = false;
13125                    }
13126                }
13127
13128                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13129                switch (status) {
13130                    case PackageInstaller.STATUS_SUCCESS:
13131                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13132                        break;
13133                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13134                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13135                        break;
13136                    default:
13137                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13138                        break;
13139                }
13140            }
13141        };
13142
13143        // Treat a move like reinstalling an existing app, which ensures that we
13144        // process everythign uniformly, like unpacking native libraries.
13145        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13146
13147        final Message msg = mHandler.obtainMessage(INIT_COPY);
13148        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13149        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13150                installerPackageName, null, user, packageAbiOverride);
13151        mHandler.sendMessage(msg);
13152    }
13153
13154    @Override
13155    public boolean setInstallLocation(int loc) {
13156        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13157                null);
13158        if (getInstallLocation() == loc) {
13159            return true;
13160        }
13161        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13162                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13163            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13164                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13165            return true;
13166        }
13167        return false;
13168   }
13169
13170    @Override
13171    public int getInstallLocation() {
13172        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13173                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13174                PackageHelper.APP_INSTALL_AUTO);
13175    }
13176
13177    /** Called by UserManagerService */
13178    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13179        mDirtyUsers.remove(userHandle);
13180        mSettings.removeUserLPw(userHandle);
13181        mPendingBroadcasts.remove(userHandle);
13182        if (mInstaller != null) {
13183            // Technically, we shouldn't be doing this with the package lock
13184            // held.  However, this is very rare, and there is already so much
13185            // other disk I/O going on, that we'll let it slide for now.
13186            mInstaller.removeUserDataDirs(userHandle);
13187        }
13188        mUserNeedsBadging.delete(userHandle);
13189        removeUnusedPackagesLILPw(userManager, userHandle);
13190    }
13191
13192    /**
13193     * We're removing userHandle and would like to remove any downloaded packages
13194     * that are no longer in use by any other user.
13195     * @param userHandle the user being removed
13196     */
13197    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13198        final boolean DEBUG_CLEAN_APKS = false;
13199        int [] users = userManager.getUserIdsLPr();
13200        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13201        while (psit.hasNext()) {
13202            PackageSetting ps = psit.next();
13203            if (ps.pkg == null) {
13204                continue;
13205            }
13206            final String packageName = ps.pkg.packageName;
13207            // Skip over if system app
13208            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13209                continue;
13210            }
13211            if (DEBUG_CLEAN_APKS) {
13212                Slog.i(TAG, "Checking package " + packageName);
13213            }
13214            boolean keep = false;
13215            for (int i = 0; i < users.length; i++) {
13216                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13217                    keep = true;
13218                    if (DEBUG_CLEAN_APKS) {
13219                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13220                                + users[i]);
13221                    }
13222                    break;
13223                }
13224            }
13225            if (!keep) {
13226                if (DEBUG_CLEAN_APKS) {
13227                    Slog.i(TAG, "  Removing package " + packageName);
13228                }
13229                mHandler.post(new Runnable() {
13230                    public void run() {
13231                        deletePackageX(packageName, userHandle, 0);
13232                    } //end run
13233                });
13234            }
13235        }
13236    }
13237
13238    /** Called by UserManagerService */
13239    void createNewUserLILPw(int userHandle, File path) {
13240        if (mInstaller != null) {
13241            mInstaller.createUserConfig(userHandle);
13242            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13243        }
13244    }
13245
13246    @Override
13247    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13248        mContext.enforceCallingOrSelfPermission(
13249                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13250                "Only package verification agents can read the verifier device identity");
13251
13252        synchronized (mPackages) {
13253            return mSettings.getVerifierDeviceIdentityLPw();
13254        }
13255    }
13256
13257    @Override
13258    public void setPermissionEnforced(String permission, boolean enforced) {
13259        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13260        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13261            synchronized (mPackages) {
13262                if (mSettings.mReadExternalStorageEnforced == null
13263                        || mSettings.mReadExternalStorageEnforced != enforced) {
13264                    mSettings.mReadExternalStorageEnforced = enforced;
13265                    mSettings.writeLPr();
13266                }
13267            }
13268            // kill any non-foreground processes so we restart them and
13269            // grant/revoke the GID.
13270            final IActivityManager am = ActivityManagerNative.getDefault();
13271            if (am != null) {
13272                final long token = Binder.clearCallingIdentity();
13273                try {
13274                    am.killProcessesBelowForeground("setPermissionEnforcement");
13275                } catch (RemoteException e) {
13276                } finally {
13277                    Binder.restoreCallingIdentity(token);
13278                }
13279            }
13280        } else {
13281            throw new IllegalArgumentException("No selective enforcement for " + permission);
13282        }
13283    }
13284
13285    @Override
13286    @Deprecated
13287    public boolean isPermissionEnforced(String permission) {
13288        return true;
13289    }
13290
13291    @Override
13292    public boolean isStorageLow() {
13293        final long token = Binder.clearCallingIdentity();
13294        try {
13295            final DeviceStorageMonitorInternal
13296                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13297            if (dsm != null) {
13298                return dsm.isMemoryLow();
13299            } else {
13300                return false;
13301            }
13302        } finally {
13303            Binder.restoreCallingIdentity(token);
13304        }
13305    }
13306
13307    @Override
13308    public IPackageInstaller getPackageInstaller() {
13309        return mInstallerService;
13310    }
13311
13312    private boolean userNeedsBadging(int userId) {
13313        int index = mUserNeedsBadging.indexOfKey(userId);
13314        if (index < 0) {
13315            final UserInfo userInfo;
13316            final long token = Binder.clearCallingIdentity();
13317            try {
13318                userInfo = sUserManager.getUserInfo(userId);
13319            } finally {
13320                Binder.restoreCallingIdentity(token);
13321            }
13322            final boolean b;
13323            if (userInfo != null && userInfo.isManagedProfile()) {
13324                b = true;
13325            } else {
13326                b = false;
13327            }
13328            mUserNeedsBadging.put(userId, b);
13329            return b;
13330        }
13331        return mUserNeedsBadging.valueAt(index);
13332    }
13333
13334    @Override
13335    public KeySet getKeySetByAlias(String packageName, String alias) {
13336        if (packageName == null || alias == null) {
13337            return null;
13338        }
13339        synchronized(mPackages) {
13340            final PackageParser.Package pkg = mPackages.get(packageName);
13341            if (pkg == null) {
13342                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13343                throw new IllegalArgumentException("Unknown package: " + packageName);
13344            }
13345            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13346            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13347        }
13348    }
13349
13350    @Override
13351    public KeySet getSigningKeySet(String packageName) {
13352        if (packageName == null) {
13353            return null;
13354        }
13355        synchronized(mPackages) {
13356            final PackageParser.Package pkg = mPackages.get(packageName);
13357            if (pkg == null) {
13358                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13359                throw new IllegalArgumentException("Unknown package: " + packageName);
13360            }
13361            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13362                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13363                throw new SecurityException("May not access signing KeySet of other apps.");
13364            }
13365            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13366            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13367        }
13368    }
13369
13370    @Override
13371    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13372        if (packageName == null || ks == null) {
13373            return false;
13374        }
13375        synchronized(mPackages) {
13376            final PackageParser.Package pkg = mPackages.get(packageName);
13377            if (pkg == null) {
13378                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13379                throw new IllegalArgumentException("Unknown package: " + packageName);
13380            }
13381            IBinder ksh = ks.getToken();
13382            if (ksh instanceof KeySetHandle) {
13383                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13384                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13385            }
13386            return false;
13387        }
13388    }
13389
13390    @Override
13391    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13392        if (packageName == null || ks == null) {
13393            return false;
13394        }
13395        synchronized(mPackages) {
13396            final PackageParser.Package pkg = mPackages.get(packageName);
13397            if (pkg == null) {
13398                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13399                throw new IllegalArgumentException("Unknown package: " + packageName);
13400            }
13401            IBinder ksh = ks.getToken();
13402            if (ksh instanceof KeySetHandle) {
13403                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13404                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13405            }
13406            return false;
13407        }
13408    }
13409}
13410