PackageManagerService.java revision 9f837a99d48c5bb8ad7fbc133943e5bf622ce065
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.Iterator;
203import java.util.List;
204import java.util.Map;
205import java.util.Objects;
206import java.util.Set;
207import java.util.concurrent.atomic.AtomicBoolean;
208import java.util.concurrent.atomic.AtomicLong;
209
210import dalvik.system.DexFile;
211import dalvik.system.StaleDexCacheError;
212import dalvik.system.VMRuntime;
213
214import libcore.io.IoUtils;
215import libcore.util.EmptyArray;
216
217/**
218 * Keep track of all those .apks everywhere.
219 *
220 * This is very central to the platform's security; please run the unit
221 * tests whenever making modifications here:
222 *
223mmm frameworks/base/tests/AndroidTests
224adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
225adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
226 *
227 * {@hide}
228 */
229public class PackageManagerService extends IPackageManager.Stub {
230    static final String TAG = "PackageManager";
231    static final boolean DEBUG_SETTINGS = false;
232    static final boolean DEBUG_PREFERRED = false;
233    static final boolean DEBUG_UPGRADE = false;
234    private static final boolean DEBUG_INSTALL = false;
235    private static final boolean DEBUG_REMOVE = false;
236    private static final boolean DEBUG_BROADCASTS = false;
237    private static final boolean DEBUG_SHOW_INFO = false;
238    private static final boolean DEBUG_PACKAGE_INFO = false;
239    private static final boolean DEBUG_INTENT_MATCHING = false;
240    private static final boolean DEBUG_PACKAGE_SCANNING = false;
241    private static final boolean DEBUG_VERIFY = false;
242    private static final boolean DEBUG_DEXOPT = false;
243    private static final boolean DEBUG_ABI_SELECTION = false;
244
245    private static final int RADIO_UID = Process.PHONE_UID;
246    private static final int LOG_UID = Process.LOG_UID;
247    private static final int NFC_UID = Process.NFC_UID;
248    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
249    private static final int SHELL_UID = Process.SHELL_UID;
250
251    // Cap the size of permission trees that 3rd party apps can define
252    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
253
254    // Suffix used during package installation when copying/moving
255    // package apks to install directory.
256    private static final String INSTALL_PACKAGE_SUFFIX = "-";
257
258    static final int SCAN_NO_DEX = 1<<1;
259    static final int SCAN_FORCE_DEX = 1<<2;
260    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
261    static final int SCAN_NEW_INSTALL = 1<<4;
262    static final int SCAN_NO_PATHS = 1<<5;
263    static final int SCAN_UPDATE_TIME = 1<<6;
264    static final int SCAN_DEFER_DEX = 1<<7;
265    static final int SCAN_BOOTING = 1<<8;
266    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
267    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
268    static final int SCAN_REPLACING = 1<<11;
269
270    static final int REMOVE_CHATTY = 1<<16;
271
272    /**
273     * Timeout (in milliseconds) after which the watchdog should declare that
274     * our handler thread is wedged.  The usual default for such things is one
275     * minute but we sometimes do very lengthy I/O operations on this thread,
276     * such as installing multi-gigabyte applications, so ours needs to be longer.
277     */
278    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
279
280    /**
281     * Whether verification is enabled by default.
282     */
283    private static final boolean DEFAULT_VERIFY_ENABLE = true;
284
285    /**
286     * The default maximum time to wait for the verification agent to return in
287     * milliseconds.
288     */
289    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
290
291    /**
292     * The default response for package verification timeout.
293     *
294     * This can be either PackageManager.VERIFICATION_ALLOW or
295     * PackageManager.VERIFICATION_REJECT.
296     */
297    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
298
299    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
300
301    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
302            DEFAULT_CONTAINER_PACKAGE,
303            "com.android.defcontainer.DefaultContainerService");
304
305    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
306
307    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
308
309    private static String sPreferredInstructionSet;
310
311    final ServiceThread mHandlerThread;
312
313    private static final String IDMAP_PREFIX = "/data/resource-cache/";
314    private static final String IDMAP_SUFFIX = "@idmap";
315
316    final PackageHandler mHandler;
317
318    /**
319     * Messages for {@link #mHandler} that need to wait for system ready before
320     * being dispatched.
321     */
322    private ArrayList<Message> mPostSystemReadyMessages;
323
324    final int mSdkVersion = Build.VERSION.SDK_INT;
325
326    final Context mContext;
327    final boolean mFactoryTest;
328    final boolean mOnlyCore;
329    final boolean mLazyDexOpt;
330    final DisplayMetrics mMetrics;
331    final int mDefParseFlags;
332    final String[] mSeparateProcesses;
333
334    // This is where all application persistent data goes.
335    final File mAppDataDir;
336
337    // This is where all application persistent data goes for secondary users.
338    final File mUserAppDataDir;
339
340    /** The location for ASEC container files on internal storage. */
341    final String mAsecInternalPath;
342
343    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
344    // LOCK HELD.  Can be called with mInstallLock held.
345    final Installer mInstaller;
346
347    /** Directory where installed third-party apps stored */
348    final File mAppInstallDir;
349
350    /**
351     * Directory to which applications installed internally have their
352     * 32 bit native libraries copied.
353     */
354    private File mAppLib32InstallDir;
355
356    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
357    // apps.
358    final File mDrmAppPrivateInstallDir;
359
360    // ----------------------------------------------------------------
361
362    // Lock for state used when installing and doing other long running
363    // operations.  Methods that must be called with this lock held have
364    // the suffix "LI".
365    final Object mInstallLock = new Object();
366
367    // ----------------------------------------------------------------
368
369    // Keys are String (package name), values are Package.  This also serves
370    // as the lock for the global state.  Methods that must be called with
371    // this lock held have the prefix "LP".
372    final ArrayMap<String, PackageParser.Package> mPackages =
373            new ArrayMap<String, PackageParser.Package>();
374
375    // Tracks available target package names -> overlay package paths.
376    final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays =
377        new ArrayMap<String, ArrayMap<String, PackageParser.Package>>();
378
379    final Settings mSettings;
380    boolean mRestoredSettings;
381
382    // System configuration read by SystemConfig.
383    final int[] mGlobalGids;
384    final SparseArray<ArraySet<String>> mSystemPermissions;
385    final ArrayMap<String, FeatureInfo> mAvailableFeatures;
386
387    // If mac_permissions.xml was found for seinfo labeling.
388    boolean mFoundPolicyFile;
389
390    // If a recursive restorecon of /data/data/<pkg> is needed.
391    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
392
393    public static final class SharedLibraryEntry {
394        public final String path;
395        public final String apk;
396
397        SharedLibraryEntry(String _path, String _apk) {
398            path = _path;
399            apk = _apk;
400        }
401    }
402
403    // Currently known shared libraries.
404    final ArrayMap<String, SharedLibraryEntry> mSharedLibraries =
405            new ArrayMap<String, SharedLibraryEntry>();
406
407    // All available activities, for your resolving pleasure.
408    final ActivityIntentResolver mActivities =
409            new ActivityIntentResolver();
410
411    // All available receivers, for your resolving pleasure.
412    final ActivityIntentResolver mReceivers =
413            new ActivityIntentResolver();
414
415    // All available services, for your resolving pleasure.
416    final ServiceIntentResolver mServices = new ServiceIntentResolver();
417
418    // All available providers, for your resolving pleasure.
419    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
420
421    // Mapping from provider base names (first directory in content URI codePath)
422    // to the provider information.
423    final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority =
424            new ArrayMap<String, PackageParser.Provider>();
425
426    // Mapping from instrumentation class names to info about them.
427    final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
428            new ArrayMap<ComponentName, PackageParser.Instrumentation>();
429
430    // Mapping from permission names to info about them.
431    final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups =
432            new ArrayMap<String, PackageParser.PermissionGroup>();
433
434    // Packages whose data we have transfered into another package, thus
435    // should no longer exist.
436    final ArraySet<String> mTransferedPackages = new ArraySet<String>();
437
438    // Broadcast actions that are only available to the system.
439    final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>();
440
441    /** List of packages waiting for verification. */
442    final SparseArray<PackageVerificationState> mPendingVerification
443            = new SparseArray<PackageVerificationState>();
444
445    /** Set of packages associated with each app op permission. */
446    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
447
448    final PackageInstallerService mInstallerService;
449
450    ArraySet<PackageParser.Package> mDeferredDexOpt = null;
451
452    // Cache of users who need badging.
453    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
454
455    /** Token for keys in mPendingVerification. */
456    private int mPendingVerificationToken = 0;
457
458    volatile boolean mSystemReady;
459    volatile boolean mSafeMode;
460    volatile boolean mHasSystemUidErrors;
461
462    ApplicationInfo mAndroidApplication;
463    final ActivityInfo mResolveActivity = new ActivityInfo();
464    final ResolveInfo mResolveInfo = new ResolveInfo();
465    ComponentName mResolveComponentName;
466    PackageParser.Package mPlatformPackage;
467    ComponentName mCustomResolverComponentName;
468
469    boolean mResolverReplaced = false;
470
471    // Set of pending broadcasts for aggregating enable/disable of components.
472    static class PendingPackageBroadcasts {
473        // for each user id, a map of <package name -> components within that package>
474        final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap;
475
476        public PendingPackageBroadcasts() {
477            mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2);
478        }
479
480        public ArrayList<String> get(int userId, String packageName) {
481            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
482            return packages.get(packageName);
483        }
484
485        public void put(int userId, String packageName, ArrayList<String> components) {
486            ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId);
487            packages.put(packageName, components);
488        }
489
490        public void remove(int userId, String packageName) {
491            ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId);
492            if (packages != null) {
493                packages.remove(packageName);
494            }
495        }
496
497        public void remove(int userId) {
498            mUidMap.remove(userId);
499        }
500
501        public int userIdCount() {
502            return mUidMap.size();
503        }
504
505        public int userIdAt(int n) {
506            return mUidMap.keyAt(n);
507        }
508
509        public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) {
510            return mUidMap.get(userId);
511        }
512
513        public int size() {
514            // total number of pending broadcast entries across all userIds
515            int num = 0;
516            for (int i = 0; i< mUidMap.size(); i++) {
517                num += mUidMap.valueAt(i).size();
518            }
519            return num;
520        }
521
522        public void clear() {
523            mUidMap.clear();
524        }
525
526        private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) {
527            ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId);
528            if (map == null) {
529                map = new ArrayMap<String, ArrayList<String>>();
530                mUidMap.put(userId, map);
531            }
532            return map;
533        }
534    }
535    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
536
537    // Service Connection to remote media container service to copy
538    // package uri's from external media onto secure containers
539    // or internal storage.
540    private IMediaContainerService mContainerService = null;
541
542    static final int SEND_PENDING_BROADCAST = 1;
543    static final int MCS_BOUND = 3;
544    static final int END_COPY = 4;
545    static final int INIT_COPY = 5;
546    static final int MCS_UNBIND = 6;
547    static final int START_CLEANING_PACKAGE = 7;
548    static final int FIND_INSTALL_LOC = 8;
549    static final int POST_INSTALL = 9;
550    static final int MCS_RECONNECT = 10;
551    static final int MCS_GIVE_UP = 11;
552    static final int UPDATED_MEDIA_STATUS = 12;
553    static final int WRITE_SETTINGS = 13;
554    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
555    static final int PACKAGE_VERIFIED = 15;
556    static final int CHECK_PENDING_VERIFICATION = 16;
557
558    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
559
560    // Delay time in millisecs
561    static final int BROADCAST_DELAY = 10 * 1000;
562
563    static UserManagerService sUserManager;
564
565    // Stores a list of users whose package restrictions file needs to be updated
566    private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>();
567
568    final private DefaultContainerConnection mDefContainerConn =
569            new DefaultContainerConnection();
570    class DefaultContainerConnection implements ServiceConnection {
571        public void onServiceConnected(ComponentName name, IBinder service) {
572            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
573            IMediaContainerService imcs =
574                IMediaContainerService.Stub.asInterface(service);
575            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
576        }
577
578        public void onServiceDisconnected(ComponentName name) {
579            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
580        }
581    };
582
583    // Recordkeeping of restore-after-install operations that are currently in flight
584    // between the Package Manager and the Backup Manager
585    class PostInstallData {
586        public InstallArgs args;
587        public PackageInstalledInfo res;
588
589        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
590            args = _a;
591            res = _r;
592        }
593    };
594    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
595    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
596
597    private final String mRequiredVerifierPackage;
598
599    private final PackageUsage mPackageUsage = new PackageUsage();
600
601    private class PackageUsage {
602        private static final int WRITE_INTERVAL
603            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
604
605        private final Object mFileLock = new Object();
606        private final AtomicLong mLastWritten = new AtomicLong(0);
607        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
608
609        private boolean mIsHistoricalPackageUsageAvailable = true;
610
611        boolean isHistoricalPackageUsageAvailable() {
612            return mIsHistoricalPackageUsageAvailable;
613        }
614
615        void write(boolean force) {
616            if (force) {
617                writeInternal();
618                return;
619            }
620            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
621                && !DEBUG_DEXOPT) {
622                return;
623            }
624            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
625                new Thread("PackageUsage_DiskWriter") {
626                    @Override
627                    public void run() {
628                        try {
629                            writeInternal();
630                        } finally {
631                            mBackgroundWriteRunning.set(false);
632                        }
633                    }
634                }.start();
635            }
636        }
637
638        private void writeInternal() {
639            synchronized (mPackages) {
640                synchronized (mFileLock) {
641                    AtomicFile file = getFile();
642                    FileOutputStream f = null;
643                    try {
644                        f = file.startWrite();
645                        BufferedOutputStream out = new BufferedOutputStream(f);
646                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
647                        StringBuilder sb = new StringBuilder();
648                        for (PackageParser.Package pkg : mPackages.values()) {
649                            if (pkg.mLastPackageUsageTimeInMills == 0) {
650                                continue;
651                            }
652                            sb.setLength(0);
653                            sb.append(pkg.packageName);
654                            sb.append(' ');
655                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
656                            sb.append('\n');
657                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
658                        }
659                        out.flush();
660                        file.finishWrite(f);
661                    } catch (IOException e) {
662                        if (f != null) {
663                            file.failWrite(f);
664                        }
665                        Log.e(TAG, "Failed to write package usage times", e);
666                    }
667                }
668            }
669            mLastWritten.set(SystemClock.elapsedRealtime());
670        }
671
672        void readLP() {
673            synchronized (mFileLock) {
674                AtomicFile file = getFile();
675                BufferedInputStream in = null;
676                try {
677                    in = new BufferedInputStream(file.openRead());
678                    StringBuffer sb = new StringBuffer();
679                    while (true) {
680                        String packageName = readToken(in, sb, ' ');
681                        if (packageName == null) {
682                            break;
683                        }
684                        String timeInMillisString = readToken(in, sb, '\n');
685                        if (timeInMillisString == null) {
686                            throw new IOException("Failed to find last usage time for package "
687                                                  + packageName);
688                        }
689                        PackageParser.Package pkg = mPackages.get(packageName);
690                        if (pkg == null) {
691                            continue;
692                        }
693                        long timeInMillis;
694                        try {
695                            timeInMillis = Long.parseLong(timeInMillisString.toString());
696                        } catch (NumberFormatException e) {
697                            throw new IOException("Failed to parse " + timeInMillisString
698                                                  + " as a long.", e);
699                        }
700                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
701                    }
702                } catch (FileNotFoundException expected) {
703                    mIsHistoricalPackageUsageAvailable = false;
704                } catch (IOException e) {
705                    Log.w(TAG, "Failed to read package usage times", e);
706                } finally {
707                    IoUtils.closeQuietly(in);
708                }
709            }
710            mLastWritten.set(SystemClock.elapsedRealtime());
711        }
712
713        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
714                throws IOException {
715            sb.setLength(0);
716            while (true) {
717                int ch = in.read();
718                if (ch == -1) {
719                    if (sb.length() == 0) {
720                        return null;
721                    }
722                    throw new IOException("Unexpected EOF");
723                }
724                if (ch == endOfToken) {
725                    return sb.toString();
726                }
727                sb.append((char)ch);
728            }
729        }
730
731        private AtomicFile getFile() {
732            File dataDir = Environment.getDataDirectory();
733            File systemDir = new File(dataDir, "system");
734            File fname = new File(systemDir, "package-usage.list");
735            return new AtomicFile(fname);
736        }
737    }
738
739    class PackageHandler extends Handler {
740        private boolean mBound = false;
741        final ArrayList<HandlerParams> mPendingInstalls =
742            new ArrayList<HandlerParams>();
743
744        private boolean connectToService() {
745            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
746                    " DefaultContainerService");
747            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
748            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
749            if (mContext.bindServiceAsUser(service, mDefContainerConn,
750                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
751                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
752                mBound = true;
753                return true;
754            }
755            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
756            return false;
757        }
758
759        private void disconnectService() {
760            mContainerService = null;
761            mBound = false;
762            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
763            mContext.unbindService(mDefContainerConn);
764            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
765        }
766
767        PackageHandler(Looper looper) {
768            super(looper);
769        }
770
771        public void handleMessage(Message msg) {
772            try {
773                doHandleMessage(msg);
774            } finally {
775                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
776            }
777        }
778
779        void doHandleMessage(Message msg) {
780            switch (msg.what) {
781                case INIT_COPY: {
782                    HandlerParams params = (HandlerParams) msg.obj;
783                    int idx = mPendingInstalls.size();
784                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
785                    // If a bind was already initiated we dont really
786                    // need to do anything. The pending install
787                    // will be processed later on.
788                    if (!mBound) {
789                        // If this is the only one pending we might
790                        // have to bind to the service again.
791                        if (!connectToService()) {
792                            Slog.e(TAG, "Failed to bind to media container service");
793                            params.serviceError();
794                            return;
795                        } else {
796                            // Once we bind to the service, the first
797                            // pending request will be processed.
798                            mPendingInstalls.add(idx, params);
799                        }
800                    } else {
801                        mPendingInstalls.add(idx, params);
802                        // Already bound to the service. Just make
803                        // sure we trigger off processing the first request.
804                        if (idx == 0) {
805                            mHandler.sendEmptyMessage(MCS_BOUND);
806                        }
807                    }
808                    break;
809                }
810                case MCS_BOUND: {
811                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
812                    if (msg.obj != null) {
813                        mContainerService = (IMediaContainerService) msg.obj;
814                    }
815                    if (mContainerService == null) {
816                        // Something seriously wrong. Bail out
817                        Slog.e(TAG, "Cannot bind to media container service");
818                        for (HandlerParams params : mPendingInstalls) {
819                            // Indicate service bind error
820                            params.serviceError();
821                        }
822                        mPendingInstalls.clear();
823                    } else if (mPendingInstalls.size() > 0) {
824                        HandlerParams params = mPendingInstalls.get(0);
825                        if (params != null) {
826                            if (params.startCopy()) {
827                                // We are done...  look for more work or to
828                                // go idle.
829                                if (DEBUG_SD_INSTALL) Log.i(TAG,
830                                        "Checking for more work or unbind...");
831                                // Delete pending install
832                                if (mPendingInstalls.size() > 0) {
833                                    mPendingInstalls.remove(0);
834                                }
835                                if (mPendingInstalls.size() == 0) {
836                                    if (mBound) {
837                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
838                                                "Posting delayed MCS_UNBIND");
839                                        removeMessages(MCS_UNBIND);
840                                        Message ubmsg = obtainMessage(MCS_UNBIND);
841                                        // Unbind after a little delay, to avoid
842                                        // continual thrashing.
843                                        sendMessageDelayed(ubmsg, 10000);
844                                    }
845                                } else {
846                                    // There are more pending requests in queue.
847                                    // Just post MCS_BOUND message to trigger processing
848                                    // of next pending install.
849                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
850                                            "Posting MCS_BOUND for next work");
851                                    mHandler.sendEmptyMessage(MCS_BOUND);
852                                }
853                            }
854                        }
855                    } else {
856                        // Should never happen ideally.
857                        Slog.w(TAG, "Empty queue");
858                    }
859                    break;
860                }
861                case MCS_RECONNECT: {
862                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
863                    if (mPendingInstalls.size() > 0) {
864                        if (mBound) {
865                            disconnectService();
866                        }
867                        if (!connectToService()) {
868                            Slog.e(TAG, "Failed to bind to media container service");
869                            for (HandlerParams params : mPendingInstalls) {
870                                // Indicate service bind error
871                                params.serviceError();
872                            }
873                            mPendingInstalls.clear();
874                        }
875                    }
876                    break;
877                }
878                case MCS_UNBIND: {
879                    // If there is no actual work left, then time to unbind.
880                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
881
882                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
883                        if (mBound) {
884                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
885
886                            disconnectService();
887                        }
888                    } else if (mPendingInstalls.size() > 0) {
889                        // There are more pending requests in queue.
890                        // Just post MCS_BOUND message to trigger processing
891                        // of next pending install.
892                        mHandler.sendEmptyMessage(MCS_BOUND);
893                    }
894
895                    break;
896                }
897                case MCS_GIVE_UP: {
898                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
899                    mPendingInstalls.remove(0);
900                    break;
901                }
902                case SEND_PENDING_BROADCAST: {
903                    String packages[];
904                    ArrayList<String> components[];
905                    int size = 0;
906                    int uids[];
907                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
908                    synchronized (mPackages) {
909                        if (mPendingBroadcasts == null) {
910                            return;
911                        }
912                        size = mPendingBroadcasts.size();
913                        if (size <= 0) {
914                            // Nothing to be done. Just return
915                            return;
916                        }
917                        packages = new String[size];
918                        components = new ArrayList[size];
919                        uids = new int[size];
920                        int i = 0;  // filling out the above arrays
921
922                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
923                            int packageUserId = mPendingBroadcasts.userIdAt(n);
924                            Iterator<Map.Entry<String, ArrayList<String>>> it
925                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
926                                            .entrySet().iterator();
927                            while (it.hasNext() && i < size) {
928                                Map.Entry<String, ArrayList<String>> ent = it.next();
929                                packages[i] = ent.getKey();
930                                components[i] = ent.getValue();
931                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
932                                uids[i] = (ps != null)
933                                        ? UserHandle.getUid(packageUserId, ps.appId)
934                                        : -1;
935                                i++;
936                            }
937                        }
938                        size = i;
939                        mPendingBroadcasts.clear();
940                    }
941                    // Send broadcasts
942                    for (int i = 0; i < size; i++) {
943                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
944                    }
945                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
946                    break;
947                }
948                case START_CLEANING_PACKAGE: {
949                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
950                    final String packageName = (String)msg.obj;
951                    final int userId = msg.arg1;
952                    final boolean andCode = msg.arg2 != 0;
953                    synchronized (mPackages) {
954                        if (userId == UserHandle.USER_ALL) {
955                            int[] users = sUserManager.getUserIds();
956                            for (int user : users) {
957                                mSettings.addPackageToCleanLPw(
958                                        new PackageCleanItem(user, packageName, andCode));
959                            }
960                        } else {
961                            mSettings.addPackageToCleanLPw(
962                                    new PackageCleanItem(userId, packageName, andCode));
963                        }
964                    }
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
966                    startCleaningPackages();
967                } break;
968                case POST_INSTALL: {
969                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
970                    PostInstallData data = mRunningInstalls.get(msg.arg1);
971                    mRunningInstalls.delete(msg.arg1);
972                    boolean deleteOld = false;
973
974                    if (data != null) {
975                        InstallArgs args = data.args;
976                        PackageInstalledInfo res = data.res;
977
978                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
979                            res.removedInfo.sendBroadcast(false, true, false);
980                            Bundle extras = new Bundle(1);
981                            extras.putInt(Intent.EXTRA_UID, res.uid);
982                            // Determine the set of users who are adding this
983                            // package for the first time vs. those who are seeing
984                            // an update.
985                            int[] firstUsers;
986                            int[] updateUsers = new int[0];
987                            if (res.origUsers == null || res.origUsers.length == 0) {
988                                firstUsers = res.newUsers;
989                            } else {
990                                firstUsers = new int[0];
991                                for (int i=0; i<res.newUsers.length; i++) {
992                                    int user = res.newUsers[i];
993                                    boolean isNew = true;
994                                    for (int j=0; j<res.origUsers.length; j++) {
995                                        if (res.origUsers[j] == user) {
996                                            isNew = false;
997                                            break;
998                                        }
999                                    }
1000                                    if (isNew) {
1001                                        int[] newFirst = new int[firstUsers.length+1];
1002                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1003                                                firstUsers.length);
1004                                        newFirst[firstUsers.length] = user;
1005                                        firstUsers = newFirst;
1006                                    } else {
1007                                        int[] newUpdate = new int[updateUsers.length+1];
1008                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1009                                                updateUsers.length);
1010                                        newUpdate[updateUsers.length] = user;
1011                                        updateUsers = newUpdate;
1012                                    }
1013                                }
1014                            }
1015                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1016                                    res.pkg.applicationInfo.packageName,
1017                                    extras, null, null, firstUsers);
1018                            final boolean update = res.removedInfo.removedPackage != null;
1019                            if (update) {
1020                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1021                            }
1022                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1023                                    res.pkg.applicationInfo.packageName,
1024                                    extras, null, null, updateUsers);
1025                            if (update) {
1026                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1027                                        res.pkg.applicationInfo.packageName,
1028                                        extras, null, null, updateUsers);
1029                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1030                                        null, null,
1031                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1032
1033                                // treat asec-hosted packages like removable media on upgrade
1034                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1035                                    if (DEBUG_INSTALL) {
1036                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1037                                                + " is ASEC-hosted -> AVAILABLE");
1038                                    }
1039                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1040                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1041                                    pkgList.add(res.pkg.applicationInfo.packageName);
1042                                    sendResourcesChangedBroadcast(true, true,
1043                                            pkgList,uidArray, null);
1044                                }
1045                            }
1046                            if (res.removedInfo.args != null) {
1047                                // Remove the replaced package's older resources safely now
1048                                deleteOld = true;
1049                            }
1050
1051                            // Log current value of "unknown sources" setting
1052                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1053                                getUnknownSourcesSettings());
1054                        }
1055                        // Force a gc to clear up things
1056                        Runtime.getRuntime().gc();
1057                        // We delete after a gc for applications  on sdcard.
1058                        if (deleteOld) {
1059                            synchronized (mInstallLock) {
1060                                res.removedInfo.args.doPostDeleteLI(true);
1061                            }
1062                        }
1063                        if (args.observer != null) {
1064                            try {
1065                                Bundle extras = extrasForInstallResult(res);
1066                                args.observer.onPackageInstalled(res.name, res.returnCode,
1067                                        res.returnMsg, extras);
1068                            } catch (RemoteException e) {
1069                                Slog.i(TAG, "Observer no longer exists.");
1070                            }
1071                        }
1072                    } else {
1073                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1074                    }
1075                } break;
1076                case UPDATED_MEDIA_STATUS: {
1077                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1078                    boolean reportStatus = msg.arg1 == 1;
1079                    boolean doGc = msg.arg2 == 1;
1080                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1081                    if (doGc) {
1082                        // Force a gc to clear up stale containers.
1083                        Runtime.getRuntime().gc();
1084                    }
1085                    if (msg.obj != null) {
1086                        @SuppressWarnings("unchecked")
1087                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1088                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1089                        // Unload containers
1090                        unloadAllContainers(args);
1091                    }
1092                    if (reportStatus) {
1093                        try {
1094                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1095                            PackageHelper.getMountService().finishMediaUpdate();
1096                        } catch (RemoteException e) {
1097                            Log.e(TAG, "MountService not running?");
1098                        }
1099                    }
1100                } break;
1101                case WRITE_SETTINGS: {
1102                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1103                    synchronized (mPackages) {
1104                        removeMessages(WRITE_SETTINGS);
1105                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1106                        mSettings.writeLPr();
1107                        mDirtyUsers.clear();
1108                    }
1109                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1110                } break;
1111                case WRITE_PACKAGE_RESTRICTIONS: {
1112                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1113                    synchronized (mPackages) {
1114                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1115                        for (int userId : mDirtyUsers) {
1116                            mSettings.writePackageRestrictionsLPr(userId);
1117                        }
1118                        mDirtyUsers.clear();
1119                    }
1120                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1121                } break;
1122                case CHECK_PENDING_VERIFICATION: {
1123                    final int verificationId = msg.arg1;
1124                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1125
1126                    if ((state != null) && !state.timeoutExtended()) {
1127                        final InstallArgs args = state.getInstallArgs();
1128                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1129
1130                        Slog.i(TAG, "Verification timed out for " + originUri);
1131                        mPendingVerification.remove(verificationId);
1132
1133                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1134
1135                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1136                            Slog.i(TAG, "Continuing with installation of " + originUri);
1137                            state.setVerifierResponse(Binder.getCallingUid(),
1138                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1139                            broadcastPackageVerified(verificationId, originUri,
1140                                    PackageManager.VERIFICATION_ALLOW,
1141                                    state.getInstallArgs().getUser());
1142                            try {
1143                                ret = args.copyApk(mContainerService, true);
1144                            } catch (RemoteException e) {
1145                                Slog.e(TAG, "Could not contact the ContainerService");
1146                            }
1147                        } else {
1148                            broadcastPackageVerified(verificationId, originUri,
1149                                    PackageManager.VERIFICATION_REJECT,
1150                                    state.getInstallArgs().getUser());
1151                        }
1152
1153                        processPendingInstall(args, ret);
1154                        mHandler.sendEmptyMessage(MCS_UNBIND);
1155                    }
1156                    break;
1157                }
1158                case PACKAGE_VERIFIED: {
1159                    final int verificationId = msg.arg1;
1160
1161                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1162                    if (state == null) {
1163                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1164                        break;
1165                    }
1166
1167                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1168
1169                    state.setVerifierResponse(response.callerUid, response.code);
1170
1171                    if (state.isVerificationComplete()) {
1172                        mPendingVerification.remove(verificationId);
1173
1174                        final InstallArgs args = state.getInstallArgs();
1175                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1176
1177                        int ret;
1178                        if (state.isInstallAllowed()) {
1179                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1180                            broadcastPackageVerified(verificationId, originUri,
1181                                    response.code, state.getInstallArgs().getUser());
1182                            try {
1183                                ret = args.copyApk(mContainerService, true);
1184                            } catch (RemoteException e) {
1185                                Slog.e(TAG, "Could not contact the ContainerService");
1186                            }
1187                        } else {
1188                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1189                        }
1190
1191                        processPendingInstall(args, ret);
1192
1193                        mHandler.sendEmptyMessage(MCS_UNBIND);
1194                    }
1195
1196                    break;
1197                }
1198            }
1199        }
1200    }
1201
1202    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1203        Bundle extras = null;
1204        switch (res.returnCode) {
1205            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1206                extras = new Bundle();
1207                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1208                        res.origPermission);
1209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1210                        res.origPackage);
1211                break;
1212            }
1213        }
1214        return extras;
1215    }
1216
1217    void scheduleWriteSettingsLocked() {
1218        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1219            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1220        }
1221    }
1222
1223    void scheduleWritePackageRestrictionsLocked(int userId) {
1224        if (!sUserManager.exists(userId)) return;
1225        mDirtyUsers.add(userId);
1226        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1227            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1228        }
1229    }
1230
1231    public static final PackageManagerService main(Context context, Installer installer,
1232            boolean factoryTest, boolean onlyCore) {
1233        PackageManagerService m = new PackageManagerService(context, installer,
1234                factoryTest, onlyCore);
1235        ServiceManager.addService("package", m);
1236        return m;
1237    }
1238
1239    static String[] splitString(String str, char sep) {
1240        int count = 1;
1241        int i = 0;
1242        while ((i=str.indexOf(sep, i)) >= 0) {
1243            count++;
1244            i++;
1245        }
1246
1247        String[] res = new String[count];
1248        i=0;
1249        count = 0;
1250        int lastI=0;
1251        while ((i=str.indexOf(sep, i)) >= 0) {
1252            res[count] = str.substring(lastI, i);
1253            count++;
1254            i++;
1255            lastI = i;
1256        }
1257        res[count] = str.substring(lastI, str.length());
1258        return res;
1259    }
1260
1261    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1262        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1263                Context.DISPLAY_SERVICE);
1264        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1265    }
1266
1267    public PackageManagerService(Context context, Installer installer,
1268            boolean factoryTest, boolean onlyCore) {
1269        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1270                SystemClock.uptimeMillis());
1271
1272        if (mSdkVersion <= 0) {
1273            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1274        }
1275
1276        mContext = context;
1277        mFactoryTest = factoryTest;
1278        mOnlyCore = onlyCore;
1279        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1280        mMetrics = new DisplayMetrics();
1281        mSettings = new Settings(context);
1282        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1283                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1284        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1285                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1287                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1288        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1289                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1290        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1291                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1292        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1293                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1294
1295        String separateProcesses = SystemProperties.get("debug.separate_processes");
1296        if (separateProcesses != null && separateProcesses.length() > 0) {
1297            if ("*".equals(separateProcesses)) {
1298                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1299                mSeparateProcesses = null;
1300                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1301            } else {
1302                mDefParseFlags = 0;
1303                mSeparateProcesses = separateProcesses.split(",");
1304                Slog.w(TAG, "Running with debug.separate_processes: "
1305                        + separateProcesses);
1306            }
1307        } else {
1308            mDefParseFlags = 0;
1309            mSeparateProcesses = null;
1310        }
1311
1312        mInstaller = installer;
1313
1314        getDefaultDisplayMetrics(context, mMetrics);
1315
1316        SystemConfig systemConfig = SystemConfig.getInstance();
1317        mGlobalGids = systemConfig.getGlobalGids();
1318        mSystemPermissions = systemConfig.getSystemPermissions();
1319        mAvailableFeatures = systemConfig.getAvailableFeatures();
1320
1321        synchronized (mInstallLock) {
1322        // writer
1323        synchronized (mPackages) {
1324            mHandlerThread = new ServiceThread(TAG,
1325                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1326            mHandlerThread.start();
1327            mHandler = new PackageHandler(mHandlerThread.getLooper());
1328            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1329
1330            File dataDir = Environment.getDataDirectory();
1331            mAppDataDir = new File(dataDir, "data");
1332            mAppInstallDir = new File(dataDir, "app");
1333            mAppLib32InstallDir = new File(dataDir, "app-lib");
1334            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1335            mUserAppDataDir = new File(dataDir, "user");
1336            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1337
1338            sUserManager = new UserManagerService(context, this,
1339                    mInstallLock, mPackages);
1340
1341            // Propagate permission configuration in to package manager.
1342            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1343                    = systemConfig.getPermissions();
1344            for (int i=0; i<permConfig.size(); i++) {
1345                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1346                BasePermission bp = mSettings.mPermissions.get(perm.name);
1347                if (bp == null) {
1348                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1349                    mSettings.mPermissions.put(perm.name, bp);
1350                }
1351                if (perm.gids != null) {
1352                    bp.gids = appendInts(bp.gids, perm.gids);
1353                }
1354            }
1355
1356            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1357            for (int i=0; i<libConfig.size(); i++) {
1358                mSharedLibraries.put(libConfig.keyAt(i),
1359                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1360            }
1361
1362            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1363
1364            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1365                    mSdkVersion, mOnlyCore);
1366
1367            String customResolverActivity = Resources.getSystem().getString(
1368                    R.string.config_customResolverActivity);
1369            if (TextUtils.isEmpty(customResolverActivity)) {
1370                customResolverActivity = null;
1371            } else {
1372                mCustomResolverComponentName = ComponentName.unflattenFromString(
1373                        customResolverActivity);
1374            }
1375
1376            long startTime = SystemClock.uptimeMillis();
1377
1378            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1379                    startTime);
1380
1381            // Set flag to monitor and not change apk file paths when
1382            // scanning install directories.
1383            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1384
1385            final ArraySet<String> alreadyDexOpted = new ArraySet<String>();
1386
1387            /**
1388             * Add everything in the in the boot class path to the
1389             * list of process files because dexopt will have been run
1390             * if necessary during zygote startup.
1391             */
1392            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1393            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1394
1395            if (bootClassPath != null) {
1396                String[] bootClassPathElements = splitString(bootClassPath, ':');
1397                for (String element : bootClassPathElements) {
1398                    alreadyDexOpted.add(element);
1399                }
1400            } else {
1401                Slog.w(TAG, "No BOOTCLASSPATH found!");
1402            }
1403
1404            if (systemServerClassPath != null) {
1405                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1406                for (String element : systemServerClassPathElements) {
1407                    alreadyDexOpted.add(element);
1408                }
1409            } else {
1410                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1411            }
1412
1413            boolean didDexOptLibraryOrTool = false;
1414
1415            final List<String> allInstructionSets = getAllInstructionSets();
1416            final String[] dexCodeInstructionSets =
1417                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1418
1419            /**
1420             * Ensure all external libraries have had dexopt run on them.
1421             */
1422            if (mSharedLibraries.size() > 0) {
1423                // NOTE: For now, we're compiling these system "shared libraries"
1424                // (and framework jars) into all available architectures. It's possible
1425                // to compile them only when we come across an app that uses them (there's
1426                // already logic for that in scanPackageLI) but that adds some complexity.
1427                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1428                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1429                        final String lib = libEntry.path;
1430                        if (lib == null) {
1431                            continue;
1432                        }
1433
1434                        try {
1435                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1436                                                                                 dexCodeInstructionSet,
1437                                                                                 false);
1438                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1439                                alreadyDexOpted.add(lib);
1440
1441                                // The list of "shared libraries" we have at this point is
1442                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1443                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1444                                } else {
1445                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1446                                }
1447                                didDexOptLibraryOrTool = true;
1448                            }
1449                        } catch (FileNotFoundException e) {
1450                            Slog.w(TAG, "Library not found: " + lib);
1451                        } catch (IOException e) {
1452                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1453                                    + e.getMessage());
1454                        }
1455                    }
1456                }
1457            }
1458
1459            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1460
1461            // Gross hack for now: we know this file doesn't contain any
1462            // code, so don't dexopt it to avoid the resulting log spew.
1463            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1464
1465            // Gross hack for now: we know this file is only part of
1466            // the boot class path for art, so don't dexopt it to
1467            // avoid the resulting log spew.
1468            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1469
1470            /**
1471             * And there are a number of commands implemented in Java, which
1472             * we currently need to do the dexopt on so that they can be
1473             * run from a non-root shell.
1474             */
1475            String[] frameworkFiles = frameworkDir.list();
1476            if (frameworkFiles != null) {
1477                // TODO: We could compile these only for the most preferred ABI. We should
1478                // first double check that the dex files for these commands are not referenced
1479                // by other system apps.
1480                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1481                    for (int i=0; i<frameworkFiles.length; i++) {
1482                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1483                        String path = libPath.getPath();
1484                        // Skip the file if we already did it.
1485                        if (alreadyDexOpted.contains(path)) {
1486                            continue;
1487                        }
1488                        // Skip the file if it is not a type we want to dexopt.
1489                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1490                            continue;
1491                        }
1492                        try {
1493                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1494                                                                                 dexCodeInstructionSet,
1495                                                                                 false);
1496                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1497                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1498                                didDexOptLibraryOrTool = true;
1499                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1500                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1501                                didDexOptLibraryOrTool = true;
1502                            }
1503                        } catch (FileNotFoundException e) {
1504                            Slog.w(TAG, "Jar not found: " + path);
1505                        } catch (IOException e) {
1506                            Slog.w(TAG, "Exception reading jar: " + path, e);
1507                        }
1508                    }
1509                }
1510            }
1511
1512            // Collect vendor overlay packages.
1513            // (Do this before scanning any apps.)
1514            // For security and version matching reason, only consider
1515            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1516            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1517            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1518                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1519
1520            // Find base frameworks (resource packages without code).
1521            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1522                    | PackageParser.PARSE_IS_SYSTEM_DIR
1523                    | PackageParser.PARSE_IS_PRIVILEGED,
1524                    scanFlags | SCAN_NO_DEX, 0);
1525
1526            // Collected privileged system packages.
1527            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1528            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1529                    | PackageParser.PARSE_IS_SYSTEM_DIR
1530                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1531
1532            // Collect ordinary system packages.
1533            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1534            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1535                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1536
1537            // Collect all vendor packages.
1538            File vendorAppDir = new File("/vendor/app");
1539            try {
1540                vendorAppDir = vendorAppDir.getCanonicalFile();
1541            } catch (IOException e) {
1542                // failed to look up canonical path, continue with original one
1543            }
1544            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1545                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1546
1547            // Collect all OEM packages.
1548            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1549            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1550                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1551
1552            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1553            mInstaller.moveFiles();
1554
1555            // Prune any system packages that no longer exist.
1556            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1557            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1558            if (!mOnlyCore) {
1559                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1560                while (psit.hasNext()) {
1561                    PackageSetting ps = psit.next();
1562
1563                    /*
1564                     * If this is not a system app, it can't be a
1565                     * disable system app.
1566                     */
1567                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1568                        continue;
1569                    }
1570
1571                    /*
1572                     * If the package is scanned, it's not erased.
1573                     */
1574                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1575                    if (scannedPkg != null) {
1576                        /*
1577                         * If the system app is both scanned and in the
1578                         * disabled packages list, then it must have been
1579                         * added via OTA. Remove it from the currently
1580                         * scanned package so the previously user-installed
1581                         * application can be scanned.
1582                         */
1583                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1584                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1585                                    + ps.name + "; removing system app.  Last known codePath="
1586                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1587                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1588                                    + scannedPkg.mVersionCode);
1589                            removePackageLI(ps, true);
1590                            expectingBetter.put(ps.name, ps.codePath);
1591                        }
1592
1593                        continue;
1594                    }
1595
1596                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1597                        psit.remove();
1598                        logCriticalInfo(Log.WARN, "System package " + ps.name
1599                                + " no longer exists; wiping its data");
1600                        removeDataDirsLI(ps.name);
1601                    } else {
1602                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1603                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1604                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1605                        }
1606                    }
1607                }
1608            }
1609
1610            //look for any incomplete package installations
1611            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1612            //clean up list
1613            for(int i = 0; i < deletePkgsList.size(); i++) {
1614                //clean up here
1615                cleanupInstallFailedPackage(deletePkgsList.get(i));
1616            }
1617            //delete tmp files
1618            deleteTempPackageFiles();
1619
1620            // Remove any shared userIDs that have no associated packages
1621            mSettings.pruneSharedUsersLPw();
1622
1623            if (!mOnlyCore) {
1624                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1625                        SystemClock.uptimeMillis());
1626                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1627
1628                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1629                        scanFlags, 0);
1630
1631                /**
1632                 * Remove disable package settings for any updated system
1633                 * apps that were removed via an OTA. If they're not a
1634                 * previously-updated app, remove them completely.
1635                 * Otherwise, just revoke their system-level permissions.
1636                 */
1637                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1638                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1639                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1640
1641                    String msg;
1642                    if (deletedPkg == null) {
1643                        msg = "Updated system package " + deletedAppName
1644                                + " no longer exists; wiping its data";
1645                        removeDataDirsLI(deletedAppName);
1646                    } else {
1647                        msg = "Updated system app + " + deletedAppName
1648                                + " no longer present; removing system privileges for "
1649                                + deletedAppName;
1650
1651                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1652
1653                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1654                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1655                    }
1656                    logCriticalInfo(Log.WARN, msg);
1657                }
1658
1659                /**
1660                 * Make sure all system apps that we expected to appear on
1661                 * the userdata partition actually showed up. If they never
1662                 * appeared, crawl back and revive the system version.
1663                 */
1664                for (int i = 0; i < expectingBetter.size(); i++) {
1665                    final String packageName = expectingBetter.keyAt(i);
1666                    if (!mPackages.containsKey(packageName)) {
1667                        final File scanFile = expectingBetter.valueAt(i);
1668
1669                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1670                                + " but never showed up; reverting to system");
1671
1672                        final int reparseFlags;
1673                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1674                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1675                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1676                                    | PackageParser.PARSE_IS_PRIVILEGED;
1677                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1678                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1679                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1680                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1681                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1682                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1683                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1684                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1685                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1686                        } else {
1687                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1688                            continue;
1689                        }
1690
1691                        mSettings.enableSystemPackageLPw(packageName);
1692
1693                        try {
1694                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1695                        } catch (PackageManagerException e) {
1696                            Slog.e(TAG, "Failed to parse original system package: "
1697                                    + e.getMessage());
1698                        }
1699                    }
1700                }
1701            }
1702
1703            // Now that we know all of the shared libraries, update all clients to have
1704            // the correct library paths.
1705            updateAllSharedLibrariesLPw();
1706
1707            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1708                // NOTE: We ignore potential failures here during a system scan (like
1709                // the rest of the commands above) because there's precious little we
1710                // can do about it. A settings error is reported, though.
1711                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1712                        false /* force dexopt */, false /* defer dexopt */);
1713            }
1714
1715            // Now that we know all the packages we are keeping,
1716            // read and update their last usage times.
1717            mPackageUsage.readLP();
1718
1719            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1720                    SystemClock.uptimeMillis());
1721            Slog.i(TAG, "Time to scan packages: "
1722                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1723                    + " seconds");
1724
1725            // If the platform SDK has changed since the last time we booted,
1726            // we need to re-grant app permission to catch any new ones that
1727            // appear.  This is really a hack, and means that apps can in some
1728            // cases get permissions that the user didn't initially explicitly
1729            // allow...  it would be nice to have some better way to handle
1730            // this situation.
1731            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1732                    != mSdkVersion;
1733            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1734                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1735                    + "; regranting permissions for internal storage");
1736            mSettings.mInternalSdkPlatform = mSdkVersion;
1737
1738            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1739                    | (regrantPermissions
1740                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1741                            : 0));
1742
1743            // If this is the first boot, and it is a normal boot, then
1744            // we need to initialize the default preferred apps.
1745            if (!mRestoredSettings && !onlyCore) {
1746                mSettings.readDefaultPreferredAppsLPw(this, 0);
1747            }
1748
1749            // If this is first boot after an OTA, and a normal boot, then
1750            // we need to clear code cache directories.
1751            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1752                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1753                for (String pkgName : mSettings.mPackages.keySet()) {
1754                    deleteCodeCacheDirsLI(pkgName);
1755                }
1756                mSettings.mFingerprint = Build.FINGERPRINT;
1757            }
1758
1759            // All the changes are done during package scanning.
1760            mSettings.updateInternalDatabaseVersion();
1761
1762            // can downgrade to reader
1763            mSettings.writeLPr();
1764
1765            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1766                    SystemClock.uptimeMillis());
1767
1768
1769            mRequiredVerifierPackage = getRequiredVerifierLPr();
1770        } // synchronized (mPackages)
1771        } // synchronized (mInstallLock)
1772
1773        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1774
1775        // Now after opening every single application zip, make sure they
1776        // are all flushed.  Not really needed, but keeps things nice and
1777        // tidy.
1778        Runtime.getRuntime().gc();
1779    }
1780
1781    @Override
1782    public boolean isFirstBoot() {
1783        return !mRestoredSettings;
1784    }
1785
1786    @Override
1787    public boolean isOnlyCoreApps() {
1788        return mOnlyCore;
1789    }
1790
1791    private String getRequiredVerifierLPr() {
1792        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1793        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1794                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1795
1796        String requiredVerifier = null;
1797
1798        final int N = receivers.size();
1799        for (int i = 0; i < N; i++) {
1800            final ResolveInfo info = receivers.get(i);
1801
1802            if (info.activityInfo == null) {
1803                continue;
1804            }
1805
1806            final String packageName = info.activityInfo.packageName;
1807
1808            final PackageSetting ps = mSettings.mPackages.get(packageName);
1809            if (ps == null) {
1810                continue;
1811            }
1812
1813            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1814            if (!gp.grantedPermissions
1815                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1816                continue;
1817            }
1818
1819            if (requiredVerifier != null) {
1820                throw new RuntimeException("There can be only one required verifier");
1821            }
1822
1823            requiredVerifier = packageName;
1824        }
1825
1826        return requiredVerifier;
1827    }
1828
1829    @Override
1830    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1831            throws RemoteException {
1832        try {
1833            return super.onTransact(code, data, reply, flags);
1834        } catch (RuntimeException e) {
1835            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1836                Slog.wtf(TAG, "Package Manager Crash", e);
1837            }
1838            throw e;
1839        }
1840    }
1841
1842    void cleanupInstallFailedPackage(PackageSetting ps) {
1843        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1844
1845        removeDataDirsLI(ps.name);
1846        if (ps.codePath != null) {
1847            if (ps.codePath.isDirectory()) {
1848                FileUtils.deleteContents(ps.codePath);
1849            }
1850            ps.codePath.delete();
1851        }
1852        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1853            if (ps.resourcePath.isDirectory()) {
1854                FileUtils.deleteContents(ps.resourcePath);
1855            }
1856            ps.resourcePath.delete();
1857        }
1858        mSettings.removePackageLPw(ps.name);
1859    }
1860
1861    static int[] appendInts(int[] cur, int[] add) {
1862        if (add == null) return cur;
1863        if (cur == null) return add;
1864        final int N = add.length;
1865        for (int i=0; i<N; i++) {
1866            cur = appendInt(cur, add[i]);
1867        }
1868        return cur;
1869    }
1870
1871    static int[] removeInts(int[] cur, int[] rem) {
1872        if (rem == null) return cur;
1873        if (cur == null) return cur;
1874        final int N = rem.length;
1875        for (int i=0; i<N; i++) {
1876            cur = removeInt(cur, rem[i]);
1877        }
1878        return cur;
1879    }
1880
1881    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1882        if (!sUserManager.exists(userId)) return null;
1883        final PackageSetting ps = (PackageSetting) p.mExtras;
1884        if (ps == null) {
1885            return null;
1886        }
1887        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1888        final PackageUserState state = ps.readUserState(userId);
1889        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1890                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1891                state, userId);
1892    }
1893
1894    @Override
1895    public boolean isPackageAvailable(String packageName, int userId) {
1896        if (!sUserManager.exists(userId)) return false;
1897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1898        synchronized (mPackages) {
1899            PackageParser.Package p = mPackages.get(packageName);
1900            if (p != null) {
1901                final PackageSetting ps = (PackageSetting) p.mExtras;
1902                if (ps != null) {
1903                    final PackageUserState state = ps.readUserState(userId);
1904                    if (state != null) {
1905                        return PackageParser.isAvailable(state);
1906                    }
1907                }
1908            }
1909        }
1910        return false;
1911    }
1912
1913    @Override
1914    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1915        if (!sUserManager.exists(userId)) return null;
1916        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1917        // reader
1918        synchronized (mPackages) {
1919            PackageParser.Package p = mPackages.get(packageName);
1920            if (DEBUG_PACKAGE_INFO)
1921                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1922            if (p != null) {
1923                return generatePackageInfo(p, flags, userId);
1924            }
1925            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1926                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1927            }
1928        }
1929        return null;
1930    }
1931
1932    @Override
1933    public String[] currentToCanonicalPackageNames(String[] names) {
1934        String[] out = new String[names.length];
1935        // reader
1936        synchronized (mPackages) {
1937            for (int i=names.length-1; i>=0; i--) {
1938                PackageSetting ps = mSettings.mPackages.get(names[i]);
1939                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1940            }
1941        }
1942        return out;
1943    }
1944
1945    @Override
1946    public String[] canonicalToCurrentPackageNames(String[] names) {
1947        String[] out = new String[names.length];
1948        // reader
1949        synchronized (mPackages) {
1950            for (int i=names.length-1; i>=0; i--) {
1951                String cur = mSettings.mRenamedPackages.get(names[i]);
1952                out[i] = cur != null ? cur : names[i];
1953            }
1954        }
1955        return out;
1956    }
1957
1958    @Override
1959    public int getPackageUid(String packageName, int userId) {
1960        if (!sUserManager.exists(userId)) return -1;
1961        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1962        // reader
1963        synchronized (mPackages) {
1964            PackageParser.Package p = mPackages.get(packageName);
1965            if(p != null) {
1966                return UserHandle.getUid(userId, p.applicationInfo.uid);
1967            }
1968            PackageSetting ps = mSettings.mPackages.get(packageName);
1969            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1970                return -1;
1971            }
1972            p = ps.pkg;
1973            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1974        }
1975    }
1976
1977    @Override
1978    public int[] getPackageGids(String packageName) {
1979        // reader
1980        synchronized (mPackages) {
1981            PackageParser.Package p = mPackages.get(packageName);
1982            if (DEBUG_PACKAGE_INFO)
1983                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1984            if (p != null) {
1985                final PackageSetting ps = (PackageSetting)p.mExtras;
1986                return ps.getGids();
1987            }
1988        }
1989        // stupid thing to indicate an error.
1990        return new int[0];
1991    }
1992
1993    static final PermissionInfo generatePermissionInfo(
1994            BasePermission bp, int flags) {
1995        if (bp.perm != null) {
1996            return PackageParser.generatePermissionInfo(bp.perm, flags);
1997        }
1998        PermissionInfo pi = new PermissionInfo();
1999        pi.name = bp.name;
2000        pi.packageName = bp.sourcePackage;
2001        pi.nonLocalizedLabel = bp.name;
2002        pi.protectionLevel = bp.protectionLevel;
2003        return pi;
2004    }
2005
2006    @Override
2007    public PermissionInfo getPermissionInfo(String name, int flags) {
2008        // reader
2009        synchronized (mPackages) {
2010            final BasePermission p = mSettings.mPermissions.get(name);
2011            if (p != null) {
2012                return generatePermissionInfo(p, flags);
2013            }
2014            return null;
2015        }
2016    }
2017
2018    @Override
2019    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2020        // reader
2021        synchronized (mPackages) {
2022            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2023            for (BasePermission p : mSettings.mPermissions.values()) {
2024                if (group == null) {
2025                    if (p.perm == null || p.perm.info.group == null) {
2026                        out.add(generatePermissionInfo(p, flags));
2027                    }
2028                } else {
2029                    if (p.perm != null && group.equals(p.perm.info.group)) {
2030                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2031                    }
2032                }
2033            }
2034
2035            if (out.size() > 0) {
2036                return out;
2037            }
2038            return mPermissionGroups.containsKey(group) ? out : null;
2039        }
2040    }
2041
2042    @Override
2043    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2044        // reader
2045        synchronized (mPackages) {
2046            return PackageParser.generatePermissionGroupInfo(
2047                    mPermissionGroups.get(name), flags);
2048        }
2049    }
2050
2051    @Override
2052    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2053        // reader
2054        synchronized (mPackages) {
2055            final int N = mPermissionGroups.size();
2056            ArrayList<PermissionGroupInfo> out
2057                    = new ArrayList<PermissionGroupInfo>(N);
2058            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2059                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2060            }
2061            return out;
2062        }
2063    }
2064
2065    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2066            int userId) {
2067        if (!sUserManager.exists(userId)) return null;
2068        PackageSetting ps = mSettings.mPackages.get(packageName);
2069        if (ps != null) {
2070            if (ps.pkg == null) {
2071                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2072                        flags, userId);
2073                if (pInfo != null) {
2074                    return pInfo.applicationInfo;
2075                }
2076                return null;
2077            }
2078            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2079                    ps.readUserState(userId), userId);
2080        }
2081        return null;
2082    }
2083
2084    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2085            int userId) {
2086        if (!sUserManager.exists(userId)) return null;
2087        PackageSetting ps = mSettings.mPackages.get(packageName);
2088        if (ps != null) {
2089            PackageParser.Package pkg = ps.pkg;
2090            if (pkg == null) {
2091                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2092                    return null;
2093                }
2094                // Only data remains, so we aren't worried about code paths
2095                pkg = new PackageParser.Package(packageName);
2096                pkg.applicationInfo.packageName = packageName;
2097                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2098                pkg.applicationInfo.dataDir =
2099                        getDataPathForPackage(packageName, 0).getPath();
2100                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2101                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2102            }
2103            return generatePackageInfo(pkg, flags, userId);
2104        }
2105        return null;
2106    }
2107
2108    @Override
2109    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2110        if (!sUserManager.exists(userId)) return null;
2111        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2112        // writer
2113        synchronized (mPackages) {
2114            PackageParser.Package p = mPackages.get(packageName);
2115            if (DEBUG_PACKAGE_INFO) Log.v(
2116                    TAG, "getApplicationInfo " + packageName
2117                    + ": " + p);
2118            if (p != null) {
2119                PackageSetting ps = mSettings.mPackages.get(packageName);
2120                if (ps == null) return null;
2121                // Note: isEnabledLP() does not apply here - always return info
2122                return PackageParser.generateApplicationInfo(
2123                        p, flags, ps.readUserState(userId), userId);
2124            }
2125            if ("android".equals(packageName)||"system".equals(packageName)) {
2126                return mAndroidApplication;
2127            }
2128            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2129                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2130            }
2131        }
2132        return null;
2133    }
2134
2135
2136    @Override
2137    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2138        mContext.enforceCallingOrSelfPermission(
2139                android.Manifest.permission.CLEAR_APP_CACHE, null);
2140        // Queue up an async operation since clearing cache may take a little while.
2141        mHandler.post(new Runnable() {
2142            public void run() {
2143                mHandler.removeCallbacks(this);
2144                int retCode = -1;
2145                synchronized (mInstallLock) {
2146                    retCode = mInstaller.freeCache(freeStorageSize);
2147                    if (retCode < 0) {
2148                        Slog.w(TAG, "Couldn't clear application caches");
2149                    }
2150                }
2151                if (observer != null) {
2152                    try {
2153                        observer.onRemoveCompleted(null, (retCode >= 0));
2154                    } catch (RemoteException e) {
2155                        Slog.w(TAG, "RemoveException when invoking call back");
2156                    }
2157                }
2158            }
2159        });
2160    }
2161
2162    @Override
2163    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2164        mContext.enforceCallingOrSelfPermission(
2165                android.Manifest.permission.CLEAR_APP_CACHE, null);
2166        // Queue up an async operation since clearing cache may take a little while.
2167        mHandler.post(new Runnable() {
2168            public void run() {
2169                mHandler.removeCallbacks(this);
2170                int retCode = -1;
2171                synchronized (mInstallLock) {
2172                    retCode = mInstaller.freeCache(freeStorageSize);
2173                    if (retCode < 0) {
2174                        Slog.w(TAG, "Couldn't clear application caches");
2175                    }
2176                }
2177                if(pi != null) {
2178                    try {
2179                        // Callback via pending intent
2180                        int code = (retCode >= 0) ? 1 : 0;
2181                        pi.sendIntent(null, code, null,
2182                                null, null);
2183                    } catch (SendIntentException e1) {
2184                        Slog.i(TAG, "Failed to send pending intent");
2185                    }
2186                }
2187            }
2188        });
2189    }
2190
2191    void freeStorage(long freeStorageSize) throws IOException {
2192        synchronized (mInstallLock) {
2193            if (mInstaller.freeCache(freeStorageSize) < 0) {
2194                throw new IOException("Failed to free enough space");
2195            }
2196        }
2197    }
2198
2199    @Override
2200    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2201        if (!sUserManager.exists(userId)) return null;
2202        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2203        synchronized (mPackages) {
2204            PackageParser.Activity a = mActivities.mActivities.get(component);
2205
2206            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2207            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2208                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2209                if (ps == null) return null;
2210                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2211                        userId);
2212            }
2213            if (mResolveComponentName.equals(component)) {
2214                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2215                        new PackageUserState(), userId);
2216            }
2217        }
2218        return null;
2219    }
2220
2221    @Override
2222    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2223            String resolvedType) {
2224        synchronized (mPackages) {
2225            PackageParser.Activity a = mActivities.mActivities.get(component);
2226            if (a == null) {
2227                return false;
2228            }
2229            for (int i=0; i<a.intents.size(); i++) {
2230                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2231                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2232                    return true;
2233                }
2234            }
2235            return false;
2236        }
2237    }
2238
2239    @Override
2240    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2241        if (!sUserManager.exists(userId)) return null;
2242        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2243        synchronized (mPackages) {
2244            PackageParser.Activity a = mReceivers.mActivities.get(component);
2245            if (DEBUG_PACKAGE_INFO) Log.v(
2246                TAG, "getReceiverInfo " + component + ": " + a);
2247            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2248                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2249                if (ps == null) return null;
2250                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2251                        userId);
2252            }
2253        }
2254        return null;
2255    }
2256
2257    @Override
2258    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2259        if (!sUserManager.exists(userId)) return null;
2260        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2261        synchronized (mPackages) {
2262            PackageParser.Service s = mServices.mServices.get(component);
2263            if (DEBUG_PACKAGE_INFO) Log.v(
2264                TAG, "getServiceInfo " + component + ": " + s);
2265            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2266                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2267                if (ps == null) return null;
2268                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2269                        userId);
2270            }
2271        }
2272        return null;
2273    }
2274
2275    @Override
2276    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2277        if (!sUserManager.exists(userId)) return null;
2278        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2279        synchronized (mPackages) {
2280            PackageParser.Provider p = mProviders.mProviders.get(component);
2281            if (DEBUG_PACKAGE_INFO) Log.v(
2282                TAG, "getProviderInfo " + component + ": " + p);
2283            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2284                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2285                if (ps == null) return null;
2286                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2287                        userId);
2288            }
2289        }
2290        return null;
2291    }
2292
2293    @Override
2294    public String[] getSystemSharedLibraryNames() {
2295        Set<String> libSet;
2296        synchronized (mPackages) {
2297            libSet = mSharedLibraries.keySet();
2298            int size = libSet.size();
2299            if (size > 0) {
2300                String[] libs = new String[size];
2301                libSet.toArray(libs);
2302                return libs;
2303            }
2304        }
2305        return null;
2306    }
2307
2308    @Override
2309    public FeatureInfo[] getSystemAvailableFeatures() {
2310        Collection<FeatureInfo> featSet;
2311        synchronized (mPackages) {
2312            featSet = mAvailableFeatures.values();
2313            int size = featSet.size();
2314            if (size > 0) {
2315                FeatureInfo[] features = new FeatureInfo[size+1];
2316                featSet.toArray(features);
2317                FeatureInfo fi = new FeatureInfo();
2318                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2319                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2320                features[size] = fi;
2321                return features;
2322            }
2323        }
2324        return null;
2325    }
2326
2327    @Override
2328    public boolean hasSystemFeature(String name) {
2329        synchronized (mPackages) {
2330            return mAvailableFeatures.containsKey(name);
2331        }
2332    }
2333
2334    private void checkValidCaller(int uid, int userId) {
2335        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2336            return;
2337
2338        throw new SecurityException("Caller uid=" + uid
2339                + " is not privileged to communicate with user=" + userId);
2340    }
2341
2342    @Override
2343    public int checkPermission(String permName, String pkgName) {
2344        synchronized (mPackages) {
2345            PackageParser.Package p = mPackages.get(pkgName);
2346            if (p != null && p.mExtras != null) {
2347                PackageSetting ps = (PackageSetting)p.mExtras;
2348                if (ps.sharedUser != null) {
2349                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2350                        return PackageManager.PERMISSION_GRANTED;
2351                    }
2352                } else if (ps.grantedPermissions.contains(permName)) {
2353                    return PackageManager.PERMISSION_GRANTED;
2354                }
2355            }
2356        }
2357        return PackageManager.PERMISSION_DENIED;
2358    }
2359
2360    @Override
2361    public int checkUidPermission(String permName, int uid) {
2362        synchronized (mPackages) {
2363            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2364            if (obj != null) {
2365                GrantedPermissions gp = (GrantedPermissions)obj;
2366                if (gp.grantedPermissions.contains(permName)) {
2367                    return PackageManager.PERMISSION_GRANTED;
2368                }
2369            } else {
2370                ArraySet<String> perms = mSystemPermissions.get(uid);
2371                if (perms != null && perms.contains(permName)) {
2372                    return PackageManager.PERMISSION_GRANTED;
2373                }
2374            }
2375        }
2376        return PackageManager.PERMISSION_DENIED;
2377    }
2378
2379    /**
2380     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2381     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2382     * @param checkShell TODO(yamasani):
2383     * @param message the message to log on security exception
2384     */
2385    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2386            boolean checkShell, String message) {
2387        if (userId < 0) {
2388            throw new IllegalArgumentException("Invalid userId " + userId);
2389        }
2390        if (checkShell) {
2391            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2392        }
2393        if (userId == UserHandle.getUserId(callingUid)) return;
2394        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2395            if (requireFullPermission) {
2396                mContext.enforceCallingOrSelfPermission(
2397                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2398            } else {
2399                try {
2400                    mContext.enforceCallingOrSelfPermission(
2401                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2402                } catch (SecurityException se) {
2403                    mContext.enforceCallingOrSelfPermission(
2404                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2405                }
2406            }
2407        }
2408    }
2409
2410    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2411        if (callingUid == Process.SHELL_UID) {
2412            if (userHandle >= 0
2413                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2414                throw new SecurityException("Shell does not have permission to access user "
2415                        + userHandle);
2416            } else if (userHandle < 0) {
2417                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2418                        + Debug.getCallers(3));
2419            }
2420        }
2421    }
2422
2423    private BasePermission findPermissionTreeLP(String permName) {
2424        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2425            if (permName.startsWith(bp.name) &&
2426                    permName.length() > bp.name.length() &&
2427                    permName.charAt(bp.name.length()) == '.') {
2428                return bp;
2429            }
2430        }
2431        return null;
2432    }
2433
2434    private BasePermission checkPermissionTreeLP(String permName) {
2435        if (permName != null) {
2436            BasePermission bp = findPermissionTreeLP(permName);
2437            if (bp != null) {
2438                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2439                    return bp;
2440                }
2441                throw new SecurityException("Calling uid "
2442                        + Binder.getCallingUid()
2443                        + " is not allowed to add to permission tree "
2444                        + bp.name + " owned by uid " + bp.uid);
2445            }
2446        }
2447        throw new SecurityException("No permission tree found for " + permName);
2448    }
2449
2450    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2451        if (s1 == null) {
2452            return s2 == null;
2453        }
2454        if (s2 == null) {
2455            return false;
2456        }
2457        if (s1.getClass() != s2.getClass()) {
2458            return false;
2459        }
2460        return s1.equals(s2);
2461    }
2462
2463    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2464        if (pi1.icon != pi2.icon) return false;
2465        if (pi1.logo != pi2.logo) return false;
2466        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2467        if (!compareStrings(pi1.name, pi2.name)) return false;
2468        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2469        // We'll take care of setting this one.
2470        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2471        // These are not currently stored in settings.
2472        //if (!compareStrings(pi1.group, pi2.group)) return false;
2473        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2474        //if (pi1.labelRes != pi2.labelRes) return false;
2475        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2476        return true;
2477    }
2478
2479    int permissionInfoFootprint(PermissionInfo info) {
2480        int size = info.name.length();
2481        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2482        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2483        return size;
2484    }
2485
2486    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2487        int size = 0;
2488        for (BasePermission perm : mSettings.mPermissions.values()) {
2489            if (perm.uid == tree.uid) {
2490                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2491            }
2492        }
2493        return size;
2494    }
2495
2496    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2497        // We calculate the max size of permissions defined by this uid and throw
2498        // if that plus the size of 'info' would exceed our stated maximum.
2499        if (tree.uid != Process.SYSTEM_UID) {
2500            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2501            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2502                throw new SecurityException("Permission tree size cap exceeded");
2503            }
2504        }
2505    }
2506
2507    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2508        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2509            throw new SecurityException("Label must be specified in permission");
2510        }
2511        BasePermission tree = checkPermissionTreeLP(info.name);
2512        BasePermission bp = mSettings.mPermissions.get(info.name);
2513        boolean added = bp == null;
2514        boolean changed = true;
2515        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2516        if (added) {
2517            enforcePermissionCapLocked(info, tree);
2518            bp = new BasePermission(info.name, tree.sourcePackage,
2519                    BasePermission.TYPE_DYNAMIC);
2520        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2521            throw new SecurityException(
2522                    "Not allowed to modify non-dynamic permission "
2523                    + info.name);
2524        } else {
2525            if (bp.protectionLevel == fixedLevel
2526                    && bp.perm.owner.equals(tree.perm.owner)
2527                    && bp.uid == tree.uid
2528                    && comparePermissionInfos(bp.perm.info, info)) {
2529                changed = false;
2530            }
2531        }
2532        bp.protectionLevel = fixedLevel;
2533        info = new PermissionInfo(info);
2534        info.protectionLevel = fixedLevel;
2535        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2536        bp.perm.info.packageName = tree.perm.info.packageName;
2537        bp.uid = tree.uid;
2538        if (added) {
2539            mSettings.mPermissions.put(info.name, bp);
2540        }
2541        if (changed) {
2542            if (!async) {
2543                mSettings.writeLPr();
2544            } else {
2545                scheduleWriteSettingsLocked();
2546            }
2547        }
2548        return added;
2549    }
2550
2551    @Override
2552    public boolean addPermission(PermissionInfo info) {
2553        synchronized (mPackages) {
2554            return addPermissionLocked(info, false);
2555        }
2556    }
2557
2558    @Override
2559    public boolean addPermissionAsync(PermissionInfo info) {
2560        synchronized (mPackages) {
2561            return addPermissionLocked(info, true);
2562        }
2563    }
2564
2565    @Override
2566    public void removePermission(String name) {
2567        synchronized (mPackages) {
2568            checkPermissionTreeLP(name);
2569            BasePermission bp = mSettings.mPermissions.get(name);
2570            if (bp != null) {
2571                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2572                    throw new SecurityException(
2573                            "Not allowed to modify non-dynamic permission "
2574                            + name);
2575                }
2576                mSettings.mPermissions.remove(name);
2577                mSettings.writeLPr();
2578            }
2579        }
2580    }
2581
2582    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2583        int index = pkg.requestedPermissions.indexOf(bp.name);
2584        if (index == -1) {
2585            throw new SecurityException("Package " + pkg.packageName
2586                    + " has not requested permission " + bp.name);
2587        }
2588        boolean isNormal =
2589                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2590                        == PermissionInfo.PROTECTION_NORMAL);
2591        boolean isDangerous =
2592                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2593                        == PermissionInfo.PROTECTION_DANGEROUS);
2594        boolean isDevelopment =
2595                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2596
2597        if (!isNormal && !isDangerous && !isDevelopment) {
2598            throw new SecurityException("Permission " + bp.name
2599                    + " is not a changeable permission type");
2600        }
2601
2602        if (isNormal || isDangerous) {
2603            if (pkg.requestedPermissionsRequired.get(index)) {
2604                throw new SecurityException("Can't change " + bp.name
2605                        + ". It is required by the application");
2606            }
2607        }
2608    }
2609
2610    @Override
2611    public void grantPermission(String packageName, String permissionName) {
2612        mContext.enforceCallingOrSelfPermission(
2613                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2614        synchronized (mPackages) {
2615            final PackageParser.Package pkg = mPackages.get(packageName);
2616            if (pkg == null) {
2617                throw new IllegalArgumentException("Unknown package: " + packageName);
2618            }
2619            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2620            if (bp == null) {
2621                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2622            }
2623
2624            checkGrantRevokePermissions(pkg, bp);
2625
2626            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2627            if (ps == null) {
2628                return;
2629            }
2630            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2631            if (gp.grantedPermissions.add(permissionName)) {
2632                if (ps.haveGids) {
2633                    gp.gids = appendInts(gp.gids, bp.gids);
2634                }
2635                mSettings.writeLPr();
2636            }
2637        }
2638    }
2639
2640    @Override
2641    public void revokePermission(String packageName, String permissionName) {
2642        int changedAppId = -1;
2643
2644        synchronized (mPackages) {
2645            final PackageParser.Package pkg = mPackages.get(packageName);
2646            if (pkg == null) {
2647                throw new IllegalArgumentException("Unknown package: " + packageName);
2648            }
2649            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2650                mContext.enforceCallingOrSelfPermission(
2651                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2652            }
2653            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2654            if (bp == null) {
2655                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2656            }
2657
2658            checkGrantRevokePermissions(pkg, bp);
2659
2660            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2661            if (ps == null) {
2662                return;
2663            }
2664            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2665            if (gp.grantedPermissions.remove(permissionName)) {
2666                gp.grantedPermissions.remove(permissionName);
2667                if (ps.haveGids) {
2668                    gp.gids = removeInts(gp.gids, bp.gids);
2669                }
2670                mSettings.writeLPr();
2671                changedAppId = ps.appId;
2672            }
2673        }
2674
2675        if (changedAppId >= 0) {
2676            // We changed the perm on someone, kill its processes.
2677            IActivityManager am = ActivityManagerNative.getDefault();
2678            if (am != null) {
2679                final int callingUserId = UserHandle.getCallingUserId();
2680                final long ident = Binder.clearCallingIdentity();
2681                try {
2682                    //XXX we should only revoke for the calling user's app permissions,
2683                    // but for now we impact all users.
2684                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2685                    //        "revoke " + permissionName);
2686                    int[] users = sUserManager.getUserIds();
2687                    for (int user : users) {
2688                        am.killUid(UserHandle.getUid(user, changedAppId),
2689                                "revoke " + permissionName);
2690                    }
2691                } catch (RemoteException e) {
2692                } finally {
2693                    Binder.restoreCallingIdentity(ident);
2694                }
2695            }
2696        }
2697    }
2698
2699    @Override
2700    public boolean isProtectedBroadcast(String actionName) {
2701        synchronized (mPackages) {
2702            return mProtectedBroadcasts.contains(actionName);
2703        }
2704    }
2705
2706    @Override
2707    public int checkSignatures(String pkg1, String pkg2) {
2708        synchronized (mPackages) {
2709            final PackageParser.Package p1 = mPackages.get(pkg1);
2710            final PackageParser.Package p2 = mPackages.get(pkg2);
2711            if (p1 == null || p1.mExtras == null
2712                    || p2 == null || p2.mExtras == null) {
2713                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2714            }
2715            return compareSignatures(p1.mSignatures, p2.mSignatures);
2716        }
2717    }
2718
2719    @Override
2720    public int checkUidSignatures(int uid1, int uid2) {
2721        // Map to base uids.
2722        uid1 = UserHandle.getAppId(uid1);
2723        uid2 = UserHandle.getAppId(uid2);
2724        // reader
2725        synchronized (mPackages) {
2726            Signature[] s1;
2727            Signature[] s2;
2728            Object obj = mSettings.getUserIdLPr(uid1);
2729            if (obj != null) {
2730                if (obj instanceof SharedUserSetting) {
2731                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2732                } else if (obj instanceof PackageSetting) {
2733                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2734                } else {
2735                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2736                }
2737            } else {
2738                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2739            }
2740            obj = mSettings.getUserIdLPr(uid2);
2741            if (obj != null) {
2742                if (obj instanceof SharedUserSetting) {
2743                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2744                } else if (obj instanceof PackageSetting) {
2745                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2746                } else {
2747                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2748                }
2749            } else {
2750                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2751            }
2752            return compareSignatures(s1, s2);
2753        }
2754    }
2755
2756    /**
2757     * Compares two sets of signatures. Returns:
2758     * <br />
2759     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2760     * <br />
2761     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2762     * <br />
2763     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2764     * <br />
2765     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2766     * <br />
2767     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2768     */
2769    static int compareSignatures(Signature[] s1, Signature[] s2) {
2770        if (s1 == null) {
2771            return s2 == null
2772                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2773                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2774        }
2775
2776        if (s2 == null) {
2777            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2778        }
2779
2780        if (s1.length != s2.length) {
2781            return PackageManager.SIGNATURE_NO_MATCH;
2782        }
2783
2784        // Since both signature sets are of size 1, we can compare without HashSets.
2785        if (s1.length == 1) {
2786            return s1[0].equals(s2[0]) ?
2787                    PackageManager.SIGNATURE_MATCH :
2788                    PackageManager.SIGNATURE_NO_MATCH;
2789        }
2790
2791        ArraySet<Signature> set1 = new ArraySet<Signature>();
2792        for (Signature sig : s1) {
2793            set1.add(sig);
2794        }
2795        ArraySet<Signature> set2 = new ArraySet<Signature>();
2796        for (Signature sig : s2) {
2797            set2.add(sig);
2798        }
2799        // Make sure s2 contains all signatures in s1.
2800        if (set1.equals(set2)) {
2801            return PackageManager.SIGNATURE_MATCH;
2802        }
2803        return PackageManager.SIGNATURE_NO_MATCH;
2804    }
2805
2806    /**
2807     * If the database version for this type of package (internal storage or
2808     * external storage) is less than the version where package signatures
2809     * were updated, return true.
2810     */
2811    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2812        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2813                DatabaseVersion.SIGNATURE_END_ENTITY))
2814                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2815                        DatabaseVersion.SIGNATURE_END_ENTITY));
2816    }
2817
2818    /**
2819     * Used for backward compatibility to make sure any packages with
2820     * certificate chains get upgraded to the new style. {@code existingSigs}
2821     * will be in the old format (since they were stored on disk from before the
2822     * system upgrade) and {@code scannedSigs} will be in the newer format.
2823     */
2824    private int compareSignaturesCompat(PackageSignatures existingSigs,
2825            PackageParser.Package scannedPkg) {
2826        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2827            return PackageManager.SIGNATURE_NO_MATCH;
2828        }
2829
2830        ArraySet<Signature> existingSet = new ArraySet<Signature>();
2831        for (Signature sig : existingSigs.mSignatures) {
2832            existingSet.add(sig);
2833        }
2834        ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>();
2835        for (Signature sig : scannedPkg.mSignatures) {
2836            try {
2837                Signature[] chainSignatures = sig.getChainSignatures();
2838                for (Signature chainSig : chainSignatures) {
2839                    scannedCompatSet.add(chainSig);
2840                }
2841            } catch (CertificateEncodingException e) {
2842                scannedCompatSet.add(sig);
2843            }
2844        }
2845        /*
2846         * Make sure the expanded scanned set contains all signatures in the
2847         * existing one.
2848         */
2849        if (scannedCompatSet.equals(existingSet)) {
2850            // Migrate the old signatures to the new scheme.
2851            existingSigs.assignSignatures(scannedPkg.mSignatures);
2852            // The new KeySets will be re-added later in the scanning process.
2853            synchronized (mPackages) {
2854                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2855            }
2856            return PackageManager.SIGNATURE_MATCH;
2857        }
2858        return PackageManager.SIGNATURE_NO_MATCH;
2859    }
2860
2861    @Override
2862    public String[] getPackagesForUid(int uid) {
2863        uid = UserHandle.getAppId(uid);
2864        // reader
2865        synchronized (mPackages) {
2866            Object obj = mSettings.getUserIdLPr(uid);
2867            if (obj instanceof SharedUserSetting) {
2868                final SharedUserSetting sus = (SharedUserSetting) obj;
2869                final int N = sus.packages.size();
2870                final String[] res = new String[N];
2871                final Iterator<PackageSetting> it = sus.packages.iterator();
2872                int i = 0;
2873                while (it.hasNext()) {
2874                    res[i++] = it.next().name;
2875                }
2876                return res;
2877            } else if (obj instanceof PackageSetting) {
2878                final PackageSetting ps = (PackageSetting) obj;
2879                return new String[] { ps.name };
2880            }
2881        }
2882        return null;
2883    }
2884
2885    @Override
2886    public String getNameForUid(int uid) {
2887        // reader
2888        synchronized (mPackages) {
2889            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2890            if (obj instanceof SharedUserSetting) {
2891                final SharedUserSetting sus = (SharedUserSetting) obj;
2892                return sus.name + ":" + sus.userId;
2893            } else if (obj instanceof PackageSetting) {
2894                final PackageSetting ps = (PackageSetting) obj;
2895                return ps.name;
2896            }
2897        }
2898        return null;
2899    }
2900
2901    @Override
2902    public int getUidForSharedUser(String sharedUserName) {
2903        if(sharedUserName == null) {
2904            return -1;
2905        }
2906        // reader
2907        synchronized (mPackages) {
2908            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2909            if (suid == null) {
2910                return -1;
2911            }
2912            return suid.userId;
2913        }
2914    }
2915
2916    @Override
2917    public int getFlagsForUid(int uid) {
2918        synchronized (mPackages) {
2919            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2920            if (obj instanceof SharedUserSetting) {
2921                final SharedUserSetting sus = (SharedUserSetting) obj;
2922                return sus.pkgFlags;
2923            } else if (obj instanceof PackageSetting) {
2924                final PackageSetting ps = (PackageSetting) obj;
2925                return ps.pkgFlags;
2926            }
2927        }
2928        return 0;
2929    }
2930
2931    @Override
2932    public boolean isUidPrivileged(int uid) {
2933        uid = UserHandle.getAppId(uid);
2934        // reader
2935        synchronized (mPackages) {
2936            Object obj = mSettings.getUserIdLPr(uid);
2937            if (obj instanceof SharedUserSetting) {
2938                final SharedUserSetting sus = (SharedUserSetting) obj;
2939                final Iterator<PackageSetting> it = sus.packages.iterator();
2940                while (it.hasNext()) {
2941                    if (it.next().isPrivileged()) {
2942                        return true;
2943                    }
2944                }
2945            } else if (obj instanceof PackageSetting) {
2946                final PackageSetting ps = (PackageSetting) obj;
2947                return ps.isPrivileged();
2948            }
2949        }
2950        return false;
2951    }
2952
2953    @Override
2954    public String[] getAppOpPermissionPackages(String permissionName) {
2955        synchronized (mPackages) {
2956            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2957            if (pkgs == null) {
2958                return null;
2959            }
2960            return pkgs.toArray(new String[pkgs.size()]);
2961        }
2962    }
2963
2964    @Override
2965    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2966            int flags, int userId) {
2967        if (!sUserManager.exists(userId)) return null;
2968        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2969        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2970        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2971    }
2972
2973    @Override
2974    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2975            IntentFilter filter, int match, ComponentName activity) {
2976        final int userId = UserHandle.getCallingUserId();
2977        if (DEBUG_PREFERRED) {
2978            Log.v(TAG, "setLastChosenActivity intent=" + intent
2979                + " resolvedType=" + resolvedType
2980                + " flags=" + flags
2981                + " filter=" + filter
2982                + " match=" + match
2983                + " activity=" + activity);
2984            filter.dump(new PrintStreamPrinter(System.out), "    ");
2985        }
2986        intent.setComponent(null);
2987        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2988        // Find any earlier preferred or last chosen entries and nuke them
2989        findPreferredActivity(intent, resolvedType,
2990                flags, query, 0, false, true, false, userId);
2991        // Add the new activity as the last chosen for this filter
2992        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2993                "Setting last chosen");
2994    }
2995
2996    @Override
2997    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2998        final int userId = UserHandle.getCallingUserId();
2999        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3000        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3001        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3002                false, false, false, userId);
3003    }
3004
3005    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3006            int flags, List<ResolveInfo> query, int userId) {
3007        if (query != null) {
3008            final int N = query.size();
3009            if (N == 1) {
3010                return query.get(0);
3011            } else if (N > 1) {
3012                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3013                // If there is more than one activity with the same priority,
3014                // then let the user decide between them.
3015                ResolveInfo r0 = query.get(0);
3016                ResolveInfo r1 = query.get(1);
3017                if (DEBUG_INTENT_MATCHING || debug) {
3018                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3019                            + r1.activityInfo.name + "=" + r1.priority);
3020                }
3021                // If the first activity has a higher priority, or a different
3022                // default, then it is always desireable to pick it.
3023                if (r0.priority != r1.priority
3024                        || r0.preferredOrder != r1.preferredOrder
3025                        || r0.isDefault != r1.isDefault) {
3026                    return query.get(0);
3027                }
3028                // If we have saved a preference for a preferred activity for
3029                // this Intent, use that.
3030                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3031                        flags, query, r0.priority, true, false, debug, userId);
3032                if (ri != null) {
3033                    return ri;
3034                }
3035                if (userId != 0) {
3036                    ri = new ResolveInfo(mResolveInfo);
3037                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3038                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3039                            ri.activityInfo.applicationInfo);
3040                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3041                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3042                    return ri;
3043                }
3044                return mResolveInfo;
3045            }
3046        }
3047        return null;
3048    }
3049
3050    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3051            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3052        final int N = query.size();
3053        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3054                .get(userId);
3055        // Get the list of persistent preferred activities that handle the intent
3056        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3057        List<PersistentPreferredActivity> pprefs = ppir != null
3058                ? ppir.queryIntent(intent, resolvedType,
3059                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3060                : null;
3061        if (pprefs != null && pprefs.size() > 0) {
3062            final int M = pprefs.size();
3063            for (int i=0; i<M; i++) {
3064                final PersistentPreferredActivity ppa = pprefs.get(i);
3065                if (DEBUG_PREFERRED || debug) {
3066                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3067                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3068                            + "\n  component=" + ppa.mComponent);
3069                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3070                }
3071                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3072                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3073                if (DEBUG_PREFERRED || debug) {
3074                    Slog.v(TAG, "Found persistent preferred activity:");
3075                    if (ai != null) {
3076                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3077                    } else {
3078                        Slog.v(TAG, "  null");
3079                    }
3080                }
3081                if (ai == null) {
3082                    // This previously registered persistent preferred activity
3083                    // component is no longer known. Ignore it and do NOT remove it.
3084                    continue;
3085                }
3086                for (int j=0; j<N; j++) {
3087                    final ResolveInfo ri = query.get(j);
3088                    if (!ri.activityInfo.applicationInfo.packageName
3089                            .equals(ai.applicationInfo.packageName)) {
3090                        continue;
3091                    }
3092                    if (!ri.activityInfo.name.equals(ai.name)) {
3093                        continue;
3094                    }
3095                    //  Found a persistent preference that can handle the intent.
3096                    if (DEBUG_PREFERRED || debug) {
3097                        Slog.v(TAG, "Returning persistent preferred activity: " +
3098                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3099                    }
3100                    return ri;
3101                }
3102            }
3103        }
3104        return null;
3105    }
3106
3107    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3108            List<ResolveInfo> query, int priority, boolean always,
3109            boolean removeMatches, boolean debug, int userId) {
3110        if (!sUserManager.exists(userId)) return null;
3111        // writer
3112        synchronized (mPackages) {
3113            if (intent.getSelector() != null) {
3114                intent = intent.getSelector();
3115            }
3116            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3117
3118            // Try to find a matching persistent preferred activity.
3119            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3120                    debug, userId);
3121
3122            // If a persistent preferred activity matched, use it.
3123            if (pri != null) {
3124                return pri;
3125            }
3126
3127            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3128            // Get the list of preferred activities that handle the intent
3129            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3130            List<PreferredActivity> prefs = pir != null
3131                    ? pir.queryIntent(intent, resolvedType,
3132                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3133                    : null;
3134            if (prefs != null && prefs.size() > 0) {
3135                boolean changed = false;
3136                try {
3137                    // First figure out how good the original match set is.
3138                    // We will only allow preferred activities that came
3139                    // from the same match quality.
3140                    int match = 0;
3141
3142                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3143
3144                    final int N = query.size();
3145                    for (int j=0; j<N; j++) {
3146                        final ResolveInfo ri = query.get(j);
3147                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3148                                + ": 0x" + Integer.toHexString(match));
3149                        if (ri.match > match) {
3150                            match = ri.match;
3151                        }
3152                    }
3153
3154                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3155                            + Integer.toHexString(match));
3156
3157                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3158                    final int M = prefs.size();
3159                    for (int i=0; i<M; i++) {
3160                        final PreferredActivity pa = prefs.get(i);
3161                        if (DEBUG_PREFERRED || debug) {
3162                            Slog.v(TAG, "Checking PreferredActivity ds="
3163                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3164                                    + "\n  component=" + pa.mPref.mComponent);
3165                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3166                        }
3167                        if (pa.mPref.mMatch != match) {
3168                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3169                                    + Integer.toHexString(pa.mPref.mMatch));
3170                            continue;
3171                        }
3172                        // If it's not an "always" type preferred activity and that's what we're
3173                        // looking for, skip it.
3174                        if (always && !pa.mPref.mAlways) {
3175                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3176                            continue;
3177                        }
3178                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3179                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3180                        if (DEBUG_PREFERRED || debug) {
3181                            Slog.v(TAG, "Found preferred activity:");
3182                            if (ai != null) {
3183                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3184                            } else {
3185                                Slog.v(TAG, "  null");
3186                            }
3187                        }
3188                        if (ai == null) {
3189                            // This previously registered preferred activity
3190                            // component is no longer known.  Most likely an update
3191                            // to the app was installed and in the new version this
3192                            // component no longer exists.  Clean it up by removing
3193                            // it from the preferred activities list, and skip it.
3194                            Slog.w(TAG, "Removing dangling preferred activity: "
3195                                    + pa.mPref.mComponent);
3196                            pir.removeFilter(pa);
3197                            changed = true;
3198                            continue;
3199                        }
3200                        for (int j=0; j<N; j++) {
3201                            final ResolveInfo ri = query.get(j);
3202                            if (!ri.activityInfo.applicationInfo.packageName
3203                                    .equals(ai.applicationInfo.packageName)) {
3204                                continue;
3205                            }
3206                            if (!ri.activityInfo.name.equals(ai.name)) {
3207                                continue;
3208                            }
3209
3210                            if (removeMatches) {
3211                                pir.removeFilter(pa);
3212                                changed = true;
3213                                if (DEBUG_PREFERRED) {
3214                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3215                                }
3216                                break;
3217                            }
3218
3219                            // Okay we found a previously set preferred or last chosen app.
3220                            // If the result set is different from when this
3221                            // was created, we need to clear it and re-ask the
3222                            // user their preference, if we're looking for an "always" type entry.
3223                            if (always && !pa.mPref.sameSet(query, priority)) {
3224                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3225                                        + intent + " type " + resolvedType);
3226                                if (DEBUG_PREFERRED) {
3227                                    Slog.v(TAG, "Removing preferred activity since set changed "
3228                                            + pa.mPref.mComponent);
3229                                }
3230                                pir.removeFilter(pa);
3231                                // Re-add the filter as a "last chosen" entry (!always)
3232                                PreferredActivity lastChosen = new PreferredActivity(
3233                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3234                                pir.addFilter(lastChosen);
3235                                changed = true;
3236                                return null;
3237                            }
3238
3239                            // Yay! Either the set matched or we're looking for the last chosen
3240                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3241                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3242                            return ri;
3243                        }
3244                    }
3245                } finally {
3246                    if (changed) {
3247                        if (DEBUG_PREFERRED) {
3248                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3249                        }
3250                        mSettings.writePackageRestrictionsLPr(userId);
3251                    }
3252                }
3253            }
3254        }
3255        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3256        return null;
3257    }
3258
3259    /*
3260     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3261     */
3262    @Override
3263    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3264            int targetUserId) {
3265        mContext.enforceCallingOrSelfPermission(
3266                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3267        List<CrossProfileIntentFilter> matches =
3268                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3269        if (matches != null) {
3270            int size = matches.size();
3271            for (int i = 0; i < size; i++) {
3272                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3273            }
3274        }
3275        return false;
3276    }
3277
3278    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3279            String resolvedType, int userId) {
3280        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3281        if (resolver != null) {
3282            return resolver.queryIntent(intent, resolvedType, false, userId);
3283        }
3284        return null;
3285    }
3286
3287    @Override
3288    public List<ResolveInfo> queryIntentActivities(Intent intent,
3289            String resolvedType, int flags, int userId) {
3290        if (!sUserManager.exists(userId)) return Collections.emptyList();
3291        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3292        ComponentName comp = intent.getComponent();
3293        if (comp == null) {
3294            if (intent.getSelector() != null) {
3295                intent = intent.getSelector();
3296                comp = intent.getComponent();
3297            }
3298        }
3299
3300        if (comp != null) {
3301            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3302            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3303            if (ai != null) {
3304                final ResolveInfo ri = new ResolveInfo();
3305                ri.activityInfo = ai;
3306                list.add(ri);
3307            }
3308            return list;
3309        }
3310
3311        // reader
3312        synchronized (mPackages) {
3313            final String pkgName = intent.getPackage();
3314            if (pkgName == null) {
3315                List<CrossProfileIntentFilter> matchingFilters =
3316                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3317                // Check for results that need to skip the current profile.
3318                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3319                        resolvedType, flags, userId);
3320                if (resolveInfo != null) {
3321                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3322                    result.add(resolveInfo);
3323                    return result;
3324                }
3325                // Check for cross profile results.
3326                resolveInfo = queryCrossProfileIntents(
3327                        matchingFilters, intent, resolvedType, flags, userId);
3328
3329                // Check for results in the current profile.
3330                List<ResolveInfo> result = mActivities.queryIntent(
3331                        intent, resolvedType, flags, userId);
3332                if (resolveInfo != null) {
3333                    result.add(resolveInfo);
3334                    Collections.sort(result, mResolvePrioritySorter);
3335                }
3336                return result;
3337            }
3338            final PackageParser.Package pkg = mPackages.get(pkgName);
3339            if (pkg != null) {
3340                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3341                        pkg.activities, userId);
3342            }
3343            return new ArrayList<ResolveInfo>();
3344        }
3345    }
3346
3347    private ResolveInfo querySkipCurrentProfileIntents(
3348            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3349            int flags, int sourceUserId) {
3350        if (matchingFilters != null) {
3351            int size = matchingFilters.size();
3352            for (int i = 0; i < size; i ++) {
3353                CrossProfileIntentFilter filter = matchingFilters.get(i);
3354                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3355                    // Checking if there are activities in the target user that can handle the
3356                    // intent.
3357                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3358                            flags, sourceUserId);
3359                    if (resolveInfo != null) {
3360                        return resolveInfo;
3361                    }
3362                }
3363            }
3364        }
3365        return null;
3366    }
3367
3368    // Return matching ResolveInfo if any for skip current profile intent filters.
3369    private ResolveInfo queryCrossProfileIntents(
3370            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3371            int flags, int sourceUserId) {
3372        if (matchingFilters != null) {
3373            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3374            // match the same intent. For performance reasons, it is better not to
3375            // run queryIntent twice for the same userId
3376            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3377            int size = matchingFilters.size();
3378            for (int i = 0; i < size; i++) {
3379                CrossProfileIntentFilter filter = matchingFilters.get(i);
3380                int targetUserId = filter.getTargetUserId();
3381                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3382                        && !alreadyTriedUserIds.get(targetUserId)) {
3383                    // Checking if there are activities in the target user that can handle the
3384                    // intent.
3385                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3386                            flags, sourceUserId);
3387                    if (resolveInfo != null) return resolveInfo;
3388                    alreadyTriedUserIds.put(targetUserId, true);
3389                }
3390            }
3391        }
3392        return null;
3393    }
3394
3395    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3396            String resolvedType, int flags, int sourceUserId) {
3397        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3398                resolvedType, flags, filter.getTargetUserId());
3399        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3400            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3401        }
3402        return null;
3403    }
3404
3405    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3406            int sourceUserId, int targetUserId) {
3407        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3408        String className;
3409        if (targetUserId == UserHandle.USER_OWNER) {
3410            className = FORWARD_INTENT_TO_USER_OWNER;
3411        } else {
3412            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3413        }
3414        ComponentName forwardingActivityComponentName = new ComponentName(
3415                mAndroidApplication.packageName, className);
3416        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3417                sourceUserId);
3418        if (targetUserId == UserHandle.USER_OWNER) {
3419            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3420            forwardingResolveInfo.noResourceId = true;
3421        }
3422        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3423        forwardingResolveInfo.priority = 0;
3424        forwardingResolveInfo.preferredOrder = 0;
3425        forwardingResolveInfo.match = 0;
3426        forwardingResolveInfo.isDefault = true;
3427        forwardingResolveInfo.filter = filter;
3428        forwardingResolveInfo.targetUserId = targetUserId;
3429        return forwardingResolveInfo;
3430    }
3431
3432    @Override
3433    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3434            Intent[] specifics, String[] specificTypes, Intent intent,
3435            String resolvedType, int flags, int userId) {
3436        if (!sUserManager.exists(userId)) return Collections.emptyList();
3437        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3438                false, "query intent activity options");
3439        final String resultsAction = intent.getAction();
3440
3441        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3442                | PackageManager.GET_RESOLVED_FILTER, userId);
3443
3444        if (DEBUG_INTENT_MATCHING) {
3445            Log.v(TAG, "Query " + intent + ": " + results);
3446        }
3447
3448        int specificsPos = 0;
3449        int N;
3450
3451        // todo: note that the algorithm used here is O(N^2).  This
3452        // isn't a problem in our current environment, but if we start running
3453        // into situations where we have more than 5 or 10 matches then this
3454        // should probably be changed to something smarter...
3455
3456        // First we go through and resolve each of the specific items
3457        // that were supplied, taking care of removing any corresponding
3458        // duplicate items in the generic resolve list.
3459        if (specifics != null) {
3460            for (int i=0; i<specifics.length; i++) {
3461                final Intent sintent = specifics[i];
3462                if (sintent == null) {
3463                    continue;
3464                }
3465
3466                if (DEBUG_INTENT_MATCHING) {
3467                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3468                }
3469
3470                String action = sintent.getAction();
3471                if (resultsAction != null && resultsAction.equals(action)) {
3472                    // If this action was explicitly requested, then don't
3473                    // remove things that have it.
3474                    action = null;
3475                }
3476
3477                ResolveInfo ri = null;
3478                ActivityInfo ai = null;
3479
3480                ComponentName comp = sintent.getComponent();
3481                if (comp == null) {
3482                    ri = resolveIntent(
3483                        sintent,
3484                        specificTypes != null ? specificTypes[i] : null,
3485                            flags, userId);
3486                    if (ri == null) {
3487                        continue;
3488                    }
3489                    if (ri == mResolveInfo) {
3490                        // ACK!  Must do something better with this.
3491                    }
3492                    ai = ri.activityInfo;
3493                    comp = new ComponentName(ai.applicationInfo.packageName,
3494                            ai.name);
3495                } else {
3496                    ai = getActivityInfo(comp, flags, userId);
3497                    if (ai == null) {
3498                        continue;
3499                    }
3500                }
3501
3502                // Look for any generic query activities that are duplicates
3503                // of this specific one, and remove them from the results.
3504                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3505                N = results.size();
3506                int j;
3507                for (j=specificsPos; j<N; j++) {
3508                    ResolveInfo sri = results.get(j);
3509                    if ((sri.activityInfo.name.equals(comp.getClassName())
3510                            && sri.activityInfo.applicationInfo.packageName.equals(
3511                                    comp.getPackageName()))
3512                        || (action != null && sri.filter.matchAction(action))) {
3513                        results.remove(j);
3514                        if (DEBUG_INTENT_MATCHING) Log.v(
3515                            TAG, "Removing duplicate item from " + j
3516                            + " due to specific " + specificsPos);
3517                        if (ri == null) {
3518                            ri = sri;
3519                        }
3520                        j--;
3521                        N--;
3522                    }
3523                }
3524
3525                // Add this specific item to its proper place.
3526                if (ri == null) {
3527                    ri = new ResolveInfo();
3528                    ri.activityInfo = ai;
3529                }
3530                results.add(specificsPos, ri);
3531                ri.specificIndex = i;
3532                specificsPos++;
3533            }
3534        }
3535
3536        // Now we go through the remaining generic results and remove any
3537        // duplicate actions that are found here.
3538        N = results.size();
3539        for (int i=specificsPos; i<N-1; i++) {
3540            final ResolveInfo rii = results.get(i);
3541            if (rii.filter == null) {
3542                continue;
3543            }
3544
3545            // Iterate over all of the actions of this result's intent
3546            // filter...  typically this should be just one.
3547            final Iterator<String> it = rii.filter.actionsIterator();
3548            if (it == null) {
3549                continue;
3550            }
3551            while (it.hasNext()) {
3552                final String action = it.next();
3553                if (resultsAction != null && resultsAction.equals(action)) {
3554                    // If this action was explicitly requested, then don't
3555                    // remove things that have it.
3556                    continue;
3557                }
3558                for (int j=i+1; j<N; j++) {
3559                    final ResolveInfo rij = results.get(j);
3560                    if (rij.filter != null && rij.filter.hasAction(action)) {
3561                        results.remove(j);
3562                        if (DEBUG_INTENT_MATCHING) Log.v(
3563                            TAG, "Removing duplicate item from " + j
3564                            + " due to action " + action + " at " + i);
3565                        j--;
3566                        N--;
3567                    }
3568                }
3569            }
3570
3571            // If the caller didn't request filter information, drop it now
3572            // so we don't have to marshall/unmarshall it.
3573            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3574                rii.filter = null;
3575            }
3576        }
3577
3578        // Filter out the caller activity if so requested.
3579        if (caller != null) {
3580            N = results.size();
3581            for (int i=0; i<N; i++) {
3582                ActivityInfo ainfo = results.get(i).activityInfo;
3583                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3584                        && caller.getClassName().equals(ainfo.name)) {
3585                    results.remove(i);
3586                    break;
3587                }
3588            }
3589        }
3590
3591        // If the caller didn't request filter information,
3592        // drop them now so we don't have to
3593        // marshall/unmarshall it.
3594        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3595            N = results.size();
3596            for (int i=0; i<N; i++) {
3597                results.get(i).filter = null;
3598            }
3599        }
3600
3601        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3602        return results;
3603    }
3604
3605    @Override
3606    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3607            int userId) {
3608        if (!sUserManager.exists(userId)) return Collections.emptyList();
3609        ComponentName comp = intent.getComponent();
3610        if (comp == null) {
3611            if (intent.getSelector() != null) {
3612                intent = intent.getSelector();
3613                comp = intent.getComponent();
3614            }
3615        }
3616        if (comp != null) {
3617            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3618            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3619            if (ai != null) {
3620                ResolveInfo ri = new ResolveInfo();
3621                ri.activityInfo = ai;
3622                list.add(ri);
3623            }
3624            return list;
3625        }
3626
3627        // reader
3628        synchronized (mPackages) {
3629            String pkgName = intent.getPackage();
3630            if (pkgName == null) {
3631                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3632            }
3633            final PackageParser.Package pkg = mPackages.get(pkgName);
3634            if (pkg != null) {
3635                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3636                        userId);
3637            }
3638            return null;
3639        }
3640    }
3641
3642    @Override
3643    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3644        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3645        if (!sUserManager.exists(userId)) return null;
3646        if (query != null) {
3647            if (query.size() >= 1) {
3648                // If there is more than one service with the same priority,
3649                // just arbitrarily pick the first one.
3650                return query.get(0);
3651            }
3652        }
3653        return null;
3654    }
3655
3656    @Override
3657    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3658            int userId) {
3659        if (!sUserManager.exists(userId)) return Collections.emptyList();
3660        ComponentName comp = intent.getComponent();
3661        if (comp == null) {
3662            if (intent.getSelector() != null) {
3663                intent = intent.getSelector();
3664                comp = intent.getComponent();
3665            }
3666        }
3667        if (comp != null) {
3668            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3669            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3670            if (si != null) {
3671                final ResolveInfo ri = new ResolveInfo();
3672                ri.serviceInfo = si;
3673                list.add(ri);
3674            }
3675            return list;
3676        }
3677
3678        // reader
3679        synchronized (mPackages) {
3680            String pkgName = intent.getPackage();
3681            if (pkgName == null) {
3682                return mServices.queryIntent(intent, resolvedType, flags, userId);
3683            }
3684            final PackageParser.Package pkg = mPackages.get(pkgName);
3685            if (pkg != null) {
3686                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3687                        userId);
3688            }
3689            return null;
3690        }
3691    }
3692
3693    @Override
3694    public List<ResolveInfo> queryIntentContentProviders(
3695            Intent intent, String resolvedType, int flags, int userId) {
3696        if (!sUserManager.exists(userId)) return Collections.emptyList();
3697        ComponentName comp = intent.getComponent();
3698        if (comp == null) {
3699            if (intent.getSelector() != null) {
3700                intent = intent.getSelector();
3701                comp = intent.getComponent();
3702            }
3703        }
3704        if (comp != null) {
3705            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3706            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3707            if (pi != null) {
3708                final ResolveInfo ri = new ResolveInfo();
3709                ri.providerInfo = pi;
3710                list.add(ri);
3711            }
3712            return list;
3713        }
3714
3715        // reader
3716        synchronized (mPackages) {
3717            String pkgName = intent.getPackage();
3718            if (pkgName == null) {
3719                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3720            }
3721            final PackageParser.Package pkg = mPackages.get(pkgName);
3722            if (pkg != null) {
3723                return mProviders.queryIntentForPackage(
3724                        intent, resolvedType, flags, pkg.providers, userId);
3725            }
3726            return null;
3727        }
3728    }
3729
3730    @Override
3731    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3732        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3733
3734        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3735
3736        // writer
3737        synchronized (mPackages) {
3738            ArrayList<PackageInfo> list;
3739            if (listUninstalled) {
3740                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3741                for (PackageSetting ps : mSettings.mPackages.values()) {
3742                    PackageInfo pi;
3743                    if (ps.pkg != null) {
3744                        pi = generatePackageInfo(ps.pkg, flags, userId);
3745                    } else {
3746                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3747                    }
3748                    if (pi != null) {
3749                        list.add(pi);
3750                    }
3751                }
3752            } else {
3753                list = new ArrayList<PackageInfo>(mPackages.size());
3754                for (PackageParser.Package p : mPackages.values()) {
3755                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3756                    if (pi != null) {
3757                        list.add(pi);
3758                    }
3759                }
3760            }
3761
3762            return new ParceledListSlice<PackageInfo>(list);
3763        }
3764    }
3765
3766    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3767            String[] permissions, boolean[] tmp, int flags, int userId) {
3768        int numMatch = 0;
3769        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3770        for (int i=0; i<permissions.length; i++) {
3771            if (gp.grantedPermissions.contains(permissions[i])) {
3772                tmp[i] = true;
3773                numMatch++;
3774            } else {
3775                tmp[i] = false;
3776            }
3777        }
3778        if (numMatch == 0) {
3779            return;
3780        }
3781        PackageInfo pi;
3782        if (ps.pkg != null) {
3783            pi = generatePackageInfo(ps.pkg, flags, userId);
3784        } else {
3785            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3786        }
3787        // The above might return null in cases of uninstalled apps or install-state
3788        // skew across users/profiles.
3789        if (pi != null) {
3790            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3791                if (numMatch == permissions.length) {
3792                    pi.requestedPermissions = permissions;
3793                } else {
3794                    pi.requestedPermissions = new String[numMatch];
3795                    numMatch = 0;
3796                    for (int i=0; i<permissions.length; i++) {
3797                        if (tmp[i]) {
3798                            pi.requestedPermissions[numMatch] = permissions[i];
3799                            numMatch++;
3800                        }
3801                    }
3802                }
3803            }
3804            list.add(pi);
3805        }
3806    }
3807
3808    @Override
3809    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3810            String[] permissions, int flags, int userId) {
3811        if (!sUserManager.exists(userId)) return null;
3812        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3813
3814        // writer
3815        synchronized (mPackages) {
3816            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3817            boolean[] tmpBools = new boolean[permissions.length];
3818            if (listUninstalled) {
3819                for (PackageSetting ps : mSettings.mPackages.values()) {
3820                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3821                }
3822            } else {
3823                for (PackageParser.Package pkg : mPackages.values()) {
3824                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3825                    if (ps != null) {
3826                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3827                                userId);
3828                    }
3829                }
3830            }
3831
3832            return new ParceledListSlice<PackageInfo>(list);
3833        }
3834    }
3835
3836    @Override
3837    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3838        if (!sUserManager.exists(userId)) return null;
3839        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3840
3841        // writer
3842        synchronized (mPackages) {
3843            ArrayList<ApplicationInfo> list;
3844            if (listUninstalled) {
3845                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3846                for (PackageSetting ps : mSettings.mPackages.values()) {
3847                    ApplicationInfo ai;
3848                    if (ps.pkg != null) {
3849                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3850                                ps.readUserState(userId), userId);
3851                    } else {
3852                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3853                    }
3854                    if (ai != null) {
3855                        list.add(ai);
3856                    }
3857                }
3858            } else {
3859                list = new ArrayList<ApplicationInfo>(mPackages.size());
3860                for (PackageParser.Package p : mPackages.values()) {
3861                    if (p.mExtras != null) {
3862                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3863                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3864                        if (ai != null) {
3865                            list.add(ai);
3866                        }
3867                    }
3868                }
3869            }
3870
3871            return new ParceledListSlice<ApplicationInfo>(list);
3872        }
3873    }
3874
3875    public List<ApplicationInfo> getPersistentApplications(int flags) {
3876        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3877
3878        // reader
3879        synchronized (mPackages) {
3880            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3881            final int userId = UserHandle.getCallingUserId();
3882            while (i.hasNext()) {
3883                final PackageParser.Package p = i.next();
3884                if (p.applicationInfo != null
3885                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3886                        && (!mSafeMode || isSystemApp(p))) {
3887                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3888                    if (ps != null) {
3889                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3890                                ps.readUserState(userId), userId);
3891                        if (ai != null) {
3892                            finalList.add(ai);
3893                        }
3894                    }
3895                }
3896            }
3897        }
3898
3899        return finalList;
3900    }
3901
3902    @Override
3903    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3904        if (!sUserManager.exists(userId)) return null;
3905        // reader
3906        synchronized (mPackages) {
3907            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3908            PackageSetting ps = provider != null
3909                    ? mSettings.mPackages.get(provider.owner.packageName)
3910                    : null;
3911            return ps != null
3912                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3913                    && (!mSafeMode || (provider.info.applicationInfo.flags
3914                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3915                    ? PackageParser.generateProviderInfo(provider, flags,
3916                            ps.readUserState(userId), userId)
3917                    : null;
3918        }
3919    }
3920
3921    /**
3922     * @deprecated
3923     */
3924    @Deprecated
3925    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3926        // reader
3927        synchronized (mPackages) {
3928            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3929                    .entrySet().iterator();
3930            final int userId = UserHandle.getCallingUserId();
3931            while (i.hasNext()) {
3932                Map.Entry<String, PackageParser.Provider> entry = i.next();
3933                PackageParser.Provider p = entry.getValue();
3934                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3935
3936                if (ps != null && p.syncable
3937                        && (!mSafeMode || (p.info.applicationInfo.flags
3938                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3939                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3940                            ps.readUserState(userId), userId);
3941                    if (info != null) {
3942                        outNames.add(entry.getKey());
3943                        outInfo.add(info);
3944                    }
3945                }
3946            }
3947        }
3948    }
3949
3950    @Override
3951    public List<ProviderInfo> queryContentProviders(String processName,
3952            int uid, int flags) {
3953        ArrayList<ProviderInfo> finalList = null;
3954        // reader
3955        synchronized (mPackages) {
3956            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3957            final int userId = processName != null ?
3958                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3959            while (i.hasNext()) {
3960                final PackageParser.Provider p = i.next();
3961                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3962                if (ps != null && p.info.authority != null
3963                        && (processName == null
3964                                || (p.info.processName.equals(processName)
3965                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3966                        && mSettings.isEnabledLPr(p.info, flags, userId)
3967                        && (!mSafeMode
3968                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3969                    if (finalList == null) {
3970                        finalList = new ArrayList<ProviderInfo>(3);
3971                    }
3972                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3973                            ps.readUserState(userId), userId);
3974                    if (info != null) {
3975                        finalList.add(info);
3976                    }
3977                }
3978            }
3979        }
3980
3981        if (finalList != null) {
3982            Collections.sort(finalList, mProviderInitOrderSorter);
3983        }
3984
3985        return finalList;
3986    }
3987
3988    @Override
3989    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3990            int flags) {
3991        // reader
3992        synchronized (mPackages) {
3993            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3994            return PackageParser.generateInstrumentationInfo(i, flags);
3995        }
3996    }
3997
3998    @Override
3999    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4000            int flags) {
4001        ArrayList<InstrumentationInfo> finalList =
4002            new ArrayList<InstrumentationInfo>();
4003
4004        // reader
4005        synchronized (mPackages) {
4006            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4007            while (i.hasNext()) {
4008                final PackageParser.Instrumentation p = i.next();
4009                if (targetPackage == null
4010                        || targetPackage.equals(p.info.targetPackage)) {
4011                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4012                            flags);
4013                    if (ii != null) {
4014                        finalList.add(ii);
4015                    }
4016                }
4017            }
4018        }
4019
4020        return finalList;
4021    }
4022
4023    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4024        ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4025        if (overlays == null) {
4026            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4027            return;
4028        }
4029        for (PackageParser.Package opkg : overlays.values()) {
4030            // Not much to do if idmap fails: we already logged the error
4031            // and we certainly don't want to abort installation of pkg simply
4032            // because an overlay didn't fit properly. For these reasons,
4033            // ignore the return value of createIdmapForPackagePairLI.
4034            createIdmapForPackagePairLI(pkg, opkg);
4035        }
4036    }
4037
4038    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4039            PackageParser.Package opkg) {
4040        if (!opkg.mTrustedOverlay) {
4041            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4042                    opkg.baseCodePath + ": overlay not trusted");
4043            return false;
4044        }
4045        ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4046        if (overlaySet == null) {
4047            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4048                    opkg.baseCodePath + " but target package has no known overlays");
4049            return false;
4050        }
4051        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4052        // TODO: generate idmap for split APKs
4053        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4054            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4055                    + opkg.baseCodePath);
4056            return false;
4057        }
4058        PackageParser.Package[] overlayArray =
4059            overlaySet.values().toArray(new PackageParser.Package[0]);
4060        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4061            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4062                return p1.mOverlayPriority - p2.mOverlayPriority;
4063            }
4064        };
4065        Arrays.sort(overlayArray, cmp);
4066
4067        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4068        int i = 0;
4069        for (PackageParser.Package p : overlayArray) {
4070            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4071        }
4072        return true;
4073    }
4074
4075    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4076        final File[] files = dir.listFiles();
4077        if (ArrayUtils.isEmpty(files)) {
4078            Log.d(TAG, "No files in app dir " + dir);
4079            return;
4080        }
4081
4082        if (DEBUG_PACKAGE_SCANNING) {
4083            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4084                    + " flags=0x" + Integer.toHexString(parseFlags));
4085        }
4086
4087        for (File file : files) {
4088            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4089                    && !PackageInstallerService.isStageName(file.getName());
4090            if (!isPackage) {
4091                // Ignore entries which are not packages
4092                continue;
4093            }
4094            try {
4095                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4096                        scanFlags, currentTime, null);
4097            } catch (PackageManagerException e) {
4098                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4099
4100                // Delete invalid userdata apps
4101                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4102                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4103                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4104                    if (file.isDirectory()) {
4105                        FileUtils.deleteContents(file);
4106                    }
4107                    file.delete();
4108                }
4109            }
4110        }
4111    }
4112
4113    private static File getSettingsProblemFile() {
4114        File dataDir = Environment.getDataDirectory();
4115        File systemDir = new File(dataDir, "system");
4116        File fname = new File(systemDir, "uiderrors.txt");
4117        return fname;
4118    }
4119
4120    static void reportSettingsProblem(int priority, String msg) {
4121        logCriticalInfo(priority, msg);
4122    }
4123
4124    static void logCriticalInfo(int priority, String msg) {
4125        Slog.println(priority, TAG, msg);
4126        EventLogTags.writePmCriticalInfo(msg);
4127        try {
4128            File fname = getSettingsProblemFile();
4129            FileOutputStream out = new FileOutputStream(fname, true);
4130            PrintWriter pw = new FastPrintWriter(out);
4131            SimpleDateFormat formatter = new SimpleDateFormat();
4132            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4133            pw.println(dateString + ": " + msg);
4134            pw.close();
4135            FileUtils.setPermissions(
4136                    fname.toString(),
4137                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4138                    -1, -1);
4139        } catch (java.io.IOException e) {
4140        }
4141    }
4142
4143    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4144            PackageParser.Package pkg, File srcFile, int parseFlags)
4145            throws PackageManagerException {
4146        if (ps != null
4147                && ps.codePath.equals(srcFile)
4148                && ps.timeStamp == srcFile.lastModified()
4149                && !isCompatSignatureUpdateNeeded(pkg)) {
4150            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4151            if (ps.signatures.mSignatures != null
4152                    && ps.signatures.mSignatures.length != 0
4153                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4154                // Optimization: reuse the existing cached certificates
4155                // if the package appears to be unchanged.
4156                pkg.mSignatures = ps.signatures.mSignatures;
4157                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4158                synchronized (mPackages) {
4159                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4160                }
4161                return;
4162            }
4163
4164            Slog.w(TAG, "PackageSetting for " + ps.name
4165                    + " is missing signatures.  Collecting certs again to recover them.");
4166        } else {
4167            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4168        }
4169
4170        try {
4171            pp.collectCertificates(pkg, parseFlags);
4172            pp.collectManifestDigest(pkg);
4173        } catch (PackageParserException e) {
4174            throw PackageManagerException.from(e);
4175        }
4176    }
4177
4178    /*
4179     *  Scan a package and return the newly parsed package.
4180     *  Returns null in case of errors and the error code is stored in mLastScanError
4181     */
4182    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4183            long currentTime, UserHandle user) throws PackageManagerException {
4184        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4185        parseFlags |= mDefParseFlags;
4186        PackageParser pp = new PackageParser();
4187        pp.setSeparateProcesses(mSeparateProcesses);
4188        pp.setOnlyCoreApps(mOnlyCore);
4189        pp.setDisplayMetrics(mMetrics);
4190
4191        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4192            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4193        }
4194
4195        final PackageParser.Package pkg;
4196        try {
4197            pkg = pp.parsePackage(scanFile, parseFlags);
4198        } catch (PackageParserException e) {
4199            throw PackageManagerException.from(e);
4200        }
4201
4202        PackageSetting ps = null;
4203        PackageSetting updatedPkg;
4204        // reader
4205        synchronized (mPackages) {
4206            // Look to see if we already know about this package.
4207            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4208            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4209                // This package has been renamed to its original name.  Let's
4210                // use that.
4211                ps = mSettings.peekPackageLPr(oldName);
4212            }
4213            // If there was no original package, see one for the real package name.
4214            if (ps == null) {
4215                ps = mSettings.peekPackageLPr(pkg.packageName);
4216            }
4217            // Check to see if this package could be hiding/updating a system
4218            // package.  Must look for it either under the original or real
4219            // package name depending on our state.
4220            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4221            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4222        }
4223        boolean updatedPkgBetter = false;
4224        // First check if this is a system package that may involve an update
4225        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4226            if (ps != null && !ps.codePath.equals(scanFile)) {
4227                // The path has changed from what was last scanned...  check the
4228                // version of the new path against what we have stored to determine
4229                // what to do.
4230                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4231                if (pkg.mVersionCode < ps.versionCode) {
4232                    // The system package has been updated and the code path does not match
4233                    // Ignore entry. Skip it.
4234                    logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
4235                            + " ignored: updated version " + ps.versionCode
4236                            + " better than this " + pkg.mVersionCode);
4237                    if (!updatedPkg.codePath.equals(scanFile)) {
4238                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4239                                + ps.name + " changing from " + updatedPkg.codePathString
4240                                + " to " + scanFile);
4241                        updatedPkg.codePath = scanFile;
4242                        updatedPkg.codePathString = scanFile.toString();
4243                        // This is the point at which we know that the system-disk APK
4244                        // for this package has moved during a reboot (e.g. due to an OTA),
4245                        // so we need to reevaluate it for privilege policy.
4246                        if (locationIsPrivileged(scanFile)) {
4247                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4248                        }
4249                    }
4250                    updatedPkg.pkg = pkg;
4251                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4252                } else {
4253                    // The current app on the system partition is better than
4254                    // what we have updated to on the data partition; switch
4255                    // back to the system partition version.
4256                    // At this point, its safely assumed that package installation for
4257                    // apps in system partition will go through. If not there won't be a working
4258                    // version of the app
4259                    // writer
4260                    synchronized (mPackages) {
4261                        // Just remove the loaded entries from package lists.
4262                        mPackages.remove(ps.name);
4263                    }
4264
4265                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4266                            + " reverting from " + ps.codePathString
4267                            + ": new version " + pkg.mVersionCode
4268                            + " better than installed " + ps.versionCode);
4269
4270                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4271                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4272                            getAppDexInstructionSets(ps));
4273                    synchronized (mInstallLock) {
4274                        args.cleanUpResourcesLI();
4275                    }
4276                    synchronized (mPackages) {
4277                        mSettings.enableSystemPackageLPw(ps.name);
4278                    }
4279                    updatedPkgBetter = true;
4280                }
4281            }
4282        }
4283
4284        if (updatedPkg != null) {
4285            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4286            // initially
4287            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4288
4289            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4290            // flag set initially
4291            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4292                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4293            }
4294        }
4295
4296        // Verify certificates against what was last scanned
4297        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4298
4299        /*
4300         * A new system app appeared, but we already had a non-system one of the
4301         * same name installed earlier.
4302         */
4303        boolean shouldHideSystemApp = false;
4304        if (updatedPkg == null && ps != null
4305                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4306            /*
4307             * Check to make sure the signatures match first. If they don't,
4308             * wipe the installed application and its data.
4309             */
4310            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4311                    != PackageManager.SIGNATURE_MATCH) {
4312                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4313                        + " signatures don't match existing userdata copy; removing");
4314                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4315                ps = null;
4316            } else {
4317                /*
4318                 * If the newly-added system app is an older version than the
4319                 * already installed version, hide it. It will be scanned later
4320                 * and re-added like an update.
4321                 */
4322                if (pkg.mVersionCode < ps.versionCode) {
4323                    shouldHideSystemApp = true;
4324                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4325                            + " but new version " + pkg.mVersionCode + " better than installed "
4326                            + ps.versionCode + "; hiding system");
4327                } else {
4328                    /*
4329                     * The newly found system app is a newer version that the
4330                     * one previously installed. Simply remove the
4331                     * already-installed application and replace it with our own
4332                     * while keeping the application data.
4333                     */
4334                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4335                            + " reverting from " + ps.codePathString + ": new version "
4336                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4337                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4338                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4339                            getAppDexInstructionSets(ps));
4340                    synchronized (mInstallLock) {
4341                        args.cleanUpResourcesLI();
4342                    }
4343                }
4344            }
4345        }
4346
4347        // The apk is forward locked (not public) if its code and resources
4348        // are kept in different files. (except for app in either system or
4349        // vendor path).
4350        // TODO grab this value from PackageSettings
4351        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4352            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4353                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4354            }
4355        }
4356
4357        // TODO: extend to support forward-locked splits
4358        String resourcePath = null;
4359        String baseResourcePath = null;
4360        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4361            if (ps != null && ps.resourcePathString != null) {
4362                resourcePath = ps.resourcePathString;
4363                baseResourcePath = ps.resourcePathString;
4364            } else {
4365                // Should not happen at all. Just log an error.
4366                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4367            }
4368        } else {
4369            resourcePath = pkg.codePath;
4370            baseResourcePath = pkg.baseCodePath;
4371        }
4372
4373        // Set application objects path explicitly.
4374        pkg.applicationInfo.setCodePath(pkg.codePath);
4375        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4376        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4377        pkg.applicationInfo.setResourcePath(resourcePath);
4378        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4379        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4380
4381        // Note that we invoke the following method only if we are about to unpack an application
4382        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4383                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4384
4385        /*
4386         * If the system app should be overridden by a previously installed
4387         * data, hide the system app now and let the /data/app scan pick it up
4388         * again.
4389         */
4390        if (shouldHideSystemApp) {
4391            synchronized (mPackages) {
4392                /*
4393                 * We have to grant systems permissions before we hide, because
4394                 * grantPermissions will assume the package update is trying to
4395                 * expand its permissions.
4396                 */
4397                grantPermissionsLPw(pkg, true, pkg.packageName);
4398                mSettings.disableSystemPackageLPw(pkg.packageName);
4399            }
4400        }
4401
4402        return scannedPkg;
4403    }
4404
4405    private static String fixProcessName(String defProcessName,
4406            String processName, int uid) {
4407        if (processName == null) {
4408            return defProcessName;
4409        }
4410        return processName;
4411    }
4412
4413    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4414            throws PackageManagerException {
4415        if (pkgSetting.signatures.mSignatures != null) {
4416            // Already existing package. Make sure signatures match
4417            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4418                    == PackageManager.SIGNATURE_MATCH;
4419            if (!match) {
4420                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4421                        == PackageManager.SIGNATURE_MATCH;
4422            }
4423            if (!match) {
4424                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4425                        + pkg.packageName + " signatures do not match the "
4426                        + "previously installed version; ignoring!");
4427            }
4428        }
4429
4430        // Check for shared user signatures
4431        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4432            // Already existing package. Make sure signatures match
4433            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4434                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4435            if (!match) {
4436                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4437                        == PackageManager.SIGNATURE_MATCH;
4438            }
4439            if (!match) {
4440                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4441                        "Package " + pkg.packageName
4442                        + " has no signatures that match those in shared user "
4443                        + pkgSetting.sharedUser.name + "; ignoring!");
4444            }
4445        }
4446    }
4447
4448    /**
4449     * Enforces that only the system UID or root's UID can call a method exposed
4450     * via Binder.
4451     *
4452     * @param message used as message if SecurityException is thrown
4453     * @throws SecurityException if the caller is not system or root
4454     */
4455    private static final void enforceSystemOrRoot(String message) {
4456        final int uid = Binder.getCallingUid();
4457        if (uid != Process.SYSTEM_UID && uid != 0) {
4458            throw new SecurityException(message);
4459        }
4460    }
4461
4462    @Override
4463    public void performBootDexOpt() {
4464        enforceSystemOrRoot("Only the system can request dexopt be performed");
4465
4466        final ArraySet<PackageParser.Package> pkgs;
4467        synchronized (mPackages) {
4468            pkgs = mDeferredDexOpt;
4469            mDeferredDexOpt = null;
4470        }
4471
4472        if (pkgs != null) {
4473            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4474            // in case the device runs out of space.
4475            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4476            // Give priority to core apps.
4477            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4478                PackageParser.Package pkg = it.next();
4479                if (pkg.coreApp) {
4480                    if (DEBUG_DEXOPT) {
4481                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4482                    }
4483                    sortedPkgs.add(pkg);
4484                    it.remove();
4485                }
4486            }
4487            // Give priority to system apps that listen for pre boot complete.
4488            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4489            ArraySet<String> pkgNames = getPackageNamesForIntent(intent);
4490            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4491                PackageParser.Package pkg = it.next();
4492                if (pkgNames.contains(pkg.packageName)) {
4493                    if (DEBUG_DEXOPT) {
4494                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4495                    }
4496                    sortedPkgs.add(pkg);
4497                    it.remove();
4498                }
4499            }
4500            // Give priority to system apps.
4501            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4502                PackageParser.Package pkg = it.next();
4503                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4504                    if (DEBUG_DEXOPT) {
4505                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4506                    }
4507                    sortedPkgs.add(pkg);
4508                    it.remove();
4509                }
4510            }
4511            // Give priority to updated system apps.
4512            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4513                PackageParser.Package pkg = it.next();
4514                if (isUpdatedSystemApp(pkg)) {
4515                    if (DEBUG_DEXOPT) {
4516                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4517                    }
4518                    sortedPkgs.add(pkg);
4519                    it.remove();
4520                }
4521            }
4522            // Give priority to apps that listen for boot complete.
4523            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4524            pkgNames = getPackageNamesForIntent(intent);
4525            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4526                PackageParser.Package pkg = it.next();
4527                if (pkgNames.contains(pkg.packageName)) {
4528                    if (DEBUG_DEXOPT) {
4529                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4530                    }
4531                    sortedPkgs.add(pkg);
4532                    it.remove();
4533                }
4534            }
4535            // Filter out packages that aren't recently used.
4536            filterRecentlyUsedApps(pkgs);
4537            // Add all remaining apps.
4538            for (PackageParser.Package pkg : pkgs) {
4539                if (DEBUG_DEXOPT) {
4540                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4541                }
4542                sortedPkgs.add(pkg);
4543            }
4544
4545            int i = 0;
4546            int total = sortedPkgs.size();
4547            File dataDir = Environment.getDataDirectory();
4548            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4549            if (lowThreshold == 0) {
4550                throw new IllegalStateException("Invalid low memory threshold");
4551            }
4552            for (PackageParser.Package pkg : sortedPkgs) {
4553                long usableSpace = dataDir.getUsableSpace();
4554                if (usableSpace < lowThreshold) {
4555                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4556                    break;
4557                }
4558                performBootDexOpt(pkg, ++i, total);
4559            }
4560        }
4561    }
4562
4563    private void filterRecentlyUsedApps(ArraySet<PackageParser.Package> pkgs) {
4564        // Filter out packages that aren't recently used.
4565        //
4566        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4567        // should do a full dexopt.
4568        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4569            // TODO: add a property to control this?
4570            long dexOptLRUThresholdInMinutes;
4571            if (mLazyDexOpt) {
4572                dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4573            } else {
4574                dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4575            }
4576            long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4577
4578            int total = pkgs.size();
4579            int skipped = 0;
4580            long now = System.currentTimeMillis();
4581            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4582                PackageParser.Package pkg = i.next();
4583                long then = pkg.mLastPackageUsageTimeInMills;
4584                if (then + dexOptLRUThresholdInMills < now) {
4585                    if (DEBUG_DEXOPT) {
4586                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4587                              ((then == 0) ? "never" : new Date(then)));
4588                    }
4589                    i.remove();
4590                    skipped++;
4591                }
4592            }
4593            if (DEBUG_DEXOPT) {
4594                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4595            }
4596        }
4597    }
4598
4599    private ArraySet<String> getPackageNamesForIntent(Intent intent) {
4600        List<ResolveInfo> ris = null;
4601        try {
4602            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4603                    intent, null, 0, UserHandle.USER_OWNER);
4604        } catch (RemoteException e) {
4605        }
4606        ArraySet<String> pkgNames = new ArraySet<String>();
4607        if (ris != null) {
4608            for (ResolveInfo ri : ris) {
4609                pkgNames.add(ri.activityInfo.packageName);
4610            }
4611        }
4612        return pkgNames;
4613    }
4614
4615    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4616        if (DEBUG_DEXOPT) {
4617            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4618        }
4619        if (!isFirstBoot()) {
4620            try {
4621                ActivityManagerNative.getDefault().showBootMessage(
4622                        mContext.getResources().getString(R.string.android_upgrading_apk,
4623                                curr, total), true);
4624            } catch (RemoteException e) {
4625            }
4626        }
4627        PackageParser.Package p = pkg;
4628        synchronized (mInstallLock) {
4629            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4630                            false /* defer */, true /* include dependencies */);
4631        }
4632    }
4633
4634    @Override
4635    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4636        return performDexOpt(packageName, instructionSet, false);
4637    }
4638
4639    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4640        if (info.primaryCpuAbi == null) {
4641            return getPreferredInstructionSet();
4642        }
4643
4644        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4645    }
4646
4647    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4648        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4649        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4650        if (!dexopt && !updateUsage) {
4651            // We aren't going to dexopt or update usage, so bail early.
4652            return false;
4653        }
4654        PackageParser.Package p;
4655        final String targetInstructionSet;
4656        synchronized (mPackages) {
4657            p = mPackages.get(packageName);
4658            if (p == null) {
4659                return false;
4660            }
4661            if (updateUsage) {
4662                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4663            }
4664            mPackageUsage.write(false);
4665            if (!dexopt) {
4666                // We aren't going to dexopt, so bail early.
4667                return false;
4668            }
4669
4670            targetInstructionSet = instructionSet != null ? instructionSet :
4671                    getPrimaryInstructionSet(p.applicationInfo);
4672            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4673                return false;
4674            }
4675        }
4676
4677        synchronized (mInstallLock) {
4678            final String[] instructionSets = new String[] { targetInstructionSet };
4679            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4680                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4681        }
4682    }
4683
4684    public ArraySet<String> getPackagesThatNeedDexOpt() {
4685        ArraySet<String> pkgs = null;
4686        synchronized (mPackages) {
4687            for (PackageParser.Package p : mPackages.values()) {
4688                if (DEBUG_DEXOPT) {
4689                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4690                }
4691                if (!p.mDexOptPerformed.isEmpty()) {
4692                    continue;
4693                }
4694                if (pkgs == null) {
4695                    pkgs = new ArraySet<String>();
4696                }
4697                pkgs.add(p.packageName);
4698            }
4699        }
4700        return pkgs;
4701    }
4702
4703    public void shutdown() {
4704        mPackageUsage.write(true);
4705    }
4706
4707    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4708             boolean forceDex, boolean defer, ArraySet<String> done) {
4709        for (int i=0; i<libs.size(); i++) {
4710            PackageParser.Package libPkg;
4711            String libName;
4712            synchronized (mPackages) {
4713                libName = libs.get(i);
4714                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4715                if (lib != null && lib.apk != null) {
4716                    libPkg = mPackages.get(lib.apk);
4717                } else {
4718                    libPkg = null;
4719                }
4720            }
4721            if (libPkg != null && !done.contains(libName)) {
4722                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4723            }
4724        }
4725    }
4726
4727    static final int DEX_OPT_SKIPPED = 0;
4728    static final int DEX_OPT_PERFORMED = 1;
4729    static final int DEX_OPT_DEFERRED = 2;
4730    static final int DEX_OPT_FAILED = -1;
4731
4732    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4733            boolean forceDex, boolean defer, ArraySet<String> done) {
4734        final String[] instructionSets = targetInstructionSets != null ?
4735                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4736
4737        if (done != null) {
4738            done.add(pkg.packageName);
4739            if (pkg.usesLibraries != null) {
4740                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4741            }
4742            if (pkg.usesOptionalLibraries != null) {
4743                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4744            }
4745        }
4746
4747        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4748            return DEX_OPT_SKIPPED;
4749        }
4750
4751        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4752
4753        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4754        boolean performedDexOpt = false;
4755        // There are three basic cases here:
4756        // 1.) we need to dexopt, either because we are forced or it is needed
4757        // 2.) we are defering a needed dexopt
4758        // 3.) we are skipping an unneeded dexopt
4759        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4760        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4761            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4762                continue;
4763            }
4764
4765            for (String path : paths) {
4766                try {
4767                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4768                    // patckage or the one we find does not match the image checksum (i.e. it was
4769                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4770                    // odex file and it matches the checksum of the image but not its base address,
4771                    // meaning we need to move it.
4772                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4773                            pkg.packageName, dexCodeInstructionSet, defer);
4774                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4775                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4776                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4777                                + " vmSafeMode=" + vmSafeMode);
4778                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4779                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4780                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4781
4782                        if (ret < 0) {
4783                            // Don't bother running dexopt again if we failed, it will probably
4784                            // just result in an error again. Also, don't bother dexopting for other
4785                            // paths & ISAs.
4786                            return DEX_OPT_FAILED;
4787                        }
4788
4789                        performedDexOpt = true;
4790                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4791                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4792                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4793                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4794                                pkg.packageName, dexCodeInstructionSet);
4795
4796                        if (ret < 0) {
4797                            // Don't bother running patchoat again if we failed, it will probably
4798                            // just result in an error again. Also, don't bother dexopting for other
4799                            // paths & ISAs.
4800                            return DEX_OPT_FAILED;
4801                        }
4802
4803                        performedDexOpt = true;
4804                    }
4805
4806                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4807                    // paths and instruction sets. We'll deal with them all together when we process
4808                    // our list of deferred dexopts.
4809                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4810                        if (mDeferredDexOpt == null) {
4811                            mDeferredDexOpt = new ArraySet<PackageParser.Package>();
4812                        }
4813                        mDeferredDexOpt.add(pkg);
4814                        return DEX_OPT_DEFERRED;
4815                    }
4816                } catch (FileNotFoundException e) {
4817                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4818                    return DEX_OPT_FAILED;
4819                } catch (IOException e) {
4820                    Slog.w(TAG, "IOException reading apk: " + path, e);
4821                    return DEX_OPT_FAILED;
4822                } catch (StaleDexCacheError e) {
4823                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4824                    return DEX_OPT_FAILED;
4825                } catch (Exception e) {
4826                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4827                    return DEX_OPT_FAILED;
4828                }
4829            }
4830
4831            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4832            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4833            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4834            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4835            // it.
4836            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4837        }
4838
4839        // If we've gotten here, we're sure that no error occurred and that we haven't
4840        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4841        // we've skipped all of them because they are up to date. In both cases this
4842        // package doesn't need dexopt any longer.
4843        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4844    }
4845
4846    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4847        if (info.primaryCpuAbi != null) {
4848            if (info.secondaryCpuAbi != null) {
4849                return new String[] {
4850                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4851                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4852            } else {
4853                return new String[] {
4854                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4855            }
4856        }
4857
4858        return new String[] { getPreferredInstructionSet() };
4859    }
4860
4861    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4862        if (ps.primaryCpuAbiString != null) {
4863            if (ps.secondaryCpuAbiString != null) {
4864                return new String[] {
4865                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4866                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4867            } else {
4868                return new String[] {
4869                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4870            }
4871        }
4872
4873        return new String[] { getPreferredInstructionSet() };
4874    }
4875
4876    private static String getPreferredInstructionSet() {
4877        if (sPreferredInstructionSet == null) {
4878            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4879        }
4880
4881        return sPreferredInstructionSet;
4882    }
4883
4884    private static List<String> getAllInstructionSets() {
4885        final String[] allAbis = Build.SUPPORTED_ABIS;
4886        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4887
4888        for (String abi : allAbis) {
4889            final String instructionSet = VMRuntime.getInstructionSet(abi);
4890            if (!allInstructionSets.contains(instructionSet)) {
4891                allInstructionSets.add(instructionSet);
4892            }
4893        }
4894
4895        return allInstructionSets;
4896    }
4897
4898    /**
4899     * Returns the instruction set that should be used to compile dex code. In the presence of
4900     * a native bridge this might be different than the one shared libraries use.
4901     */
4902    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4903        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4904        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4905    }
4906
4907    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4908        ArraySet<String> dexCodeInstructionSets = new ArraySet<String>(instructionSets.length);
4909        for (String instructionSet : instructionSets) {
4910            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4911        }
4912        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4913    }
4914
4915    /**
4916     * Returns deduplicated list of supported instructions for dex code.
4917     */
4918    public static String[] getAllDexCodeInstructionSets() {
4919        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4920        for (int i = 0; i < supportedInstructionSets.length; i++) {
4921            String abi = Build.SUPPORTED_ABIS[i];
4922            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4923        }
4924        return getDexCodeInstructionSets(supportedInstructionSets);
4925    }
4926
4927    @Override
4928    public void forceDexOpt(String packageName) {
4929        enforceSystemOrRoot("forceDexOpt");
4930
4931        PackageParser.Package pkg;
4932        synchronized (mPackages) {
4933            pkg = mPackages.get(packageName);
4934            if (pkg == null) {
4935                throw new IllegalArgumentException("Missing package: " + packageName);
4936            }
4937        }
4938
4939        synchronized (mInstallLock) {
4940            final String[] instructionSets = new String[] {
4941                    getPrimaryInstructionSet(pkg.applicationInfo) };
4942            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4943            if (res != DEX_OPT_PERFORMED) {
4944                throw new IllegalStateException("Failed to dexopt: " + res);
4945            }
4946        }
4947    }
4948
4949    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4950                                boolean forceDex, boolean defer, boolean inclDependencies) {
4951        ArraySet<String> done;
4952        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4953            done = new ArraySet<String>();
4954            done.add(pkg.packageName);
4955        } else {
4956            done = null;
4957        }
4958        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4959    }
4960
4961    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4962        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4963            Slog.w(TAG, "Unable to update from " + oldPkg.name
4964                    + " to " + newPkg.packageName
4965                    + ": old package not in system partition");
4966            return false;
4967        } else if (mPackages.get(oldPkg.name) != null) {
4968            Slog.w(TAG, "Unable to update from " + oldPkg.name
4969                    + " to " + newPkg.packageName
4970                    + ": old package still exists");
4971            return false;
4972        }
4973        return true;
4974    }
4975
4976    File getDataPathForUser(int userId) {
4977        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4978    }
4979
4980    private File getDataPathForPackage(String packageName, int userId) {
4981        /*
4982         * Until we fully support multiple users, return the directory we
4983         * previously would have. The PackageManagerTests will need to be
4984         * revised when this is changed back..
4985         */
4986        if (userId == 0) {
4987            return new File(mAppDataDir, packageName);
4988        } else {
4989            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4990                + File.separator + packageName);
4991        }
4992    }
4993
4994    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4995        int[] users = sUserManager.getUserIds();
4996        int res = mInstaller.install(packageName, uid, uid, seinfo);
4997        if (res < 0) {
4998            return res;
4999        }
5000        for (int user : users) {
5001            if (user != 0) {
5002                res = mInstaller.createUserData(packageName,
5003                        UserHandle.getUid(user, uid), user, seinfo);
5004                if (res < 0) {
5005                    return res;
5006                }
5007            }
5008        }
5009        return res;
5010    }
5011
5012    private int removeDataDirsLI(String packageName) {
5013        int[] users = sUserManager.getUserIds();
5014        int res = 0;
5015        for (int user : users) {
5016            int resInner = mInstaller.remove(packageName, user);
5017            if (resInner < 0) {
5018                res = resInner;
5019            }
5020        }
5021
5022        return res;
5023    }
5024
5025    private int deleteCodeCacheDirsLI(String packageName) {
5026        int[] users = sUserManager.getUserIds();
5027        int res = 0;
5028        for (int user : users) {
5029            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5030            if (resInner < 0) {
5031                res = resInner;
5032            }
5033        }
5034        return res;
5035    }
5036
5037    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5038            PackageParser.Package changingLib) {
5039        if (file.path != null) {
5040            usesLibraryFiles.add(file.path);
5041            return;
5042        }
5043        PackageParser.Package p = mPackages.get(file.apk);
5044        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5045            // If we are doing this while in the middle of updating a library apk,
5046            // then we need to make sure to use that new apk for determining the
5047            // dependencies here.  (We haven't yet finished committing the new apk
5048            // to the package manager state.)
5049            if (p == null || p.packageName.equals(changingLib.packageName)) {
5050                p = changingLib;
5051            }
5052        }
5053        if (p != null) {
5054            usesLibraryFiles.addAll(p.getAllCodePaths());
5055        }
5056    }
5057
5058    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5059            PackageParser.Package changingLib) throws PackageManagerException {
5060        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5061            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5062            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5063            for (int i=0; i<N; i++) {
5064                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5065                if (file == null) {
5066                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5067                            "Package " + pkg.packageName + " requires unavailable shared library "
5068                            + pkg.usesLibraries.get(i) + "; failing!");
5069                }
5070                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5071            }
5072            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5073            for (int i=0; i<N; i++) {
5074                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5075                if (file == null) {
5076                    Slog.w(TAG, "Package " + pkg.packageName
5077                            + " desires unavailable shared library "
5078                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5079                } else {
5080                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5081                }
5082            }
5083            N = usesLibraryFiles.size();
5084            if (N > 0) {
5085                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5086            } else {
5087                pkg.usesLibraryFiles = null;
5088            }
5089        }
5090    }
5091
5092    private static boolean hasString(List<String> list, List<String> which) {
5093        if (list == null) {
5094            return false;
5095        }
5096        for (int i=list.size()-1; i>=0; i--) {
5097            for (int j=which.size()-1; j>=0; j--) {
5098                if (which.get(j).equals(list.get(i))) {
5099                    return true;
5100                }
5101            }
5102        }
5103        return false;
5104    }
5105
5106    private void updateAllSharedLibrariesLPw() {
5107        for (PackageParser.Package pkg : mPackages.values()) {
5108            try {
5109                updateSharedLibrariesLPw(pkg, null);
5110            } catch (PackageManagerException e) {
5111                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5112            }
5113        }
5114    }
5115
5116    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5117            PackageParser.Package changingPkg) {
5118        ArrayList<PackageParser.Package> res = null;
5119        for (PackageParser.Package pkg : mPackages.values()) {
5120            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5121                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5122                if (res == null) {
5123                    res = new ArrayList<PackageParser.Package>();
5124                }
5125                res.add(pkg);
5126                try {
5127                    updateSharedLibrariesLPw(pkg, changingPkg);
5128                } catch (PackageManagerException e) {
5129                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5130                }
5131            }
5132        }
5133        return res;
5134    }
5135
5136    /**
5137     * Derive the value of the {@code cpuAbiOverride} based on the provided
5138     * value and an optional stored value from the package settings.
5139     */
5140    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5141        String cpuAbiOverride = null;
5142
5143        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5144            cpuAbiOverride = null;
5145        } else if (abiOverride != null) {
5146            cpuAbiOverride = abiOverride;
5147        } else if (settings != null) {
5148            cpuAbiOverride = settings.cpuAbiOverrideString;
5149        }
5150
5151        return cpuAbiOverride;
5152    }
5153
5154    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5155            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5156        boolean success = false;
5157        try {
5158            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5159                    currentTime, user);
5160            success = true;
5161            return res;
5162        } finally {
5163            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5164                removeDataDirsLI(pkg.packageName);
5165            }
5166        }
5167    }
5168
5169    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5170            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5171        final File scanFile = new File(pkg.codePath);
5172        if (pkg.applicationInfo.getCodePath() == null ||
5173                pkg.applicationInfo.getResourcePath() == null) {
5174            // Bail out. The resource and code paths haven't been set.
5175            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5176                    "Code and resource paths haven't been set correctly");
5177        }
5178
5179        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5180            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5181        } else {
5182            // Only allow system apps to be flagged as core apps.
5183            pkg.coreApp = false;
5184        }
5185
5186        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5187            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5188        }
5189
5190        if (mCustomResolverComponentName != null &&
5191                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5192            setUpCustomResolverActivity(pkg);
5193        }
5194
5195        if (pkg.packageName.equals("android")) {
5196            synchronized (mPackages) {
5197                if (mAndroidApplication != null) {
5198                    Slog.w(TAG, "*************************************************");
5199                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5200                    Slog.w(TAG, " file=" + scanFile);
5201                    Slog.w(TAG, "*************************************************");
5202                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5203                            "Core android package being redefined.  Skipping.");
5204                }
5205
5206                // Set up information for our fall-back user intent resolution activity.
5207                mPlatformPackage = pkg;
5208                pkg.mVersionCode = mSdkVersion;
5209                mAndroidApplication = pkg.applicationInfo;
5210
5211                if (!mResolverReplaced) {
5212                    mResolveActivity.applicationInfo = mAndroidApplication;
5213                    mResolveActivity.name = ResolverActivity.class.getName();
5214                    mResolveActivity.packageName = mAndroidApplication.packageName;
5215                    mResolveActivity.processName = "system:ui";
5216                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5217                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5218                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5219                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5220                    mResolveActivity.exported = true;
5221                    mResolveActivity.enabled = true;
5222                    mResolveInfo.activityInfo = mResolveActivity;
5223                    mResolveInfo.priority = 0;
5224                    mResolveInfo.preferredOrder = 0;
5225                    mResolveInfo.match = 0;
5226                    mResolveComponentName = new ComponentName(
5227                            mAndroidApplication.packageName, mResolveActivity.name);
5228                }
5229            }
5230        }
5231
5232        if (DEBUG_PACKAGE_SCANNING) {
5233            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5234                Log.d(TAG, "Scanning package " + pkg.packageName);
5235        }
5236
5237        if (mPackages.containsKey(pkg.packageName)
5238                || mSharedLibraries.containsKey(pkg.packageName)) {
5239            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5240                    "Application package " + pkg.packageName
5241                    + " already installed.  Skipping duplicate.");
5242        }
5243
5244        // Initialize package source and resource directories
5245        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5246        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5247
5248        SharedUserSetting suid = null;
5249        PackageSetting pkgSetting = null;
5250
5251        if (!isSystemApp(pkg)) {
5252            // Only system apps can use these features.
5253            pkg.mOriginalPackages = null;
5254            pkg.mRealPackage = null;
5255            pkg.mAdoptPermissions = null;
5256        }
5257
5258        // writer
5259        synchronized (mPackages) {
5260            if (pkg.mSharedUserId != null) {
5261                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5262                if (suid == null) {
5263                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5264                            "Creating application package " + pkg.packageName
5265                            + " for shared user failed");
5266                }
5267                if (DEBUG_PACKAGE_SCANNING) {
5268                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5269                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5270                                + "): packages=" + suid.packages);
5271                }
5272            }
5273
5274            // Check if we are renaming from an original package name.
5275            PackageSetting origPackage = null;
5276            String realName = null;
5277            if (pkg.mOriginalPackages != null) {
5278                // This package may need to be renamed to a previously
5279                // installed name.  Let's check on that...
5280                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5281                if (pkg.mOriginalPackages.contains(renamed)) {
5282                    // This package had originally been installed as the
5283                    // original name, and we have already taken care of
5284                    // transitioning to the new one.  Just update the new
5285                    // one to continue using the old name.
5286                    realName = pkg.mRealPackage;
5287                    if (!pkg.packageName.equals(renamed)) {
5288                        // Callers into this function may have already taken
5289                        // care of renaming the package; only do it here if
5290                        // it is not already done.
5291                        pkg.setPackageName(renamed);
5292                    }
5293
5294                } else {
5295                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5296                        if ((origPackage = mSettings.peekPackageLPr(
5297                                pkg.mOriginalPackages.get(i))) != null) {
5298                            // We do have the package already installed under its
5299                            // original name...  should we use it?
5300                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5301                                // New package is not compatible with original.
5302                                origPackage = null;
5303                                continue;
5304                            } else if (origPackage.sharedUser != null) {
5305                                // Make sure uid is compatible between packages.
5306                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5307                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5308                                            + " to " + pkg.packageName + ": old uid "
5309                                            + origPackage.sharedUser.name
5310                                            + " differs from " + pkg.mSharedUserId);
5311                                    origPackage = null;
5312                                    continue;
5313                                }
5314                            } else {
5315                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5316                                        + pkg.packageName + " to old name " + origPackage.name);
5317                            }
5318                            break;
5319                        }
5320                    }
5321                }
5322            }
5323
5324            if (mTransferedPackages.contains(pkg.packageName)) {
5325                Slog.w(TAG, "Package " + pkg.packageName
5326                        + " was transferred to another, but its .apk remains");
5327            }
5328
5329            // Just create the setting, don't add it yet. For already existing packages
5330            // the PkgSetting exists already and doesn't have to be created.
5331            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5332                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5333                    pkg.applicationInfo.primaryCpuAbi,
5334                    pkg.applicationInfo.secondaryCpuAbi,
5335                    pkg.applicationInfo.flags, user, false);
5336            if (pkgSetting == null) {
5337                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5338                        "Creating application package " + pkg.packageName + " failed");
5339            }
5340
5341            if (pkgSetting.origPackage != null) {
5342                // If we are first transitioning from an original package,
5343                // fix up the new package's name now.  We need to do this after
5344                // looking up the package under its new name, so getPackageLP
5345                // can take care of fiddling things correctly.
5346                pkg.setPackageName(origPackage.name);
5347
5348                // File a report about this.
5349                String msg = "New package " + pkgSetting.realName
5350                        + " renamed to replace old package " + pkgSetting.name;
5351                reportSettingsProblem(Log.WARN, msg);
5352
5353                // Make a note of it.
5354                mTransferedPackages.add(origPackage.name);
5355
5356                // No longer need to retain this.
5357                pkgSetting.origPackage = null;
5358            }
5359
5360            if (realName != null) {
5361                // Make a note of it.
5362                mTransferedPackages.add(pkg.packageName);
5363            }
5364
5365            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5366                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5367            }
5368
5369            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5370                // Check all shared libraries and map to their actual file path.
5371                // We only do this here for apps not on a system dir, because those
5372                // are the only ones that can fail an install due to this.  We
5373                // will take care of the system apps by updating all of their
5374                // library paths after the scan is done.
5375                updateSharedLibrariesLPw(pkg, null);
5376            }
5377
5378            if (mFoundPolicyFile) {
5379                SELinuxMMAC.assignSeinfoValue(pkg);
5380            }
5381
5382            pkg.applicationInfo.uid = pkgSetting.appId;
5383            pkg.mExtras = pkgSetting;
5384            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5385                try {
5386                    verifySignaturesLP(pkgSetting, pkg);
5387                } catch (PackageManagerException e) {
5388                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5389                        throw e;
5390                    }
5391                    // The signature has changed, but this package is in the system
5392                    // image...  let's recover!
5393                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5394                    // However...  if this package is part of a shared user, but it
5395                    // doesn't match the signature of the shared user, let's fail.
5396                    // What this means is that you can't change the signatures
5397                    // associated with an overall shared user, which doesn't seem all
5398                    // that unreasonable.
5399                    if (pkgSetting.sharedUser != null) {
5400                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5401                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5402                            throw new PackageManagerException(
5403                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5404                                            "Signature mismatch for shared user : "
5405                                            + pkgSetting.sharedUser);
5406                        }
5407                    }
5408                    // File a report about this.
5409                    String msg = "System package " + pkg.packageName
5410                        + " signature changed; retaining data.";
5411                    reportSettingsProblem(Log.WARN, msg);
5412                }
5413            } else {
5414                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5415                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5416                            + pkg.packageName + " upgrade keys do not match the "
5417                            + "previously installed version");
5418                } else {
5419                    // signatures may have changed as result of upgrade
5420                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5421                }
5422            }
5423            // Verify that this new package doesn't have any content providers
5424            // that conflict with existing packages.  Only do this if the
5425            // package isn't already installed, since we don't want to break
5426            // things that are installed.
5427            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5428                final int N = pkg.providers.size();
5429                int i;
5430                for (i=0; i<N; i++) {
5431                    PackageParser.Provider p = pkg.providers.get(i);
5432                    if (p.info.authority != null) {
5433                        String names[] = p.info.authority.split(";");
5434                        for (int j = 0; j < names.length; j++) {
5435                            if (mProvidersByAuthority.containsKey(names[j])) {
5436                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5437                                final String otherPackageName =
5438                                        ((other != null && other.getComponentName() != null) ?
5439                                                other.getComponentName().getPackageName() : "?");
5440                                throw new PackageManagerException(
5441                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5442                                                "Can't install because provider name " + names[j]
5443                                                + " (in package " + pkg.applicationInfo.packageName
5444                                                + ") is already used by " + otherPackageName);
5445                            }
5446                        }
5447                    }
5448                }
5449            }
5450
5451            if (pkg.mAdoptPermissions != null) {
5452                // This package wants to adopt ownership of permissions from
5453                // another package.
5454                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5455                    final String origName = pkg.mAdoptPermissions.get(i);
5456                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5457                    if (orig != null) {
5458                        if (verifyPackageUpdateLPr(orig, pkg)) {
5459                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5460                                    + pkg.packageName);
5461                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5462                        }
5463                    }
5464                }
5465            }
5466        }
5467
5468        final String pkgName = pkg.packageName;
5469
5470        final long scanFileTime = scanFile.lastModified();
5471        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5472        pkg.applicationInfo.processName = fixProcessName(
5473                pkg.applicationInfo.packageName,
5474                pkg.applicationInfo.processName,
5475                pkg.applicationInfo.uid);
5476
5477        File dataPath;
5478        if (mPlatformPackage == pkg) {
5479            // The system package is special.
5480            dataPath = new File(Environment.getDataDirectory(), "system");
5481
5482            pkg.applicationInfo.dataDir = dataPath.getPath();
5483
5484        } else {
5485            // This is a normal package, need to make its data directory.
5486            dataPath = getDataPathForPackage(pkg.packageName, 0);
5487
5488            boolean uidError = false;
5489            if (dataPath.exists()) {
5490                int currentUid = 0;
5491                try {
5492                    StructStat stat = Os.stat(dataPath.getPath());
5493                    currentUid = stat.st_uid;
5494                } catch (ErrnoException e) {
5495                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5496                }
5497
5498                // If we have mismatched owners for the data path, we have a problem.
5499                if (currentUid != pkg.applicationInfo.uid) {
5500                    boolean recovered = false;
5501                    if (currentUid == 0) {
5502                        // The directory somehow became owned by root.  Wow.
5503                        // This is probably because the system was stopped while
5504                        // installd was in the middle of messing with its libs
5505                        // directory.  Ask installd to fix that.
5506                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5507                                pkg.applicationInfo.uid);
5508                        if (ret >= 0) {
5509                            recovered = true;
5510                            String msg = "Package " + pkg.packageName
5511                                    + " unexpectedly changed to uid 0; recovered to " +
5512                                    + pkg.applicationInfo.uid;
5513                            reportSettingsProblem(Log.WARN, msg);
5514                        }
5515                    }
5516                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5517                            || (scanFlags&SCAN_BOOTING) != 0)) {
5518                        // If this is a system app, we can at least delete its
5519                        // current data so the application will still work.
5520                        int ret = removeDataDirsLI(pkgName);
5521                        if (ret >= 0) {
5522                            // TODO: Kill the processes first
5523                            // Old data gone!
5524                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5525                                    ? "System package " : "Third party package ";
5526                            String msg = prefix + pkg.packageName
5527                                    + " has changed from uid: "
5528                                    + currentUid + " to "
5529                                    + pkg.applicationInfo.uid + "; old data erased";
5530                            reportSettingsProblem(Log.WARN, msg);
5531                            recovered = true;
5532
5533                            // And now re-install the app.
5534                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5535                                                   pkg.applicationInfo.seinfo);
5536                            if (ret == -1) {
5537                                // Ack should not happen!
5538                                msg = prefix + pkg.packageName
5539                                        + " could not have data directory re-created after delete.";
5540                                reportSettingsProblem(Log.WARN, msg);
5541                                throw new PackageManagerException(
5542                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5543                            }
5544                        }
5545                        if (!recovered) {
5546                            mHasSystemUidErrors = true;
5547                        }
5548                    } else if (!recovered) {
5549                        // If we allow this install to proceed, we will be broken.
5550                        // Abort, abort!
5551                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5552                                "scanPackageLI");
5553                    }
5554                    if (!recovered) {
5555                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5556                            + pkg.applicationInfo.uid + "/fs_"
5557                            + currentUid;
5558                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5559                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5560                        String msg = "Package " + pkg.packageName
5561                                + " has mismatched uid: "
5562                                + currentUid + " on disk, "
5563                                + pkg.applicationInfo.uid + " in settings";
5564                        // writer
5565                        synchronized (mPackages) {
5566                            mSettings.mReadMessages.append(msg);
5567                            mSettings.mReadMessages.append('\n');
5568                            uidError = true;
5569                            if (!pkgSetting.uidError) {
5570                                reportSettingsProblem(Log.ERROR, msg);
5571                            }
5572                        }
5573                    }
5574                }
5575                pkg.applicationInfo.dataDir = dataPath.getPath();
5576                if (mShouldRestoreconData) {
5577                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5578                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5579                                pkg.applicationInfo.uid);
5580                }
5581            } else {
5582                if (DEBUG_PACKAGE_SCANNING) {
5583                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5584                        Log.v(TAG, "Want this data dir: " + dataPath);
5585                }
5586                //invoke installer to do the actual installation
5587                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5588                                           pkg.applicationInfo.seinfo);
5589                if (ret < 0) {
5590                    // Error from installer
5591                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5592                            "Unable to create data dirs [errorCode=" + ret + "]");
5593                }
5594
5595                if (dataPath.exists()) {
5596                    pkg.applicationInfo.dataDir = dataPath.getPath();
5597                } else {
5598                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5599                    pkg.applicationInfo.dataDir = null;
5600                }
5601            }
5602
5603            pkgSetting.uidError = uidError;
5604        }
5605
5606        final String path = scanFile.getPath();
5607        final String codePath = pkg.applicationInfo.getCodePath();
5608        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5609        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5610            setBundledAppAbisAndRoots(pkg, pkgSetting);
5611
5612            // If we haven't found any native libraries for the app, check if it has
5613            // renderscript code. We'll need to force the app to 32 bit if it has
5614            // renderscript bitcode.
5615            if (pkg.applicationInfo.primaryCpuAbi == null
5616                    && pkg.applicationInfo.secondaryCpuAbi == null
5617                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5618                NativeLibraryHelper.Handle handle = null;
5619                try {
5620                    handle = NativeLibraryHelper.Handle.create(scanFile);
5621                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5622                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5623                    }
5624                } catch (IOException ioe) {
5625                    Slog.w(TAG, "Error scanning system app : " + ioe);
5626                } finally {
5627                    IoUtils.closeQuietly(handle);
5628                }
5629            }
5630
5631            setNativeLibraryPaths(pkg);
5632        } else {
5633            // TODO: We can probably be smarter about this stuff. For installed apps,
5634            // we can calculate this information at install time once and for all. For
5635            // system apps, we can probably assume that this information doesn't change
5636            // after the first boot scan. As things stand, we do lots of unnecessary work.
5637
5638            // Give ourselves some initial paths; we'll come back for another
5639            // pass once we've determined ABI below.
5640            setNativeLibraryPaths(pkg);
5641
5642            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5643            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5644            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5645
5646            NativeLibraryHelper.Handle handle = null;
5647            try {
5648                handle = NativeLibraryHelper.Handle.create(scanFile);
5649                // TODO(multiArch): This can be null for apps that didn't go through the
5650                // usual installation process. We can calculate it again, like we
5651                // do during install time.
5652                //
5653                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5654                // unnecessary.
5655                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5656
5657                // Null out the abis so that they can be recalculated.
5658                pkg.applicationInfo.primaryCpuAbi = null;
5659                pkg.applicationInfo.secondaryCpuAbi = null;
5660                if (isMultiArch(pkg.applicationInfo)) {
5661                    // Warn if we've set an abiOverride for multi-lib packages..
5662                    // By definition, we need to copy both 32 and 64 bit libraries for
5663                    // such packages.
5664                    if (pkg.cpuAbiOverride != null
5665                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5666                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5667                    }
5668
5669                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5670                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5671                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5672                        if (isAsec) {
5673                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5674                        } else {
5675                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5676                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5677                                    useIsaSpecificSubdirs);
5678                        }
5679                    }
5680
5681                    maybeThrowExceptionForMultiArchCopy(
5682                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5683
5684                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5685                        if (isAsec) {
5686                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5687                        } else {
5688                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5689                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5690                                    useIsaSpecificSubdirs);
5691                        }
5692                    }
5693
5694                    maybeThrowExceptionForMultiArchCopy(
5695                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5696
5697                    if (abi64 >= 0) {
5698                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5699                    }
5700
5701                    if (abi32 >= 0) {
5702                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5703                        if (abi64 >= 0) {
5704                            pkg.applicationInfo.secondaryCpuAbi = abi;
5705                        } else {
5706                            pkg.applicationInfo.primaryCpuAbi = abi;
5707                        }
5708                    }
5709                } else {
5710                    String[] abiList = (cpuAbiOverride != null) ?
5711                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5712
5713                    // Enable gross and lame hacks for apps that are built with old
5714                    // SDK tools. We must scan their APKs for renderscript bitcode and
5715                    // not launch them if it's present. Don't bother checking on devices
5716                    // that don't have 64 bit support.
5717                    boolean needsRenderScriptOverride = false;
5718                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5719                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5720                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5721                        needsRenderScriptOverride = true;
5722                    }
5723
5724                    final int copyRet;
5725                    if (isAsec) {
5726                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5727                    } else {
5728                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5729                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5730                    }
5731
5732                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5733                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5734                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5735                    }
5736
5737                    if (copyRet >= 0) {
5738                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5739                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5740                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5741                    } else if (needsRenderScriptOverride) {
5742                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5743                    }
5744                }
5745            } catch (IOException ioe) {
5746                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5747            } finally {
5748                IoUtils.closeQuietly(handle);
5749            }
5750
5751            // Now that we've calculated the ABIs and determined if it's an internal app,
5752            // we will go ahead and populate the nativeLibraryPath.
5753            setNativeLibraryPaths(pkg);
5754
5755            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5756            final int[] userIds = sUserManager.getUserIds();
5757            synchronized (mInstallLock) {
5758                // Create a native library symlink only if we have native libraries
5759                // and if the native libraries are 32 bit libraries. We do not provide
5760                // this symlink for 64 bit libraries.
5761                if (pkg.applicationInfo.primaryCpuAbi != null &&
5762                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5763                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5764                    for (int userId : userIds) {
5765                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5766                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5767                                    "Failed linking native library dir (user=" + userId + ")");
5768                        }
5769                    }
5770                }
5771            }
5772        }
5773
5774        // This is a special case for the "system" package, where the ABI is
5775        // dictated by the zygote configuration (and init.rc). We should keep track
5776        // of this ABI so that we can deal with "normal" applications that run under
5777        // the same UID correctly.
5778        if (mPlatformPackage == pkg) {
5779            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5780                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5781        }
5782
5783        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5784        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5785        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5786        // Copy the derived override back to the parsed package, so that we can
5787        // update the package settings accordingly.
5788        pkg.cpuAbiOverride = cpuAbiOverride;
5789
5790        if (DEBUG_ABI_SELECTION) {
5791            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5792                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5793                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5794        }
5795
5796        // Push the derived path down into PackageSettings so we know what to
5797        // clean up at uninstall time.
5798        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5799
5800        if (DEBUG_ABI_SELECTION) {
5801            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5802                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5803                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5804        }
5805
5806        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5807            // We don't do this here during boot because we can do it all
5808            // at once after scanning all existing packages.
5809            //
5810            // We also do this *before* we perform dexopt on this package, so that
5811            // we can avoid redundant dexopts, and also to make sure we've got the
5812            // code and package path correct.
5813            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5814                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5815        }
5816
5817        if ((scanFlags & SCAN_NO_DEX) == 0) {
5818            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5819                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5820                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5821            }
5822        }
5823
5824        if (mFactoryTest && pkg.requestedPermissions.contains(
5825                android.Manifest.permission.FACTORY_TEST)) {
5826            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5827        }
5828
5829        ArrayList<PackageParser.Package> clientLibPkgs = null;
5830
5831        // writer
5832        synchronized (mPackages) {
5833            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5834                // Only system apps can add new shared libraries.
5835                if (pkg.libraryNames != null) {
5836                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5837                        String name = pkg.libraryNames.get(i);
5838                        boolean allowed = false;
5839                        if (isUpdatedSystemApp(pkg)) {
5840                            // New library entries can only be added through the
5841                            // system image.  This is important to get rid of a lot
5842                            // of nasty edge cases: for example if we allowed a non-
5843                            // system update of the app to add a library, then uninstalling
5844                            // the update would make the library go away, and assumptions
5845                            // we made such as through app install filtering would now
5846                            // have allowed apps on the device which aren't compatible
5847                            // with it.  Better to just have the restriction here, be
5848                            // conservative, and create many fewer cases that can negatively
5849                            // impact the user experience.
5850                            final PackageSetting sysPs = mSettings
5851                                    .getDisabledSystemPkgLPr(pkg.packageName);
5852                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5853                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5854                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5855                                        allowed = true;
5856                                        allowed = true;
5857                                        break;
5858                                    }
5859                                }
5860                            }
5861                        } else {
5862                            allowed = true;
5863                        }
5864                        if (allowed) {
5865                            if (!mSharedLibraries.containsKey(name)) {
5866                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5867                            } else if (!name.equals(pkg.packageName)) {
5868                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5869                                        + name + " already exists; skipping");
5870                            }
5871                        } else {
5872                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5873                                    + name + " that is not declared on system image; skipping");
5874                        }
5875                    }
5876                    if ((scanFlags&SCAN_BOOTING) == 0) {
5877                        // If we are not booting, we need to update any applications
5878                        // that are clients of our shared library.  If we are booting,
5879                        // this will all be done once the scan is complete.
5880                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5881                    }
5882                }
5883            }
5884        }
5885
5886        // We also need to dexopt any apps that are dependent on this library.  Note that
5887        // if these fail, we should abort the install since installing the library will
5888        // result in some apps being broken.
5889        if (clientLibPkgs != null) {
5890            if ((scanFlags & SCAN_NO_DEX) == 0) {
5891                for (int i = 0; i < clientLibPkgs.size(); i++) {
5892                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5893                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5894                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5895                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5896                                "scanPackageLI failed to dexopt clientLibPkgs");
5897                    }
5898                }
5899            }
5900        }
5901
5902        // Request the ActivityManager to kill the process(only for existing packages)
5903        // so that we do not end up in a confused state while the user is still using the older
5904        // version of the application while the new one gets installed.
5905        if ((scanFlags & SCAN_REPLACING) != 0) {
5906            killApplication(pkg.applicationInfo.packageName,
5907                        pkg.applicationInfo.uid, "update pkg");
5908        }
5909
5910        // Also need to kill any apps that are dependent on the library.
5911        if (clientLibPkgs != null) {
5912            for (int i=0; i<clientLibPkgs.size(); i++) {
5913                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5914                killApplication(clientPkg.applicationInfo.packageName,
5915                        clientPkg.applicationInfo.uid, "update lib");
5916            }
5917        }
5918
5919        // writer
5920        synchronized (mPackages) {
5921            // We don't expect installation to fail beyond this point
5922
5923            // Add the new setting to mSettings
5924            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5925            // Add the new setting to mPackages
5926            mPackages.put(pkg.applicationInfo.packageName, pkg);
5927            // Make sure we don't accidentally delete its data.
5928            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5929            while (iter.hasNext()) {
5930                PackageCleanItem item = iter.next();
5931                if (pkgName.equals(item.packageName)) {
5932                    iter.remove();
5933                }
5934            }
5935
5936            // Take care of first install / last update times.
5937            if (currentTime != 0) {
5938                if (pkgSetting.firstInstallTime == 0) {
5939                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5940                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5941                    pkgSetting.lastUpdateTime = currentTime;
5942                }
5943            } else if (pkgSetting.firstInstallTime == 0) {
5944                // We need *something*.  Take time time stamp of the file.
5945                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5946            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5947                if (scanFileTime != pkgSetting.timeStamp) {
5948                    // A package on the system image has changed; consider this
5949                    // to be an update.
5950                    pkgSetting.lastUpdateTime = scanFileTime;
5951                }
5952            }
5953
5954            // Add the package's KeySets to the global KeySetManagerService
5955            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5956            try {
5957                // Old KeySetData no longer valid.
5958                ksms.removeAppKeySetDataLPw(pkg.packageName);
5959                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5960                if (pkg.mKeySetMapping != null) {
5961                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5962                            pkg.mKeySetMapping.entrySet()) {
5963                        if (entry.getValue() != null) {
5964                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5965                                                          entry.getValue(), entry.getKey());
5966                        }
5967                    }
5968                    if (pkg.mUpgradeKeySets != null) {
5969                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5970                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5971                        }
5972                    }
5973                }
5974            } catch (NullPointerException e) {
5975                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5976            } catch (IllegalArgumentException e) {
5977                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5978            }
5979
5980            int N = pkg.providers.size();
5981            StringBuilder r = null;
5982            int i;
5983            for (i=0; i<N; i++) {
5984                PackageParser.Provider p = pkg.providers.get(i);
5985                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5986                        p.info.processName, pkg.applicationInfo.uid);
5987                mProviders.addProvider(p);
5988                p.syncable = p.info.isSyncable;
5989                if (p.info.authority != null) {
5990                    String names[] = p.info.authority.split(";");
5991                    p.info.authority = null;
5992                    for (int j = 0; j < names.length; j++) {
5993                        if (j == 1 && p.syncable) {
5994                            // We only want the first authority for a provider to possibly be
5995                            // syncable, so if we already added this provider using a different
5996                            // authority clear the syncable flag. We copy the provider before
5997                            // changing it because the mProviders object contains a reference
5998                            // to a provider that we don't want to change.
5999                            // Only do this for the second authority since the resulting provider
6000                            // object can be the same for all future authorities for this provider.
6001                            p = new PackageParser.Provider(p);
6002                            p.syncable = false;
6003                        }
6004                        if (!mProvidersByAuthority.containsKey(names[j])) {
6005                            mProvidersByAuthority.put(names[j], p);
6006                            if (p.info.authority == null) {
6007                                p.info.authority = names[j];
6008                            } else {
6009                                p.info.authority = p.info.authority + ";" + names[j];
6010                            }
6011                            if (DEBUG_PACKAGE_SCANNING) {
6012                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6013                                    Log.d(TAG, "Registered content provider: " + names[j]
6014                                            + ", className = " + p.info.name + ", isSyncable = "
6015                                            + p.info.isSyncable);
6016                            }
6017                        } else {
6018                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6019                            Slog.w(TAG, "Skipping provider name " + names[j] +
6020                                    " (in package " + pkg.applicationInfo.packageName +
6021                                    "): name already used by "
6022                                    + ((other != null && other.getComponentName() != null)
6023                                            ? other.getComponentName().getPackageName() : "?"));
6024                        }
6025                    }
6026                }
6027                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6028                    if (r == null) {
6029                        r = new StringBuilder(256);
6030                    } else {
6031                        r.append(' ');
6032                    }
6033                    r.append(p.info.name);
6034                }
6035            }
6036            if (r != null) {
6037                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6038            }
6039
6040            N = pkg.services.size();
6041            r = null;
6042            for (i=0; i<N; i++) {
6043                PackageParser.Service s = pkg.services.get(i);
6044                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6045                        s.info.processName, pkg.applicationInfo.uid);
6046                mServices.addService(s);
6047                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6048                    if (r == null) {
6049                        r = new StringBuilder(256);
6050                    } else {
6051                        r.append(' ');
6052                    }
6053                    r.append(s.info.name);
6054                }
6055            }
6056            if (r != null) {
6057                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6058            }
6059
6060            N = pkg.receivers.size();
6061            r = null;
6062            for (i=0; i<N; i++) {
6063                PackageParser.Activity a = pkg.receivers.get(i);
6064                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6065                        a.info.processName, pkg.applicationInfo.uid);
6066                mReceivers.addActivity(a, "receiver");
6067                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6068                    if (r == null) {
6069                        r = new StringBuilder(256);
6070                    } else {
6071                        r.append(' ');
6072                    }
6073                    r.append(a.info.name);
6074                }
6075            }
6076            if (r != null) {
6077                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6078            }
6079
6080            N = pkg.activities.size();
6081            r = null;
6082            for (i=0; i<N; i++) {
6083                PackageParser.Activity a = pkg.activities.get(i);
6084                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6085                        a.info.processName, pkg.applicationInfo.uid);
6086                mActivities.addActivity(a, "activity");
6087                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6088                    if (r == null) {
6089                        r = new StringBuilder(256);
6090                    } else {
6091                        r.append(' ');
6092                    }
6093                    r.append(a.info.name);
6094                }
6095            }
6096            if (r != null) {
6097                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6098            }
6099
6100            N = pkg.permissionGroups.size();
6101            r = null;
6102            for (i=0; i<N; i++) {
6103                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6104                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6105                if (cur == null) {
6106                    mPermissionGroups.put(pg.info.name, pg);
6107                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6108                        if (r == null) {
6109                            r = new StringBuilder(256);
6110                        } else {
6111                            r.append(' ');
6112                        }
6113                        r.append(pg.info.name);
6114                    }
6115                } else {
6116                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6117                            + pg.info.packageName + " ignored: original from "
6118                            + cur.info.packageName);
6119                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6120                        if (r == null) {
6121                            r = new StringBuilder(256);
6122                        } else {
6123                            r.append(' ');
6124                        }
6125                        r.append("DUP:");
6126                        r.append(pg.info.name);
6127                    }
6128                }
6129            }
6130            if (r != null) {
6131                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6132            }
6133
6134            N = pkg.permissions.size();
6135            r = null;
6136            for (i=0; i<N; i++) {
6137                PackageParser.Permission p = pkg.permissions.get(i);
6138                ArrayMap<String, BasePermission> permissionMap =
6139                        p.tree ? mSettings.mPermissionTrees
6140                        : mSettings.mPermissions;
6141                p.group = mPermissionGroups.get(p.info.group);
6142                if (p.info.group == null || p.group != null) {
6143                    BasePermission bp = permissionMap.get(p.info.name);
6144
6145                    // Allow system apps to redefine non-system permissions
6146                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6147                        final boolean currentOwnerIsSystem = (bp.perm != null
6148                                && isSystemApp(bp.perm.owner));
6149                        if (isSystemApp(p.owner)) {
6150                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6151                                // It's a built-in permission and no owner, take ownership now
6152                                bp.packageSetting = pkgSetting;
6153                                bp.perm = p;
6154                                bp.uid = pkg.applicationInfo.uid;
6155                                bp.sourcePackage = p.info.packageName;
6156                            } else if (!currentOwnerIsSystem) {
6157                                String msg = "New decl " + p.owner + " of permission  "
6158                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6159                                reportSettingsProblem(Log.WARN, msg);
6160                                bp = null;
6161                            }
6162                        }
6163                    }
6164
6165                    if (bp == null) {
6166                        bp = new BasePermission(p.info.name, p.info.packageName,
6167                                BasePermission.TYPE_NORMAL);
6168                        permissionMap.put(p.info.name, bp);
6169                    }
6170
6171                    if (bp.perm == null) {
6172                        if (bp.sourcePackage == null
6173                                || bp.sourcePackage.equals(p.info.packageName)) {
6174                            BasePermission tree = findPermissionTreeLP(p.info.name);
6175                            if (tree == null
6176                                    || tree.sourcePackage.equals(p.info.packageName)) {
6177                                bp.packageSetting = pkgSetting;
6178                                bp.perm = p;
6179                                bp.uid = pkg.applicationInfo.uid;
6180                                bp.sourcePackage = p.info.packageName;
6181                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6182                                    if (r == null) {
6183                                        r = new StringBuilder(256);
6184                                    } else {
6185                                        r.append(' ');
6186                                    }
6187                                    r.append(p.info.name);
6188                                }
6189                            } else {
6190                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6191                                        + p.info.packageName + " ignored: base tree "
6192                                        + tree.name + " is from package "
6193                                        + tree.sourcePackage);
6194                            }
6195                        } else {
6196                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6197                                    + p.info.packageName + " ignored: original from "
6198                                    + bp.sourcePackage);
6199                        }
6200                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6201                        if (r == null) {
6202                            r = new StringBuilder(256);
6203                        } else {
6204                            r.append(' ');
6205                        }
6206                        r.append("DUP:");
6207                        r.append(p.info.name);
6208                    }
6209                    if (bp.perm == p) {
6210                        bp.protectionLevel = p.info.protectionLevel;
6211                    }
6212                } else {
6213                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6214                            + p.info.packageName + " ignored: no group "
6215                            + p.group);
6216                }
6217            }
6218            if (r != null) {
6219                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6220            }
6221
6222            N = pkg.instrumentation.size();
6223            r = null;
6224            for (i=0; i<N; i++) {
6225                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6226                a.info.packageName = pkg.applicationInfo.packageName;
6227                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6228                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6229                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6230                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6231                a.info.dataDir = pkg.applicationInfo.dataDir;
6232
6233                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6234                // need other information about the application, like the ABI and what not ?
6235                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6236                mInstrumentation.put(a.getComponentName(), a);
6237                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6238                    if (r == null) {
6239                        r = new StringBuilder(256);
6240                    } else {
6241                        r.append(' ');
6242                    }
6243                    r.append(a.info.name);
6244                }
6245            }
6246            if (r != null) {
6247                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6248            }
6249
6250            if (pkg.protectedBroadcasts != null) {
6251                N = pkg.protectedBroadcasts.size();
6252                for (i=0; i<N; i++) {
6253                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6254                }
6255            }
6256
6257            pkgSetting.setTimeStamp(scanFileTime);
6258
6259            // Create idmap files for pairs of (packages, overlay packages).
6260            // Note: "android", ie framework-res.apk, is handled by native layers.
6261            if (pkg.mOverlayTarget != null) {
6262                // This is an overlay package.
6263                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6264                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6265                        mOverlays.put(pkg.mOverlayTarget,
6266                                new ArrayMap<String, PackageParser.Package>());
6267                    }
6268                    ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6269                    map.put(pkg.packageName, pkg);
6270                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6271                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6272                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6273                                "scanPackageLI failed to createIdmap");
6274                    }
6275                }
6276            } else if (mOverlays.containsKey(pkg.packageName) &&
6277                    !pkg.packageName.equals("android")) {
6278                // This is a regular package, with one or more known overlay packages.
6279                createIdmapsForPackageLI(pkg);
6280            }
6281        }
6282
6283        return pkg;
6284    }
6285
6286    /**
6287     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6288     * i.e, so that all packages can be run inside a single process if required.
6289     *
6290     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6291     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6292     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6293     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6294     * updating a package that belongs to a shared user.
6295     *
6296     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6297     * adds unnecessary complexity.
6298     */
6299    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6300            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6301        String requiredInstructionSet = null;
6302        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6303            requiredInstructionSet = VMRuntime.getInstructionSet(
6304                     scannedPackage.applicationInfo.primaryCpuAbi);
6305        }
6306
6307        PackageSetting requirer = null;
6308        for (PackageSetting ps : packagesForUser) {
6309            // If packagesForUser contains scannedPackage, we skip it. This will happen
6310            // when scannedPackage is an update of an existing package. Without this check,
6311            // we will never be able to change the ABI of any package belonging to a shared
6312            // user, even if it's compatible with other packages.
6313            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6314                if (ps.primaryCpuAbiString == null) {
6315                    continue;
6316                }
6317
6318                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6319                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6320                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6321                    // this but there's not much we can do.
6322                    String errorMessage = "Instruction set mismatch, "
6323                            + ((requirer == null) ? "[caller]" : requirer)
6324                            + " requires " + requiredInstructionSet + " whereas " + ps
6325                            + " requires " + instructionSet;
6326                    Slog.w(TAG, errorMessage);
6327                }
6328
6329                if (requiredInstructionSet == null) {
6330                    requiredInstructionSet = instructionSet;
6331                    requirer = ps;
6332                }
6333            }
6334        }
6335
6336        if (requiredInstructionSet != null) {
6337            String adjustedAbi;
6338            if (requirer != null) {
6339                // requirer != null implies that either scannedPackage was null or that scannedPackage
6340                // did not require an ABI, in which case we have to adjust scannedPackage to match
6341                // the ABI of the set (which is the same as requirer's ABI)
6342                adjustedAbi = requirer.primaryCpuAbiString;
6343                if (scannedPackage != null) {
6344                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6345                }
6346            } else {
6347                // requirer == null implies that we're updating all ABIs in the set to
6348                // match scannedPackage.
6349                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6350            }
6351
6352            for (PackageSetting ps : packagesForUser) {
6353                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6354                    if (ps.primaryCpuAbiString != null) {
6355                        continue;
6356                    }
6357
6358                    ps.primaryCpuAbiString = adjustedAbi;
6359                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6360                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6361                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6362
6363                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6364                                deferDexOpt, true) == DEX_OPT_FAILED) {
6365                            ps.primaryCpuAbiString = null;
6366                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6367                            return;
6368                        } else {
6369                            mInstaller.rmdex(ps.codePathString,
6370                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6371                        }
6372                    }
6373                }
6374            }
6375        }
6376    }
6377
6378    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6379        synchronized (mPackages) {
6380            mResolverReplaced = true;
6381            // Set up information for custom user intent resolution activity.
6382            mResolveActivity.applicationInfo = pkg.applicationInfo;
6383            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6384            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6385            mResolveActivity.processName = null;
6386            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6387            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6388                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6389            mResolveActivity.theme = 0;
6390            mResolveActivity.exported = true;
6391            mResolveActivity.enabled = true;
6392            mResolveInfo.activityInfo = mResolveActivity;
6393            mResolveInfo.priority = 0;
6394            mResolveInfo.preferredOrder = 0;
6395            mResolveInfo.match = 0;
6396            mResolveComponentName = mCustomResolverComponentName;
6397            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6398                    mResolveComponentName);
6399        }
6400    }
6401
6402    private static String calculateBundledApkRoot(final String codePathString) {
6403        final File codePath = new File(codePathString);
6404        final File codeRoot;
6405        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6406            codeRoot = Environment.getRootDirectory();
6407        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6408            codeRoot = Environment.getOemDirectory();
6409        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6410            codeRoot = Environment.getVendorDirectory();
6411        } else {
6412            // Unrecognized code path; take its top real segment as the apk root:
6413            // e.g. /something/app/blah.apk => /something
6414            try {
6415                File f = codePath.getCanonicalFile();
6416                File parent = f.getParentFile();    // non-null because codePath is a file
6417                File tmp;
6418                while ((tmp = parent.getParentFile()) != null) {
6419                    f = parent;
6420                    parent = tmp;
6421                }
6422                codeRoot = f;
6423                Slog.w(TAG, "Unrecognized code path "
6424                        + codePath + " - using " + codeRoot);
6425            } catch (IOException e) {
6426                // Can't canonicalize the code path -- shenanigans?
6427                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6428                return Environment.getRootDirectory().getPath();
6429            }
6430        }
6431        return codeRoot.getPath();
6432    }
6433
6434    /**
6435     * Derive and set the location of native libraries for the given package,
6436     * which varies depending on where and how the package was installed.
6437     */
6438    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6439        final ApplicationInfo info = pkg.applicationInfo;
6440        final String codePath = pkg.codePath;
6441        final File codeFile = new File(codePath);
6442        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6443        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6444
6445        info.nativeLibraryRootDir = null;
6446        info.nativeLibraryRootRequiresIsa = false;
6447        info.nativeLibraryDir = null;
6448        info.secondaryNativeLibraryDir = null;
6449
6450        if (isApkFile(codeFile)) {
6451            // Monolithic install
6452            if (bundledApp) {
6453                // If "/system/lib64/apkname" exists, assume that is the per-package
6454                // native library directory to use; otherwise use "/system/lib/apkname".
6455                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6456                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6457                        getPrimaryInstructionSet(info));
6458
6459                // This is a bundled system app so choose the path based on the ABI.
6460                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6461                // is just the default path.
6462                final String apkName = deriveCodePathName(codePath);
6463                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6464                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6465                        apkName).getAbsolutePath();
6466
6467                if (info.secondaryCpuAbi != null) {
6468                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6469                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6470                            secondaryLibDir, apkName).getAbsolutePath();
6471                }
6472            } else if (asecApp) {
6473                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6474                        .getAbsolutePath();
6475            } else {
6476                final String apkName = deriveCodePathName(codePath);
6477                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6478                        .getAbsolutePath();
6479            }
6480
6481            info.nativeLibraryRootRequiresIsa = false;
6482            info.nativeLibraryDir = info.nativeLibraryRootDir;
6483        } else {
6484            // Cluster install
6485            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6486            info.nativeLibraryRootRequiresIsa = true;
6487
6488            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6489                    getPrimaryInstructionSet(info)).getAbsolutePath();
6490
6491            if (info.secondaryCpuAbi != null) {
6492                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6493                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6494            }
6495        }
6496    }
6497
6498    /**
6499     * Calculate the abis and roots for a bundled app. These can uniquely
6500     * be determined from the contents of the system partition, i.e whether
6501     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6502     * of this information, and instead assume that the system was built
6503     * sensibly.
6504     */
6505    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6506                                           PackageSetting pkgSetting) {
6507        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6508
6509        // If "/system/lib64/apkname" exists, assume that is the per-package
6510        // native library directory to use; otherwise use "/system/lib/apkname".
6511        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6512        setBundledAppAbi(pkg, apkRoot, apkName);
6513        // pkgSetting might be null during rescan following uninstall of updates
6514        // to a bundled app, so accommodate that possibility.  The settings in
6515        // that case will be established later from the parsed package.
6516        //
6517        // If the settings aren't null, sync them up with what we've just derived.
6518        // note that apkRoot isn't stored in the package settings.
6519        if (pkgSetting != null) {
6520            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6521            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6522        }
6523    }
6524
6525    /**
6526     * Deduces the ABI of a bundled app and sets the relevant fields on the
6527     * parsed pkg object.
6528     *
6529     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6530     *        under which system libraries are installed.
6531     * @param apkName the name of the installed package.
6532     */
6533    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6534        final File codeFile = new File(pkg.codePath);
6535
6536        final boolean has64BitLibs;
6537        final boolean has32BitLibs;
6538        if (isApkFile(codeFile)) {
6539            // Monolithic install
6540            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6541            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6542        } else {
6543            // Cluster install
6544            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6545            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6546                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6547                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6548                has64BitLibs = (new File(rootDir, isa)).exists();
6549            } else {
6550                has64BitLibs = false;
6551            }
6552            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6553                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6554                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6555                has32BitLibs = (new File(rootDir, isa)).exists();
6556            } else {
6557                has32BitLibs = false;
6558            }
6559        }
6560
6561        if (has64BitLibs && !has32BitLibs) {
6562            // The package has 64 bit libs, but not 32 bit libs. Its primary
6563            // ABI should be 64 bit. We can safely assume here that the bundled
6564            // native libraries correspond to the most preferred ABI in the list.
6565
6566            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6567            pkg.applicationInfo.secondaryCpuAbi = null;
6568        } else if (has32BitLibs && !has64BitLibs) {
6569            // The package has 32 bit libs but not 64 bit libs. Its primary
6570            // ABI should be 32 bit.
6571
6572            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6573            pkg.applicationInfo.secondaryCpuAbi = null;
6574        } else if (has32BitLibs && has64BitLibs) {
6575            // The application has both 64 and 32 bit bundled libraries. We check
6576            // here that the app declares multiArch support, and warn if it doesn't.
6577            //
6578            // We will be lenient here and record both ABIs. The primary will be the
6579            // ABI that's higher on the list, i.e, a device that's configured to prefer
6580            // 64 bit apps will see a 64 bit primary ABI,
6581
6582            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6583                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6584            }
6585
6586            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6587                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6588                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6589            } else {
6590                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6591                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6592            }
6593        } else {
6594            pkg.applicationInfo.primaryCpuAbi = null;
6595            pkg.applicationInfo.secondaryCpuAbi = null;
6596        }
6597    }
6598
6599    private void killApplication(String pkgName, int appId, String reason) {
6600        // Request the ActivityManager to kill the process(only for existing packages)
6601        // so that we do not end up in a confused state while the user is still using the older
6602        // version of the application while the new one gets installed.
6603        IActivityManager am = ActivityManagerNative.getDefault();
6604        if (am != null) {
6605            try {
6606                am.killApplicationWithAppId(pkgName, appId, reason);
6607            } catch (RemoteException e) {
6608            }
6609        }
6610    }
6611
6612    void removePackageLI(PackageSetting ps, boolean chatty) {
6613        if (DEBUG_INSTALL) {
6614            if (chatty)
6615                Log.d(TAG, "Removing package " + ps.name);
6616        }
6617
6618        // writer
6619        synchronized (mPackages) {
6620            mPackages.remove(ps.name);
6621            final PackageParser.Package pkg = ps.pkg;
6622            if (pkg != null) {
6623                cleanPackageDataStructuresLILPw(pkg, chatty);
6624            }
6625        }
6626    }
6627
6628    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6629        if (DEBUG_INSTALL) {
6630            if (chatty)
6631                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6632        }
6633
6634        // writer
6635        synchronized (mPackages) {
6636            mPackages.remove(pkg.applicationInfo.packageName);
6637            cleanPackageDataStructuresLILPw(pkg, chatty);
6638        }
6639    }
6640
6641    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6642        int N = pkg.providers.size();
6643        StringBuilder r = null;
6644        int i;
6645        for (i=0; i<N; i++) {
6646            PackageParser.Provider p = pkg.providers.get(i);
6647            mProviders.removeProvider(p);
6648            if (p.info.authority == null) {
6649
6650                /* There was another ContentProvider with this authority when
6651                 * this app was installed so this authority is null,
6652                 * Ignore it as we don't have to unregister the provider.
6653                 */
6654                continue;
6655            }
6656            String names[] = p.info.authority.split(";");
6657            for (int j = 0; j < names.length; j++) {
6658                if (mProvidersByAuthority.get(names[j]) == p) {
6659                    mProvidersByAuthority.remove(names[j]);
6660                    if (DEBUG_REMOVE) {
6661                        if (chatty)
6662                            Log.d(TAG, "Unregistered content provider: " + names[j]
6663                                    + ", className = " + p.info.name + ", isSyncable = "
6664                                    + p.info.isSyncable);
6665                    }
6666                }
6667            }
6668            if (DEBUG_REMOVE && chatty) {
6669                if (r == null) {
6670                    r = new StringBuilder(256);
6671                } else {
6672                    r.append(' ');
6673                }
6674                r.append(p.info.name);
6675            }
6676        }
6677        if (r != null) {
6678            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6679        }
6680
6681        N = pkg.services.size();
6682        r = null;
6683        for (i=0; i<N; i++) {
6684            PackageParser.Service s = pkg.services.get(i);
6685            mServices.removeService(s);
6686            if (chatty) {
6687                if (r == null) {
6688                    r = new StringBuilder(256);
6689                } else {
6690                    r.append(' ');
6691                }
6692                r.append(s.info.name);
6693            }
6694        }
6695        if (r != null) {
6696            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6697        }
6698
6699        N = pkg.receivers.size();
6700        r = null;
6701        for (i=0; i<N; i++) {
6702            PackageParser.Activity a = pkg.receivers.get(i);
6703            mReceivers.removeActivity(a, "receiver");
6704            if (DEBUG_REMOVE && chatty) {
6705                if (r == null) {
6706                    r = new StringBuilder(256);
6707                } else {
6708                    r.append(' ');
6709                }
6710                r.append(a.info.name);
6711            }
6712        }
6713        if (r != null) {
6714            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6715        }
6716
6717        N = pkg.activities.size();
6718        r = null;
6719        for (i=0; i<N; i++) {
6720            PackageParser.Activity a = pkg.activities.get(i);
6721            mActivities.removeActivity(a, "activity");
6722            if (DEBUG_REMOVE && chatty) {
6723                if (r == null) {
6724                    r = new StringBuilder(256);
6725                } else {
6726                    r.append(' ');
6727                }
6728                r.append(a.info.name);
6729            }
6730        }
6731        if (r != null) {
6732            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6733        }
6734
6735        N = pkg.permissions.size();
6736        r = null;
6737        for (i=0; i<N; i++) {
6738            PackageParser.Permission p = pkg.permissions.get(i);
6739            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6740            if (bp == null) {
6741                bp = mSettings.mPermissionTrees.get(p.info.name);
6742            }
6743            if (bp != null && bp.perm == p) {
6744                bp.perm = null;
6745                if (DEBUG_REMOVE && chatty) {
6746                    if (r == null) {
6747                        r = new StringBuilder(256);
6748                    } else {
6749                        r.append(' ');
6750                    }
6751                    r.append(p.info.name);
6752                }
6753            }
6754            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6755                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6756                if (appOpPerms != null) {
6757                    appOpPerms.remove(pkg.packageName);
6758                }
6759            }
6760        }
6761        if (r != null) {
6762            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6763        }
6764
6765        N = pkg.requestedPermissions.size();
6766        r = null;
6767        for (i=0; i<N; i++) {
6768            String perm = pkg.requestedPermissions.get(i);
6769            BasePermission bp = mSettings.mPermissions.get(perm);
6770            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6771                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6772                if (appOpPerms != null) {
6773                    appOpPerms.remove(pkg.packageName);
6774                    if (appOpPerms.isEmpty()) {
6775                        mAppOpPermissionPackages.remove(perm);
6776                    }
6777                }
6778            }
6779        }
6780        if (r != null) {
6781            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6782        }
6783
6784        N = pkg.instrumentation.size();
6785        r = null;
6786        for (i=0; i<N; i++) {
6787            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6788            mInstrumentation.remove(a.getComponentName());
6789            if (DEBUG_REMOVE && chatty) {
6790                if (r == null) {
6791                    r = new StringBuilder(256);
6792                } else {
6793                    r.append(' ');
6794                }
6795                r.append(a.info.name);
6796            }
6797        }
6798        if (r != null) {
6799            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6800        }
6801
6802        r = null;
6803        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6804            // Only system apps can hold shared libraries.
6805            if (pkg.libraryNames != null) {
6806                for (i=0; i<pkg.libraryNames.size(); i++) {
6807                    String name = pkg.libraryNames.get(i);
6808                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6809                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6810                        mSharedLibraries.remove(name);
6811                        if (DEBUG_REMOVE && chatty) {
6812                            if (r == null) {
6813                                r = new StringBuilder(256);
6814                            } else {
6815                                r.append(' ');
6816                            }
6817                            r.append(name);
6818                        }
6819                    }
6820                }
6821            }
6822        }
6823        if (r != null) {
6824            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6825        }
6826    }
6827
6828    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6829        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6830            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6831                return true;
6832            }
6833        }
6834        return false;
6835    }
6836
6837    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6838    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6839    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6840
6841    private void updatePermissionsLPw(String changingPkg,
6842            PackageParser.Package pkgInfo, int flags) {
6843        // Make sure there are no dangling permission trees.
6844        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6845        while (it.hasNext()) {
6846            final BasePermission bp = it.next();
6847            if (bp.packageSetting == null) {
6848                // We may not yet have parsed the package, so just see if
6849                // we still know about its settings.
6850                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6851            }
6852            if (bp.packageSetting == null) {
6853                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6854                        + " from package " + bp.sourcePackage);
6855                it.remove();
6856            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6857                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6858                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6859                            + " from package " + bp.sourcePackage);
6860                    flags |= UPDATE_PERMISSIONS_ALL;
6861                    it.remove();
6862                }
6863            }
6864        }
6865
6866        // Make sure all dynamic permissions have been assigned to a package,
6867        // and make sure there are no dangling permissions.
6868        it = mSettings.mPermissions.values().iterator();
6869        while (it.hasNext()) {
6870            final BasePermission bp = it.next();
6871            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6872                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6873                        + bp.name + " pkg=" + bp.sourcePackage
6874                        + " info=" + bp.pendingInfo);
6875                if (bp.packageSetting == null && bp.pendingInfo != null) {
6876                    final BasePermission tree = findPermissionTreeLP(bp.name);
6877                    if (tree != null && tree.perm != null) {
6878                        bp.packageSetting = tree.packageSetting;
6879                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6880                                new PermissionInfo(bp.pendingInfo));
6881                        bp.perm.info.packageName = tree.perm.info.packageName;
6882                        bp.perm.info.name = bp.name;
6883                        bp.uid = tree.uid;
6884                    }
6885                }
6886            }
6887            if (bp.packageSetting == null) {
6888                // We may not yet have parsed the package, so just see if
6889                // we still know about its settings.
6890                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6891            }
6892            if (bp.packageSetting == null) {
6893                Slog.w(TAG, "Removing dangling permission: " + bp.name
6894                        + " from package " + bp.sourcePackage);
6895                it.remove();
6896            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6897                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6898                    Slog.i(TAG, "Removing old permission: " + bp.name
6899                            + " from package " + bp.sourcePackage);
6900                    flags |= UPDATE_PERMISSIONS_ALL;
6901                    it.remove();
6902                }
6903            }
6904        }
6905
6906        // Now update the permissions for all packages, in particular
6907        // replace the granted permissions of the system packages.
6908        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6909            for (PackageParser.Package pkg : mPackages.values()) {
6910                if (pkg != pkgInfo) {
6911                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6912                            changingPkg);
6913                }
6914            }
6915        }
6916
6917        if (pkgInfo != null) {
6918            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6919        }
6920    }
6921
6922    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6923            String packageOfInterest) {
6924        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6925        if (ps == null) {
6926            return;
6927        }
6928        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6929        ArraySet<String> origPermissions = gp.grantedPermissions;
6930        boolean changedPermission = false;
6931
6932        if (replace) {
6933            ps.permissionsFixed = false;
6934            if (gp == ps) {
6935                origPermissions = new ArraySet<String>(gp.grantedPermissions);
6936                gp.grantedPermissions.clear();
6937                gp.gids = mGlobalGids;
6938            }
6939        }
6940
6941        if (gp.gids == null) {
6942            gp.gids = mGlobalGids;
6943        }
6944
6945        final int N = pkg.requestedPermissions.size();
6946        for (int i=0; i<N; i++) {
6947            final String name = pkg.requestedPermissions.get(i);
6948            final boolean required = pkg.requestedPermissionsRequired.get(i);
6949            final BasePermission bp = mSettings.mPermissions.get(name);
6950            if (DEBUG_INSTALL) {
6951                if (gp != ps) {
6952                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6953                }
6954            }
6955
6956            if (bp == null || bp.packageSetting == null) {
6957                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6958                    Slog.w(TAG, "Unknown permission " + name
6959                            + " in package " + pkg.packageName);
6960                }
6961                continue;
6962            }
6963
6964            final String perm = bp.name;
6965            boolean allowed;
6966            boolean allowedSig = false;
6967            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6968                // Keep track of app op permissions.
6969                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6970                if (pkgs == null) {
6971                    pkgs = new ArraySet<>();
6972                    mAppOpPermissionPackages.put(bp.name, pkgs);
6973                }
6974                pkgs.add(pkg.packageName);
6975            }
6976            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6977            if (level == PermissionInfo.PROTECTION_NORMAL
6978                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6979                // We grant a normal or dangerous permission if any of the following
6980                // are true:
6981                // 1) The permission is required
6982                // 2) The permission is optional, but was granted in the past
6983                // 3) The permission is optional, but was requested by an
6984                //    app in /system (not /data)
6985                //
6986                // Otherwise, reject the permission.
6987                allowed = (required || origPermissions.contains(perm)
6988                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6989            } else if (bp.packageSetting == null) {
6990                // This permission is invalid; skip it.
6991                allowed = false;
6992            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6993                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6994                if (allowed) {
6995                    allowedSig = true;
6996                }
6997            } else {
6998                allowed = false;
6999            }
7000            if (DEBUG_INSTALL) {
7001                if (gp != ps) {
7002                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7003                }
7004            }
7005            if (allowed) {
7006                if (!isSystemApp(ps) && ps.permissionsFixed) {
7007                    // If this is an existing, non-system package, then
7008                    // we can't add any new permissions to it.
7009                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7010                        // Except...  if this is a permission that was added
7011                        // to the platform (note: need to only do this when
7012                        // updating the platform).
7013                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7014                    }
7015                }
7016                if (allowed) {
7017                    if (!gp.grantedPermissions.contains(perm)) {
7018                        changedPermission = true;
7019                        gp.grantedPermissions.add(perm);
7020                        gp.gids = appendInts(gp.gids, bp.gids);
7021                    } else if (!ps.haveGids) {
7022                        gp.gids = appendInts(gp.gids, bp.gids);
7023                    }
7024                } else {
7025                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7026                        Slog.w(TAG, "Not granting permission " + perm
7027                                + " to package " + pkg.packageName
7028                                + " because it was previously installed without");
7029                    }
7030                }
7031            } else {
7032                if (gp.grantedPermissions.remove(perm)) {
7033                    changedPermission = true;
7034                    gp.gids = removeInts(gp.gids, bp.gids);
7035                    Slog.i(TAG, "Un-granting permission " + perm
7036                            + " from package " + pkg.packageName
7037                            + " (protectionLevel=" + bp.protectionLevel
7038                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7039                            + ")");
7040                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7041                    // Don't print warning for app op permissions, since it is fine for them
7042                    // not to be granted, there is a UI for the user to decide.
7043                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7044                        Slog.w(TAG, "Not granting permission " + perm
7045                                + " to package " + pkg.packageName
7046                                + " (protectionLevel=" + bp.protectionLevel
7047                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7048                                + ")");
7049                    }
7050                }
7051            }
7052        }
7053
7054        if ((changedPermission || replace) && !ps.permissionsFixed &&
7055                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7056            // This is the first that we have heard about this package, so the
7057            // permissions we have now selected are fixed until explicitly
7058            // changed.
7059            ps.permissionsFixed = true;
7060        }
7061        ps.haveGids = true;
7062    }
7063
7064    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7065        boolean allowed = false;
7066        final int NP = PackageParser.NEW_PERMISSIONS.length;
7067        for (int ip=0; ip<NP; ip++) {
7068            final PackageParser.NewPermissionInfo npi
7069                    = PackageParser.NEW_PERMISSIONS[ip];
7070            if (npi.name.equals(perm)
7071                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7072                allowed = true;
7073                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7074                        + pkg.packageName);
7075                break;
7076            }
7077        }
7078        return allowed;
7079    }
7080
7081    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7082                                          BasePermission bp, ArraySet<String> origPermissions) {
7083        boolean allowed;
7084        allowed = (compareSignatures(
7085                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7086                        == PackageManager.SIGNATURE_MATCH)
7087                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7088                        == PackageManager.SIGNATURE_MATCH);
7089        if (!allowed && (bp.protectionLevel
7090                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7091            if (isSystemApp(pkg)) {
7092                // For updated system applications, a system permission
7093                // is granted only if it had been defined by the original application.
7094                if (isUpdatedSystemApp(pkg)) {
7095                    final PackageSetting sysPs = mSettings
7096                            .getDisabledSystemPkgLPr(pkg.packageName);
7097                    final GrantedPermissions origGp = sysPs.sharedUser != null
7098                            ? sysPs.sharedUser : sysPs;
7099
7100                    if (origGp.grantedPermissions.contains(perm)) {
7101                        // If the original was granted this permission, we take
7102                        // that grant decision as read and propagate it to the
7103                        // update.
7104                        allowed = true;
7105                    } else {
7106                        // The system apk may have been updated with an older
7107                        // version of the one on the data partition, but which
7108                        // granted a new system permission that it didn't have
7109                        // before.  In this case we do want to allow the app to
7110                        // now get the new permission if the ancestral apk is
7111                        // privileged to get it.
7112                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7113                            for (int j=0;
7114                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7115                                if (perm.equals(
7116                                        sysPs.pkg.requestedPermissions.get(j))) {
7117                                    allowed = true;
7118                                    break;
7119                                }
7120                            }
7121                        }
7122                    }
7123                } else {
7124                    allowed = isPrivilegedApp(pkg);
7125                }
7126            }
7127        }
7128        if (!allowed && (bp.protectionLevel
7129                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7130            // For development permissions, a development permission
7131            // is granted only if it was already granted.
7132            allowed = origPermissions.contains(perm);
7133        }
7134        return allowed;
7135    }
7136
7137    final class ActivityIntentResolver
7138            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7139        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7140                boolean defaultOnly, int userId) {
7141            if (!sUserManager.exists(userId)) return null;
7142            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7143            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7144        }
7145
7146        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7147                int userId) {
7148            if (!sUserManager.exists(userId)) return null;
7149            mFlags = flags;
7150            return super.queryIntent(intent, resolvedType,
7151                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7152        }
7153
7154        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7155                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7156            if (!sUserManager.exists(userId)) return null;
7157            if (packageActivities == null) {
7158                return null;
7159            }
7160            mFlags = flags;
7161            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7162            final int N = packageActivities.size();
7163            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7164                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7165
7166            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7167            for (int i = 0; i < N; ++i) {
7168                intentFilters = packageActivities.get(i).intents;
7169                if (intentFilters != null && intentFilters.size() > 0) {
7170                    PackageParser.ActivityIntentInfo[] array =
7171                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7172                    intentFilters.toArray(array);
7173                    listCut.add(array);
7174                }
7175            }
7176            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7177        }
7178
7179        public final void addActivity(PackageParser.Activity a, String type) {
7180            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7181            mActivities.put(a.getComponentName(), a);
7182            if (DEBUG_SHOW_INFO)
7183                Log.v(
7184                TAG, "  " + type + " " +
7185                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7186            if (DEBUG_SHOW_INFO)
7187                Log.v(TAG, "    Class=" + a.info.name);
7188            final int NI = a.intents.size();
7189            for (int j=0; j<NI; j++) {
7190                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7191                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7192                    intent.setPriority(0);
7193                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7194                            + a.className + " with priority > 0, forcing to 0");
7195                }
7196                if (DEBUG_SHOW_INFO) {
7197                    Log.v(TAG, "    IntentFilter:");
7198                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7199                }
7200                if (!intent.debugCheck()) {
7201                    Log.w(TAG, "==> For Activity " + a.info.name);
7202                }
7203                addFilter(intent);
7204            }
7205        }
7206
7207        public final void removeActivity(PackageParser.Activity a, String type) {
7208            mActivities.remove(a.getComponentName());
7209            if (DEBUG_SHOW_INFO) {
7210                Log.v(TAG, "  " + type + " "
7211                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7212                                : a.info.name) + ":");
7213                Log.v(TAG, "    Class=" + a.info.name);
7214            }
7215            final int NI = a.intents.size();
7216            for (int j=0; j<NI; j++) {
7217                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7218                if (DEBUG_SHOW_INFO) {
7219                    Log.v(TAG, "    IntentFilter:");
7220                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7221                }
7222                removeFilter(intent);
7223            }
7224        }
7225
7226        @Override
7227        protected boolean allowFilterResult(
7228                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7229            ActivityInfo filterAi = filter.activity.info;
7230            for (int i=dest.size()-1; i>=0; i--) {
7231                ActivityInfo destAi = dest.get(i).activityInfo;
7232                if (destAi.name == filterAi.name
7233                        && destAi.packageName == filterAi.packageName) {
7234                    return false;
7235                }
7236            }
7237            return true;
7238        }
7239
7240        @Override
7241        protected ActivityIntentInfo[] newArray(int size) {
7242            return new ActivityIntentInfo[size];
7243        }
7244
7245        @Override
7246        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7247            if (!sUserManager.exists(userId)) return true;
7248            PackageParser.Package p = filter.activity.owner;
7249            if (p != null) {
7250                PackageSetting ps = (PackageSetting)p.mExtras;
7251                if (ps != null) {
7252                    // System apps are never considered stopped for purposes of
7253                    // filtering, because there may be no way for the user to
7254                    // actually re-launch them.
7255                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7256                            && ps.getStopped(userId);
7257                }
7258            }
7259            return false;
7260        }
7261
7262        @Override
7263        protected boolean isPackageForFilter(String packageName,
7264                PackageParser.ActivityIntentInfo info) {
7265            return packageName.equals(info.activity.owner.packageName);
7266        }
7267
7268        @Override
7269        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7270                int match, int userId) {
7271            if (!sUserManager.exists(userId)) return null;
7272            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7273                return null;
7274            }
7275            final PackageParser.Activity activity = info.activity;
7276            if (mSafeMode && (activity.info.applicationInfo.flags
7277                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7278                return null;
7279            }
7280            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7281            if (ps == null) {
7282                return null;
7283            }
7284            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7285                    ps.readUserState(userId), userId);
7286            if (ai == null) {
7287                return null;
7288            }
7289            final ResolveInfo res = new ResolveInfo();
7290            res.activityInfo = ai;
7291            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7292                res.filter = info;
7293            }
7294            res.priority = info.getPriority();
7295            res.preferredOrder = activity.owner.mPreferredOrder;
7296            //System.out.println("Result: " + res.activityInfo.className +
7297            //                   " = " + res.priority);
7298            res.match = match;
7299            res.isDefault = info.hasDefault;
7300            res.labelRes = info.labelRes;
7301            res.nonLocalizedLabel = info.nonLocalizedLabel;
7302            if (userNeedsBadging(userId)) {
7303                res.noResourceId = true;
7304            } else {
7305                res.icon = info.icon;
7306            }
7307            res.system = isSystemApp(res.activityInfo.applicationInfo);
7308            return res;
7309        }
7310
7311        @Override
7312        protected void sortResults(List<ResolveInfo> results) {
7313            Collections.sort(results, mResolvePrioritySorter);
7314        }
7315
7316        @Override
7317        protected void dumpFilter(PrintWriter out, String prefix,
7318                PackageParser.ActivityIntentInfo filter) {
7319            out.print(prefix); out.print(
7320                    Integer.toHexString(System.identityHashCode(filter.activity)));
7321                    out.print(' ');
7322                    filter.activity.printComponentShortName(out);
7323                    out.print(" filter ");
7324                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7325        }
7326
7327//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7328//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7329//            final List<ResolveInfo> retList = Lists.newArrayList();
7330//            while (i.hasNext()) {
7331//                final ResolveInfo resolveInfo = i.next();
7332//                if (isEnabledLP(resolveInfo.activityInfo)) {
7333//                    retList.add(resolveInfo);
7334//                }
7335//            }
7336//            return retList;
7337//        }
7338
7339        // Keys are String (activity class name), values are Activity.
7340        private final ArrayMap<ComponentName, PackageParser.Activity> mActivities
7341                = new ArrayMap<ComponentName, PackageParser.Activity>();
7342        private int mFlags;
7343    }
7344
7345    private final class ServiceIntentResolver
7346            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7347        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7348                boolean defaultOnly, int userId) {
7349            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7350            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7351        }
7352
7353        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7354                int userId) {
7355            if (!sUserManager.exists(userId)) return null;
7356            mFlags = flags;
7357            return super.queryIntent(intent, resolvedType,
7358                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7359        }
7360
7361        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7362                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7363            if (!sUserManager.exists(userId)) return null;
7364            if (packageServices == null) {
7365                return null;
7366            }
7367            mFlags = flags;
7368            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7369            final int N = packageServices.size();
7370            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7371                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7372
7373            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7374            for (int i = 0; i < N; ++i) {
7375                intentFilters = packageServices.get(i).intents;
7376                if (intentFilters != null && intentFilters.size() > 0) {
7377                    PackageParser.ServiceIntentInfo[] array =
7378                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7379                    intentFilters.toArray(array);
7380                    listCut.add(array);
7381                }
7382            }
7383            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7384        }
7385
7386        public final void addService(PackageParser.Service s) {
7387            mServices.put(s.getComponentName(), s);
7388            if (DEBUG_SHOW_INFO) {
7389                Log.v(TAG, "  "
7390                        + (s.info.nonLocalizedLabel != null
7391                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7392                Log.v(TAG, "    Class=" + s.info.name);
7393            }
7394            final int NI = s.intents.size();
7395            int j;
7396            for (j=0; j<NI; j++) {
7397                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7398                if (DEBUG_SHOW_INFO) {
7399                    Log.v(TAG, "    IntentFilter:");
7400                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7401                }
7402                if (!intent.debugCheck()) {
7403                    Log.w(TAG, "==> For Service " + s.info.name);
7404                }
7405                addFilter(intent);
7406            }
7407        }
7408
7409        public final void removeService(PackageParser.Service s) {
7410            mServices.remove(s.getComponentName());
7411            if (DEBUG_SHOW_INFO) {
7412                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7413                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7414                Log.v(TAG, "    Class=" + s.info.name);
7415            }
7416            final int NI = s.intents.size();
7417            int j;
7418            for (j=0; j<NI; j++) {
7419                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7420                if (DEBUG_SHOW_INFO) {
7421                    Log.v(TAG, "    IntentFilter:");
7422                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7423                }
7424                removeFilter(intent);
7425            }
7426        }
7427
7428        @Override
7429        protected boolean allowFilterResult(
7430                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7431            ServiceInfo filterSi = filter.service.info;
7432            for (int i=dest.size()-1; i>=0; i--) {
7433                ServiceInfo destAi = dest.get(i).serviceInfo;
7434                if (destAi.name == filterSi.name
7435                        && destAi.packageName == filterSi.packageName) {
7436                    return false;
7437                }
7438            }
7439            return true;
7440        }
7441
7442        @Override
7443        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7444            return new PackageParser.ServiceIntentInfo[size];
7445        }
7446
7447        @Override
7448        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7449            if (!sUserManager.exists(userId)) return true;
7450            PackageParser.Package p = filter.service.owner;
7451            if (p != null) {
7452                PackageSetting ps = (PackageSetting)p.mExtras;
7453                if (ps != null) {
7454                    // System apps are never considered stopped for purposes of
7455                    // filtering, because there may be no way for the user to
7456                    // actually re-launch them.
7457                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7458                            && ps.getStopped(userId);
7459                }
7460            }
7461            return false;
7462        }
7463
7464        @Override
7465        protected boolean isPackageForFilter(String packageName,
7466                PackageParser.ServiceIntentInfo info) {
7467            return packageName.equals(info.service.owner.packageName);
7468        }
7469
7470        @Override
7471        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7472                int match, int userId) {
7473            if (!sUserManager.exists(userId)) return null;
7474            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7475            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7476                return null;
7477            }
7478            final PackageParser.Service service = info.service;
7479            if (mSafeMode && (service.info.applicationInfo.flags
7480                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7481                return null;
7482            }
7483            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7484            if (ps == null) {
7485                return null;
7486            }
7487            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7488                    ps.readUserState(userId), userId);
7489            if (si == null) {
7490                return null;
7491            }
7492            final ResolveInfo res = new ResolveInfo();
7493            res.serviceInfo = si;
7494            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7495                res.filter = filter;
7496            }
7497            res.priority = info.getPriority();
7498            res.preferredOrder = service.owner.mPreferredOrder;
7499            //System.out.println("Result: " + res.activityInfo.className +
7500            //                   " = " + res.priority);
7501            res.match = match;
7502            res.isDefault = info.hasDefault;
7503            res.labelRes = info.labelRes;
7504            res.nonLocalizedLabel = info.nonLocalizedLabel;
7505            res.icon = info.icon;
7506            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7507            return res;
7508        }
7509
7510        @Override
7511        protected void sortResults(List<ResolveInfo> results) {
7512            Collections.sort(results, mResolvePrioritySorter);
7513        }
7514
7515        @Override
7516        protected void dumpFilter(PrintWriter out, String prefix,
7517                PackageParser.ServiceIntentInfo filter) {
7518            out.print(prefix); out.print(
7519                    Integer.toHexString(System.identityHashCode(filter.service)));
7520                    out.print(' ');
7521                    filter.service.printComponentShortName(out);
7522                    out.print(" filter ");
7523                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7524        }
7525
7526//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7527//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7528//            final List<ResolveInfo> retList = Lists.newArrayList();
7529//            while (i.hasNext()) {
7530//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7531//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7532//                    retList.add(resolveInfo);
7533//                }
7534//            }
7535//            return retList;
7536//        }
7537
7538        // Keys are String (activity class name), values are Activity.
7539        private final ArrayMap<ComponentName, PackageParser.Service> mServices
7540                = new ArrayMap<ComponentName, PackageParser.Service>();
7541        private int mFlags;
7542    };
7543
7544    private final class ProviderIntentResolver
7545            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7546        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7547                boolean defaultOnly, int userId) {
7548            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7549            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7550        }
7551
7552        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7553                int userId) {
7554            if (!sUserManager.exists(userId))
7555                return null;
7556            mFlags = flags;
7557            return super.queryIntent(intent, resolvedType,
7558                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7559        }
7560
7561        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7562                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7563            if (!sUserManager.exists(userId))
7564                return null;
7565            if (packageProviders == null) {
7566                return null;
7567            }
7568            mFlags = flags;
7569            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7570            final int N = packageProviders.size();
7571            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7572                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7573
7574            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7575            for (int i = 0; i < N; ++i) {
7576                intentFilters = packageProviders.get(i).intents;
7577                if (intentFilters != null && intentFilters.size() > 0) {
7578                    PackageParser.ProviderIntentInfo[] array =
7579                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7580                    intentFilters.toArray(array);
7581                    listCut.add(array);
7582                }
7583            }
7584            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7585        }
7586
7587        public final void addProvider(PackageParser.Provider p) {
7588            if (mProviders.containsKey(p.getComponentName())) {
7589                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7590                return;
7591            }
7592
7593            mProviders.put(p.getComponentName(), p);
7594            if (DEBUG_SHOW_INFO) {
7595                Log.v(TAG, "  "
7596                        + (p.info.nonLocalizedLabel != null
7597                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7598                Log.v(TAG, "    Class=" + p.info.name);
7599            }
7600            final int NI = p.intents.size();
7601            int j;
7602            for (j = 0; j < NI; j++) {
7603                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7604                if (DEBUG_SHOW_INFO) {
7605                    Log.v(TAG, "    IntentFilter:");
7606                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7607                }
7608                if (!intent.debugCheck()) {
7609                    Log.w(TAG, "==> For Provider " + p.info.name);
7610                }
7611                addFilter(intent);
7612            }
7613        }
7614
7615        public final void removeProvider(PackageParser.Provider p) {
7616            mProviders.remove(p.getComponentName());
7617            if (DEBUG_SHOW_INFO) {
7618                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7619                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7620                Log.v(TAG, "    Class=" + p.info.name);
7621            }
7622            final int NI = p.intents.size();
7623            int j;
7624            for (j = 0; j < NI; j++) {
7625                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7626                if (DEBUG_SHOW_INFO) {
7627                    Log.v(TAG, "    IntentFilter:");
7628                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7629                }
7630                removeFilter(intent);
7631            }
7632        }
7633
7634        @Override
7635        protected boolean allowFilterResult(
7636                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7637            ProviderInfo filterPi = filter.provider.info;
7638            for (int i = dest.size() - 1; i >= 0; i--) {
7639                ProviderInfo destPi = dest.get(i).providerInfo;
7640                if (destPi.name == filterPi.name
7641                        && destPi.packageName == filterPi.packageName) {
7642                    return false;
7643                }
7644            }
7645            return true;
7646        }
7647
7648        @Override
7649        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7650            return new PackageParser.ProviderIntentInfo[size];
7651        }
7652
7653        @Override
7654        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7655            if (!sUserManager.exists(userId))
7656                return true;
7657            PackageParser.Package p = filter.provider.owner;
7658            if (p != null) {
7659                PackageSetting ps = (PackageSetting) p.mExtras;
7660                if (ps != null) {
7661                    // System apps are never considered stopped for purposes of
7662                    // filtering, because there may be no way for the user to
7663                    // actually re-launch them.
7664                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7665                            && ps.getStopped(userId);
7666                }
7667            }
7668            return false;
7669        }
7670
7671        @Override
7672        protected boolean isPackageForFilter(String packageName,
7673                PackageParser.ProviderIntentInfo info) {
7674            return packageName.equals(info.provider.owner.packageName);
7675        }
7676
7677        @Override
7678        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7679                int match, int userId) {
7680            if (!sUserManager.exists(userId))
7681                return null;
7682            final PackageParser.ProviderIntentInfo info = filter;
7683            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7684                return null;
7685            }
7686            final PackageParser.Provider provider = info.provider;
7687            if (mSafeMode && (provider.info.applicationInfo.flags
7688                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7689                return null;
7690            }
7691            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7692            if (ps == null) {
7693                return null;
7694            }
7695            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7696                    ps.readUserState(userId), userId);
7697            if (pi == null) {
7698                return null;
7699            }
7700            final ResolveInfo res = new ResolveInfo();
7701            res.providerInfo = pi;
7702            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7703                res.filter = filter;
7704            }
7705            res.priority = info.getPriority();
7706            res.preferredOrder = provider.owner.mPreferredOrder;
7707            res.match = match;
7708            res.isDefault = info.hasDefault;
7709            res.labelRes = info.labelRes;
7710            res.nonLocalizedLabel = info.nonLocalizedLabel;
7711            res.icon = info.icon;
7712            res.system = isSystemApp(res.providerInfo.applicationInfo);
7713            return res;
7714        }
7715
7716        @Override
7717        protected void sortResults(List<ResolveInfo> results) {
7718            Collections.sort(results, mResolvePrioritySorter);
7719        }
7720
7721        @Override
7722        protected void dumpFilter(PrintWriter out, String prefix,
7723                PackageParser.ProviderIntentInfo filter) {
7724            out.print(prefix);
7725            out.print(
7726                    Integer.toHexString(System.identityHashCode(filter.provider)));
7727            out.print(' ');
7728            filter.provider.printComponentShortName(out);
7729            out.print(" filter ");
7730            out.println(Integer.toHexString(System.identityHashCode(filter)));
7731        }
7732
7733        private final ArrayMap<ComponentName, PackageParser.Provider> mProviders
7734                = new ArrayMap<ComponentName, PackageParser.Provider>();
7735        private int mFlags;
7736    };
7737
7738    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7739            new Comparator<ResolveInfo>() {
7740        public int compare(ResolveInfo r1, ResolveInfo r2) {
7741            int v1 = r1.priority;
7742            int v2 = r2.priority;
7743            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7744            if (v1 != v2) {
7745                return (v1 > v2) ? -1 : 1;
7746            }
7747            v1 = r1.preferredOrder;
7748            v2 = r2.preferredOrder;
7749            if (v1 != v2) {
7750                return (v1 > v2) ? -1 : 1;
7751            }
7752            if (r1.isDefault != r2.isDefault) {
7753                return r1.isDefault ? -1 : 1;
7754            }
7755            v1 = r1.match;
7756            v2 = r2.match;
7757            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7758            if (v1 != v2) {
7759                return (v1 > v2) ? -1 : 1;
7760            }
7761            if (r1.system != r2.system) {
7762                return r1.system ? -1 : 1;
7763            }
7764            return 0;
7765        }
7766    };
7767
7768    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7769            new Comparator<ProviderInfo>() {
7770        public int compare(ProviderInfo p1, ProviderInfo p2) {
7771            final int v1 = p1.initOrder;
7772            final int v2 = p2.initOrder;
7773            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7774        }
7775    };
7776
7777    static final void sendPackageBroadcast(String action, String pkg,
7778            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7779            int[] userIds) {
7780        IActivityManager am = ActivityManagerNative.getDefault();
7781        if (am != null) {
7782            try {
7783                if (userIds == null) {
7784                    userIds = am.getRunningUserIds();
7785                }
7786                for (int id : userIds) {
7787                    final Intent intent = new Intent(action,
7788                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7789                    if (extras != null) {
7790                        intent.putExtras(extras);
7791                    }
7792                    if (targetPkg != null) {
7793                        intent.setPackage(targetPkg);
7794                    }
7795                    // Modify the UID when posting to other users
7796                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7797                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7798                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7799                        intent.putExtra(Intent.EXTRA_UID, uid);
7800                    }
7801                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7802                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7803                    if (DEBUG_BROADCASTS) {
7804                        RuntimeException here = new RuntimeException("here");
7805                        here.fillInStackTrace();
7806                        Slog.d(TAG, "Sending to user " + id + ": "
7807                                + intent.toShortString(false, true, false, false)
7808                                + " " + intent.getExtras(), here);
7809                    }
7810                    am.broadcastIntent(null, intent, null, finishedReceiver,
7811                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7812                            finishedReceiver != null, false, id);
7813                }
7814            } catch (RemoteException ex) {
7815            }
7816        }
7817    }
7818
7819    /**
7820     * Check if the external storage media is available. This is true if there
7821     * is a mounted external storage medium or if the external storage is
7822     * emulated.
7823     */
7824    private boolean isExternalMediaAvailable() {
7825        return mMediaMounted || Environment.isExternalStorageEmulated();
7826    }
7827
7828    @Override
7829    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7830        // writer
7831        synchronized (mPackages) {
7832            if (!isExternalMediaAvailable()) {
7833                // If the external storage is no longer mounted at this point,
7834                // the caller may not have been able to delete all of this
7835                // packages files and can not delete any more.  Bail.
7836                return null;
7837            }
7838            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7839            if (lastPackage != null) {
7840                pkgs.remove(lastPackage);
7841            }
7842            if (pkgs.size() > 0) {
7843                return pkgs.get(0);
7844            }
7845        }
7846        return null;
7847    }
7848
7849    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7850        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7851                userId, andCode ? 1 : 0, packageName);
7852        if (mSystemReady) {
7853            msg.sendToTarget();
7854        } else {
7855            if (mPostSystemReadyMessages == null) {
7856                mPostSystemReadyMessages = new ArrayList<>();
7857            }
7858            mPostSystemReadyMessages.add(msg);
7859        }
7860    }
7861
7862    void startCleaningPackages() {
7863        // reader
7864        synchronized (mPackages) {
7865            if (!isExternalMediaAvailable()) {
7866                return;
7867            }
7868            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7869                return;
7870            }
7871        }
7872        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7873        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7874        IActivityManager am = ActivityManagerNative.getDefault();
7875        if (am != null) {
7876            try {
7877                am.startService(null, intent, null, UserHandle.USER_OWNER);
7878            } catch (RemoteException e) {
7879            }
7880        }
7881    }
7882
7883    @Override
7884    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7885            int installFlags, String installerPackageName, VerificationParams verificationParams,
7886            String packageAbiOverride) {
7887        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7888                packageAbiOverride, UserHandle.getCallingUserId());
7889    }
7890
7891    @Override
7892    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7893            int installFlags, String installerPackageName, VerificationParams verificationParams,
7894            String packageAbiOverride, int userId) {
7895        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7896
7897        final int callingUid = Binder.getCallingUid();
7898        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7899
7900        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7901            try {
7902                if (observer != null) {
7903                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7904                }
7905            } catch (RemoteException re) {
7906            }
7907            return;
7908        }
7909
7910        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7911            installFlags |= PackageManager.INSTALL_FROM_ADB;
7912
7913        } else {
7914            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7915            // about installerPackageName.
7916
7917            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7918            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7919        }
7920
7921        UserHandle user;
7922        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7923            user = UserHandle.ALL;
7924        } else {
7925            user = new UserHandle(userId);
7926        }
7927
7928        verificationParams.setInstallerUid(callingUid);
7929
7930        final File originFile = new File(originPath);
7931        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7932
7933        final Message msg = mHandler.obtainMessage(INIT_COPY);
7934        msg.obj = new InstallParams(origin, observer, installFlags,
7935                installerPackageName, verificationParams, user, packageAbiOverride);
7936        mHandler.sendMessage(msg);
7937    }
7938
7939    void installStage(String packageName, File stagedDir, String stagedCid,
7940            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7941            String installerPackageName, int installerUid, UserHandle user) {
7942        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7943                params.referrerUri, installerUid, null);
7944
7945        final OriginInfo origin;
7946        if (stagedDir != null) {
7947            origin = OriginInfo.fromStagedFile(stagedDir);
7948        } else {
7949            origin = OriginInfo.fromStagedContainer(stagedCid);
7950        }
7951
7952        final Message msg = mHandler.obtainMessage(INIT_COPY);
7953        msg.obj = new InstallParams(origin, observer, params.installFlags,
7954                installerPackageName, verifParams, user, params.abiOverride);
7955        mHandler.sendMessage(msg);
7956    }
7957
7958    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7959        Bundle extras = new Bundle(1);
7960        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7961
7962        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7963                packageName, extras, null, null, new int[] {userId});
7964        try {
7965            IActivityManager am = ActivityManagerNative.getDefault();
7966            final boolean isSystem =
7967                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7968            if (isSystem && am.isUserRunning(userId, false)) {
7969                // The just-installed/enabled app is bundled on the system, so presumed
7970                // to be able to run automatically without needing an explicit launch.
7971                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7972                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7973                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7974                        .setPackage(packageName);
7975                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7976                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7977            }
7978        } catch (RemoteException e) {
7979            // shouldn't happen
7980            Slog.w(TAG, "Unable to bootstrap installed package", e);
7981        }
7982    }
7983
7984    @Override
7985    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7986            int userId) {
7987        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7988        PackageSetting pkgSetting;
7989        final int uid = Binder.getCallingUid();
7990        enforceCrossUserPermission(uid, userId, true, true,
7991                "setApplicationHiddenSetting for user " + userId);
7992
7993        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7994            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7995            return false;
7996        }
7997
7998        long callingId = Binder.clearCallingIdentity();
7999        try {
8000            boolean sendAdded = false;
8001            boolean sendRemoved = false;
8002            // writer
8003            synchronized (mPackages) {
8004                pkgSetting = mSettings.mPackages.get(packageName);
8005                if (pkgSetting == null) {
8006                    return false;
8007                }
8008                if (pkgSetting.getHidden(userId) != hidden) {
8009                    pkgSetting.setHidden(hidden, userId);
8010                    mSettings.writePackageRestrictionsLPr(userId);
8011                    if (hidden) {
8012                        sendRemoved = true;
8013                    } else {
8014                        sendAdded = true;
8015                    }
8016                }
8017            }
8018            if (sendAdded) {
8019                sendPackageAddedForUser(packageName, pkgSetting, userId);
8020                return true;
8021            }
8022            if (sendRemoved) {
8023                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8024                        "hiding pkg");
8025                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8026            }
8027        } finally {
8028            Binder.restoreCallingIdentity(callingId);
8029        }
8030        return false;
8031    }
8032
8033    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8034            int userId) {
8035        final PackageRemovedInfo info = new PackageRemovedInfo();
8036        info.removedPackage = packageName;
8037        info.removedUsers = new int[] {userId};
8038        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8039        info.sendBroadcast(false, false, false);
8040    }
8041
8042    /**
8043     * Returns true if application is not found or there was an error. Otherwise it returns
8044     * the hidden state of the package for the given user.
8045     */
8046    @Override
8047    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8048        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8049        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8050                false, "getApplicationHidden for user " + userId);
8051        PackageSetting pkgSetting;
8052        long callingId = Binder.clearCallingIdentity();
8053        try {
8054            // writer
8055            synchronized (mPackages) {
8056                pkgSetting = mSettings.mPackages.get(packageName);
8057                if (pkgSetting == null) {
8058                    return true;
8059                }
8060                return pkgSetting.getHidden(userId);
8061            }
8062        } finally {
8063            Binder.restoreCallingIdentity(callingId);
8064        }
8065    }
8066
8067    /**
8068     * @hide
8069     */
8070    @Override
8071    public int installExistingPackageAsUser(String packageName, int userId) {
8072        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8073                null);
8074        PackageSetting pkgSetting;
8075        final int uid = Binder.getCallingUid();
8076        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8077                + userId);
8078        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8079            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8080        }
8081
8082        long callingId = Binder.clearCallingIdentity();
8083        try {
8084            boolean sendAdded = false;
8085            Bundle extras = new Bundle(1);
8086
8087            // writer
8088            synchronized (mPackages) {
8089                pkgSetting = mSettings.mPackages.get(packageName);
8090                if (pkgSetting == null) {
8091                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8092                }
8093                if (!pkgSetting.getInstalled(userId)) {
8094                    pkgSetting.setInstalled(true, userId);
8095                    pkgSetting.setHidden(false, userId);
8096                    mSettings.writePackageRestrictionsLPr(userId);
8097                    sendAdded = true;
8098                }
8099            }
8100
8101            if (sendAdded) {
8102                sendPackageAddedForUser(packageName, pkgSetting, userId);
8103            }
8104        } finally {
8105            Binder.restoreCallingIdentity(callingId);
8106        }
8107
8108        return PackageManager.INSTALL_SUCCEEDED;
8109    }
8110
8111    boolean isUserRestricted(int userId, String restrictionKey) {
8112        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8113        if (restrictions.getBoolean(restrictionKey, false)) {
8114            Log.w(TAG, "User is restricted: " + restrictionKey);
8115            return true;
8116        }
8117        return false;
8118    }
8119
8120    @Override
8121    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8122        mContext.enforceCallingOrSelfPermission(
8123                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8124                "Only package verification agents can verify applications");
8125
8126        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8127        final PackageVerificationResponse response = new PackageVerificationResponse(
8128                verificationCode, Binder.getCallingUid());
8129        msg.arg1 = id;
8130        msg.obj = response;
8131        mHandler.sendMessage(msg);
8132    }
8133
8134    @Override
8135    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8136            long millisecondsToDelay) {
8137        mContext.enforceCallingOrSelfPermission(
8138                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8139                "Only package verification agents can extend verification timeouts");
8140
8141        final PackageVerificationState state = mPendingVerification.get(id);
8142        final PackageVerificationResponse response = new PackageVerificationResponse(
8143                verificationCodeAtTimeout, Binder.getCallingUid());
8144
8145        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8146            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8147        }
8148        if (millisecondsToDelay < 0) {
8149            millisecondsToDelay = 0;
8150        }
8151        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8152                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8153            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8154        }
8155
8156        if ((state != null) && !state.timeoutExtended()) {
8157            state.extendTimeout();
8158
8159            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8160            msg.arg1 = id;
8161            msg.obj = response;
8162            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8163        }
8164    }
8165
8166    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8167            int verificationCode, UserHandle user) {
8168        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8169        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8170        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8171        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8172        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8173
8174        mContext.sendBroadcastAsUser(intent, user,
8175                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8176    }
8177
8178    private ComponentName matchComponentForVerifier(String packageName,
8179            List<ResolveInfo> receivers) {
8180        ActivityInfo targetReceiver = null;
8181
8182        final int NR = receivers.size();
8183        for (int i = 0; i < NR; i++) {
8184            final ResolveInfo info = receivers.get(i);
8185            if (info.activityInfo == null) {
8186                continue;
8187            }
8188
8189            if (packageName.equals(info.activityInfo.packageName)) {
8190                targetReceiver = info.activityInfo;
8191                break;
8192            }
8193        }
8194
8195        if (targetReceiver == null) {
8196            return null;
8197        }
8198
8199        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8200    }
8201
8202    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8203            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8204        if (pkgInfo.verifiers.length == 0) {
8205            return null;
8206        }
8207
8208        final int N = pkgInfo.verifiers.length;
8209        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8210        for (int i = 0; i < N; i++) {
8211            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8212
8213            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8214                    receivers);
8215            if (comp == null) {
8216                continue;
8217            }
8218
8219            final int verifierUid = getUidForVerifier(verifierInfo);
8220            if (verifierUid == -1) {
8221                continue;
8222            }
8223
8224            if (DEBUG_VERIFY) {
8225                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8226                        + " with the correct signature");
8227            }
8228            sufficientVerifiers.add(comp);
8229            verificationState.addSufficientVerifier(verifierUid);
8230        }
8231
8232        return sufficientVerifiers;
8233    }
8234
8235    private int getUidForVerifier(VerifierInfo verifierInfo) {
8236        synchronized (mPackages) {
8237            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8238            if (pkg == null) {
8239                return -1;
8240            } else if (pkg.mSignatures.length != 1) {
8241                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8242                        + " has more than one signature; ignoring");
8243                return -1;
8244            }
8245
8246            /*
8247             * If the public key of the package's signature does not match
8248             * our expected public key, then this is a different package and
8249             * we should skip.
8250             */
8251
8252            final byte[] expectedPublicKey;
8253            try {
8254                final Signature verifierSig = pkg.mSignatures[0];
8255                final PublicKey publicKey = verifierSig.getPublicKey();
8256                expectedPublicKey = publicKey.getEncoded();
8257            } catch (CertificateException e) {
8258                return -1;
8259            }
8260
8261            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8262
8263            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8264                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8265                        + " does not have the expected public key; ignoring");
8266                return -1;
8267            }
8268
8269            return pkg.applicationInfo.uid;
8270        }
8271    }
8272
8273    @Override
8274    public void finishPackageInstall(int token) {
8275        enforceSystemOrRoot("Only the system is allowed to finish installs");
8276
8277        if (DEBUG_INSTALL) {
8278            Slog.v(TAG, "BM finishing package install for " + token);
8279        }
8280
8281        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8282        mHandler.sendMessage(msg);
8283    }
8284
8285    /**
8286     * Get the verification agent timeout.
8287     *
8288     * @return verification timeout in milliseconds
8289     */
8290    private long getVerificationTimeout() {
8291        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8292                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8293                DEFAULT_VERIFICATION_TIMEOUT);
8294    }
8295
8296    /**
8297     * Get the default verification agent response code.
8298     *
8299     * @return default verification response code
8300     */
8301    private int getDefaultVerificationResponse() {
8302        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8303                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8304                DEFAULT_VERIFICATION_RESPONSE);
8305    }
8306
8307    /**
8308     * Check whether or not package verification has been enabled.
8309     *
8310     * @return true if verification should be performed
8311     */
8312    private boolean isVerificationEnabled(int userId, int installFlags) {
8313        if (!DEFAULT_VERIFY_ENABLE) {
8314            return false;
8315        }
8316
8317        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8318
8319        // Check if installing from ADB
8320        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8321            // Do not run verification in a test harness environment
8322            if (ActivityManager.isRunningInTestHarness()) {
8323                return false;
8324            }
8325            if (ensureVerifyAppsEnabled) {
8326                return true;
8327            }
8328            // Check if the developer does not want package verification for ADB installs
8329            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8330                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8331                return false;
8332            }
8333        }
8334
8335        if (ensureVerifyAppsEnabled) {
8336            return true;
8337        }
8338
8339        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8340                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8341    }
8342
8343    /**
8344     * Get the "allow unknown sources" setting.
8345     *
8346     * @return the current "allow unknown sources" setting
8347     */
8348    private int getUnknownSourcesSettings() {
8349        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8350                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8351                -1);
8352    }
8353
8354    @Override
8355    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8356        final int uid = Binder.getCallingUid();
8357        // writer
8358        synchronized (mPackages) {
8359            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8360            if (targetPackageSetting == null) {
8361                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8362            }
8363
8364            PackageSetting installerPackageSetting;
8365            if (installerPackageName != null) {
8366                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8367                if (installerPackageSetting == null) {
8368                    throw new IllegalArgumentException("Unknown installer package: "
8369                            + installerPackageName);
8370                }
8371            } else {
8372                installerPackageSetting = null;
8373            }
8374
8375            Signature[] callerSignature;
8376            Object obj = mSettings.getUserIdLPr(uid);
8377            if (obj != null) {
8378                if (obj instanceof SharedUserSetting) {
8379                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8380                } else if (obj instanceof PackageSetting) {
8381                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8382                } else {
8383                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8384                }
8385            } else {
8386                throw new SecurityException("Unknown calling uid " + uid);
8387            }
8388
8389            // Verify: can't set installerPackageName to a package that is
8390            // not signed with the same cert as the caller.
8391            if (installerPackageSetting != null) {
8392                if (compareSignatures(callerSignature,
8393                        installerPackageSetting.signatures.mSignatures)
8394                        != PackageManager.SIGNATURE_MATCH) {
8395                    throw new SecurityException(
8396                            "Caller does not have same cert as new installer package "
8397                            + installerPackageName);
8398                }
8399            }
8400
8401            // Verify: if target already has an installer package, it must
8402            // be signed with the same cert as the caller.
8403            if (targetPackageSetting.installerPackageName != null) {
8404                PackageSetting setting = mSettings.mPackages.get(
8405                        targetPackageSetting.installerPackageName);
8406                // If the currently set package isn't valid, then it's always
8407                // okay to change it.
8408                if (setting != null) {
8409                    if (compareSignatures(callerSignature,
8410                            setting.signatures.mSignatures)
8411                            != PackageManager.SIGNATURE_MATCH) {
8412                        throw new SecurityException(
8413                                "Caller does not have same cert as old installer package "
8414                                + targetPackageSetting.installerPackageName);
8415                    }
8416                }
8417            }
8418
8419            // Okay!
8420            targetPackageSetting.installerPackageName = installerPackageName;
8421            scheduleWriteSettingsLocked();
8422        }
8423    }
8424
8425    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8426        // Queue up an async operation since the package installation may take a little while.
8427        mHandler.post(new Runnable() {
8428            public void run() {
8429                mHandler.removeCallbacks(this);
8430                 // Result object to be returned
8431                PackageInstalledInfo res = new PackageInstalledInfo();
8432                res.returnCode = currentStatus;
8433                res.uid = -1;
8434                res.pkg = null;
8435                res.removedInfo = new PackageRemovedInfo();
8436                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8437                    args.doPreInstall(res.returnCode);
8438                    synchronized (mInstallLock) {
8439                        installPackageLI(args, res);
8440                    }
8441                    args.doPostInstall(res.returnCode, res.uid);
8442                }
8443
8444                // A restore should be performed at this point if (a) the install
8445                // succeeded, (b) the operation is not an update, and (c) the new
8446                // package has not opted out of backup participation.
8447                final boolean update = res.removedInfo.removedPackage != null;
8448                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8449                boolean doRestore = !update
8450                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8451
8452                // Set up the post-install work request bookkeeping.  This will be used
8453                // and cleaned up by the post-install event handling regardless of whether
8454                // there's a restore pass performed.  Token values are >= 1.
8455                int token;
8456                if (mNextInstallToken < 0) mNextInstallToken = 1;
8457                token = mNextInstallToken++;
8458
8459                PostInstallData data = new PostInstallData(args, res);
8460                mRunningInstalls.put(token, data);
8461                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8462
8463                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8464                    // Pass responsibility to the Backup Manager.  It will perform a
8465                    // restore if appropriate, then pass responsibility back to the
8466                    // Package Manager to run the post-install observer callbacks
8467                    // and broadcasts.
8468                    IBackupManager bm = IBackupManager.Stub.asInterface(
8469                            ServiceManager.getService(Context.BACKUP_SERVICE));
8470                    if (bm != null) {
8471                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8472                                + " to BM for possible restore");
8473                        try {
8474                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8475                        } catch (RemoteException e) {
8476                            // can't happen; the backup manager is local
8477                        } catch (Exception e) {
8478                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8479                            doRestore = false;
8480                        }
8481                    } else {
8482                        Slog.e(TAG, "Backup Manager not found!");
8483                        doRestore = false;
8484                    }
8485                }
8486
8487                if (!doRestore) {
8488                    // No restore possible, or the Backup Manager was mysteriously not
8489                    // available -- just fire the post-install work request directly.
8490                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8491                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8492                    mHandler.sendMessage(msg);
8493                }
8494            }
8495        });
8496    }
8497
8498    private abstract class HandlerParams {
8499        private static final int MAX_RETRIES = 4;
8500
8501        /**
8502         * Number of times startCopy() has been attempted and had a non-fatal
8503         * error.
8504         */
8505        private int mRetries = 0;
8506
8507        /** User handle for the user requesting the information or installation. */
8508        private final UserHandle mUser;
8509
8510        HandlerParams(UserHandle user) {
8511            mUser = user;
8512        }
8513
8514        UserHandle getUser() {
8515            return mUser;
8516        }
8517
8518        final boolean startCopy() {
8519            boolean res;
8520            try {
8521                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8522
8523                if (++mRetries > MAX_RETRIES) {
8524                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8525                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8526                    handleServiceError();
8527                    return false;
8528                } else {
8529                    handleStartCopy();
8530                    res = true;
8531                }
8532            } catch (RemoteException e) {
8533                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8534                mHandler.sendEmptyMessage(MCS_RECONNECT);
8535                res = false;
8536            }
8537            handleReturnCode();
8538            return res;
8539        }
8540
8541        final void serviceError() {
8542            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8543            handleServiceError();
8544            handleReturnCode();
8545        }
8546
8547        abstract void handleStartCopy() throws RemoteException;
8548        abstract void handleServiceError();
8549        abstract void handleReturnCode();
8550    }
8551
8552    class MeasureParams extends HandlerParams {
8553        private final PackageStats mStats;
8554        private boolean mSuccess;
8555
8556        private final IPackageStatsObserver mObserver;
8557
8558        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8559            super(new UserHandle(stats.userHandle));
8560            mObserver = observer;
8561            mStats = stats;
8562        }
8563
8564        @Override
8565        public String toString() {
8566            return "MeasureParams{"
8567                + Integer.toHexString(System.identityHashCode(this))
8568                + " " + mStats.packageName + "}";
8569        }
8570
8571        @Override
8572        void handleStartCopy() throws RemoteException {
8573            synchronized (mInstallLock) {
8574                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8575            }
8576
8577            if (mSuccess) {
8578                final boolean mounted;
8579                if (Environment.isExternalStorageEmulated()) {
8580                    mounted = true;
8581                } else {
8582                    final String status = Environment.getExternalStorageState();
8583                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8584                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8585                }
8586
8587                if (mounted) {
8588                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8589
8590                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8591                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8592
8593                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8594                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8595
8596                    // Always subtract cache size, since it's a subdirectory
8597                    mStats.externalDataSize -= mStats.externalCacheSize;
8598
8599                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8600                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8601
8602                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8603                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8604                }
8605            }
8606        }
8607
8608        @Override
8609        void handleReturnCode() {
8610            if (mObserver != null) {
8611                try {
8612                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8613                } catch (RemoteException e) {
8614                    Slog.i(TAG, "Observer no longer exists.");
8615                }
8616            }
8617        }
8618
8619        @Override
8620        void handleServiceError() {
8621            Slog.e(TAG, "Could not measure application " + mStats.packageName
8622                            + " external storage");
8623        }
8624    }
8625
8626    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8627            throws RemoteException {
8628        long result = 0;
8629        for (File path : paths) {
8630            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8631        }
8632        return result;
8633    }
8634
8635    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8636        for (File path : paths) {
8637            try {
8638                mcs.clearDirectory(path.getAbsolutePath());
8639            } catch (RemoteException e) {
8640            }
8641        }
8642    }
8643
8644    static class OriginInfo {
8645        /**
8646         * Location where install is coming from, before it has been
8647         * copied/renamed into place. This could be a single monolithic APK
8648         * file, or a cluster directory. This location may be untrusted.
8649         */
8650        final File file;
8651        final String cid;
8652
8653        /**
8654         * Flag indicating that {@link #file} or {@link #cid} has already been
8655         * staged, meaning downstream users don't need to defensively copy the
8656         * contents.
8657         */
8658        final boolean staged;
8659
8660        /**
8661         * Flag indicating that {@link #file} or {@link #cid} is an already
8662         * installed app that is being moved.
8663         */
8664        final boolean existing;
8665
8666        final String resolvedPath;
8667        final File resolvedFile;
8668
8669        static OriginInfo fromNothing() {
8670            return new OriginInfo(null, null, false, false);
8671        }
8672
8673        static OriginInfo fromUntrustedFile(File file) {
8674            return new OriginInfo(file, null, false, false);
8675        }
8676
8677        static OriginInfo fromExistingFile(File file) {
8678            return new OriginInfo(file, null, false, true);
8679        }
8680
8681        static OriginInfo fromStagedFile(File file) {
8682            return new OriginInfo(file, null, true, false);
8683        }
8684
8685        static OriginInfo fromStagedContainer(String cid) {
8686            return new OriginInfo(null, cid, true, false);
8687        }
8688
8689        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8690            this.file = file;
8691            this.cid = cid;
8692            this.staged = staged;
8693            this.existing = existing;
8694
8695            if (cid != null) {
8696                resolvedPath = PackageHelper.getSdDir(cid);
8697                resolvedFile = new File(resolvedPath);
8698            } else if (file != null) {
8699                resolvedPath = file.getAbsolutePath();
8700                resolvedFile = file;
8701            } else {
8702                resolvedPath = null;
8703                resolvedFile = null;
8704            }
8705        }
8706    }
8707
8708    class InstallParams extends HandlerParams {
8709        final OriginInfo origin;
8710        final IPackageInstallObserver2 observer;
8711        int installFlags;
8712        final String installerPackageName;
8713        final VerificationParams verificationParams;
8714        private InstallArgs mArgs;
8715        private int mRet;
8716        final String packageAbiOverride;
8717
8718        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8719                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8720                String packageAbiOverride) {
8721            super(user);
8722            this.origin = origin;
8723            this.observer = observer;
8724            this.installFlags = installFlags;
8725            this.installerPackageName = installerPackageName;
8726            this.verificationParams = verificationParams;
8727            this.packageAbiOverride = packageAbiOverride;
8728        }
8729
8730        @Override
8731        public String toString() {
8732            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8733                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8734        }
8735
8736        public ManifestDigest getManifestDigest() {
8737            if (verificationParams == null) {
8738                return null;
8739            }
8740            return verificationParams.getManifestDigest();
8741        }
8742
8743        private int installLocationPolicy(PackageInfoLite pkgLite) {
8744            String packageName = pkgLite.packageName;
8745            int installLocation = pkgLite.installLocation;
8746            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8747            // reader
8748            synchronized (mPackages) {
8749                PackageParser.Package pkg = mPackages.get(packageName);
8750                if (pkg != null) {
8751                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8752                        // Check for downgrading.
8753                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8754                            if (pkgLite.versionCode < pkg.mVersionCode) {
8755                                Slog.w(TAG, "Can't install update of " + packageName
8756                                        + " update version " + pkgLite.versionCode
8757                                        + " is older than installed version "
8758                                        + pkg.mVersionCode);
8759                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8760                            }
8761                        }
8762                        // Check for updated system application.
8763                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8764                            if (onSd) {
8765                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8766                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8767                            }
8768                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8769                        } else {
8770                            if (onSd) {
8771                                // Install flag overrides everything.
8772                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8773                            }
8774                            // If current upgrade specifies particular preference
8775                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8776                                // Application explicitly specified internal.
8777                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8778                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8779                                // App explictly prefers external. Let policy decide
8780                            } else {
8781                                // Prefer previous location
8782                                if (isExternal(pkg)) {
8783                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8784                                }
8785                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8786                            }
8787                        }
8788                    } else {
8789                        // Invalid install. Return error code
8790                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8791                    }
8792                }
8793            }
8794            // All the special cases have been taken care of.
8795            // Return result based on recommended install location.
8796            if (onSd) {
8797                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8798            }
8799            return pkgLite.recommendedInstallLocation;
8800        }
8801
8802        /*
8803         * Invoke remote method to get package information and install
8804         * location values. Override install location based on default
8805         * policy if needed and then create install arguments based
8806         * on the install location.
8807         */
8808        public void handleStartCopy() throws RemoteException {
8809            int ret = PackageManager.INSTALL_SUCCEEDED;
8810
8811            // If we're already staged, we've firmly committed to an install location
8812            if (origin.staged) {
8813                if (origin.file != null) {
8814                    installFlags |= PackageManager.INSTALL_INTERNAL;
8815                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8816                } else if (origin.cid != null) {
8817                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8818                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8819                } else {
8820                    throw new IllegalStateException("Invalid stage location");
8821                }
8822            }
8823
8824            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8825            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8826
8827            PackageInfoLite pkgLite = null;
8828
8829            if (onInt && onSd) {
8830                // Check if both bits are set.
8831                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8832                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8833            } else {
8834                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8835                        packageAbiOverride);
8836
8837                /*
8838                 * If we have too little free space, try to free cache
8839                 * before giving up.
8840                 */
8841                if (!origin.staged && pkgLite.recommendedInstallLocation
8842                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8843                    // TODO: focus freeing disk space on the target device
8844                    final StorageManager storage = StorageManager.from(mContext);
8845                    final long lowThreshold = storage.getStorageLowBytes(
8846                            Environment.getDataDirectory());
8847
8848                    final long sizeBytes = mContainerService.calculateInstalledSize(
8849                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8850
8851                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8852                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8853                                installFlags, packageAbiOverride);
8854                    }
8855
8856                    /*
8857                     * The cache free must have deleted the file we
8858                     * downloaded to install.
8859                     *
8860                     * TODO: fix the "freeCache" call to not delete
8861                     *       the file we care about.
8862                     */
8863                    if (pkgLite.recommendedInstallLocation
8864                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8865                        pkgLite.recommendedInstallLocation
8866                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8867                    }
8868                }
8869            }
8870
8871            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8872                int loc = pkgLite.recommendedInstallLocation;
8873                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8874                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8875                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8876                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8877                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8878                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8879                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8880                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8881                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8882                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8883                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8884                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8885                } else {
8886                    // Override with defaults if needed.
8887                    loc = installLocationPolicy(pkgLite);
8888                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8889                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8890                    } else if (!onSd && !onInt) {
8891                        // Override install location with flags
8892                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8893                            // Set the flag to install on external media.
8894                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8895                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8896                        } else {
8897                            // Make sure the flag for installing on external
8898                            // media is unset
8899                            installFlags |= PackageManager.INSTALL_INTERNAL;
8900                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8901                        }
8902                    }
8903                }
8904            }
8905
8906            final InstallArgs args = createInstallArgs(this);
8907            mArgs = args;
8908
8909            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8910                 /*
8911                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8912                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8913                 */
8914                int userIdentifier = getUser().getIdentifier();
8915                if (userIdentifier == UserHandle.USER_ALL
8916                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8917                    userIdentifier = UserHandle.USER_OWNER;
8918                }
8919
8920                /*
8921                 * Determine if we have any installed package verifiers. If we
8922                 * do, then we'll defer to them to verify the packages.
8923                 */
8924                final int requiredUid = mRequiredVerifierPackage == null ? -1
8925                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8926                if (!origin.existing && requiredUid != -1
8927                        && isVerificationEnabled(userIdentifier, installFlags)) {
8928                    final Intent verification = new Intent(
8929                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8930                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8931                            PACKAGE_MIME_TYPE);
8932                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8933
8934                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8935                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8936                            0 /* TODO: Which userId? */);
8937
8938                    if (DEBUG_VERIFY) {
8939                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8940                                + verification.toString() + " with " + pkgLite.verifiers.length
8941                                + " optional verifiers");
8942                    }
8943
8944                    final int verificationId = mPendingVerificationToken++;
8945
8946                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8947
8948                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8949                            installerPackageName);
8950
8951                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8952                            installFlags);
8953
8954                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8955                            pkgLite.packageName);
8956
8957                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8958                            pkgLite.versionCode);
8959
8960                    if (verificationParams != null) {
8961                        if (verificationParams.getVerificationURI() != null) {
8962                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8963                                 verificationParams.getVerificationURI());
8964                        }
8965                        if (verificationParams.getOriginatingURI() != null) {
8966                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8967                                  verificationParams.getOriginatingURI());
8968                        }
8969                        if (verificationParams.getReferrer() != null) {
8970                            verification.putExtra(Intent.EXTRA_REFERRER,
8971                                  verificationParams.getReferrer());
8972                        }
8973                        if (verificationParams.getOriginatingUid() >= 0) {
8974                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8975                                  verificationParams.getOriginatingUid());
8976                        }
8977                        if (verificationParams.getInstallerUid() >= 0) {
8978                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8979                                  verificationParams.getInstallerUid());
8980                        }
8981                    }
8982
8983                    final PackageVerificationState verificationState = new PackageVerificationState(
8984                            requiredUid, args);
8985
8986                    mPendingVerification.append(verificationId, verificationState);
8987
8988                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8989                            receivers, verificationState);
8990
8991                    /*
8992                     * If any sufficient verifiers were listed in the package
8993                     * manifest, attempt to ask them.
8994                     */
8995                    if (sufficientVerifiers != null) {
8996                        final int N = sufficientVerifiers.size();
8997                        if (N == 0) {
8998                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8999                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9000                        } else {
9001                            for (int i = 0; i < N; i++) {
9002                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9003
9004                                final Intent sufficientIntent = new Intent(verification);
9005                                sufficientIntent.setComponent(verifierComponent);
9006
9007                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9008                            }
9009                        }
9010                    }
9011
9012                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9013                            mRequiredVerifierPackage, receivers);
9014                    if (ret == PackageManager.INSTALL_SUCCEEDED
9015                            && mRequiredVerifierPackage != null) {
9016                        /*
9017                         * Send the intent to the required verification agent,
9018                         * but only start the verification timeout after the
9019                         * target BroadcastReceivers have run.
9020                         */
9021                        verification.setComponent(requiredVerifierComponent);
9022                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9023                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9024                                new BroadcastReceiver() {
9025                                    @Override
9026                                    public void onReceive(Context context, Intent intent) {
9027                                        final Message msg = mHandler
9028                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9029                                        msg.arg1 = verificationId;
9030                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9031                                    }
9032                                }, null, 0, null, null);
9033
9034                        /*
9035                         * We don't want the copy to proceed until verification
9036                         * succeeds, so null out this field.
9037                         */
9038                        mArgs = null;
9039                    }
9040                } else {
9041                    /*
9042                     * No package verification is enabled, so immediately start
9043                     * the remote call to initiate copy using temporary file.
9044                     */
9045                    ret = args.copyApk(mContainerService, true);
9046                }
9047            }
9048
9049            mRet = ret;
9050        }
9051
9052        @Override
9053        void handleReturnCode() {
9054            // If mArgs is null, then MCS couldn't be reached. When it
9055            // reconnects, it will try again to install. At that point, this
9056            // will succeed.
9057            if (mArgs != null) {
9058                processPendingInstall(mArgs, mRet);
9059            }
9060        }
9061
9062        @Override
9063        void handleServiceError() {
9064            mArgs = createInstallArgs(this);
9065            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9066        }
9067
9068        public boolean isForwardLocked() {
9069            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9070        }
9071    }
9072
9073    /**
9074     * Used during creation of InstallArgs
9075     *
9076     * @param installFlags package installation flags
9077     * @return true if should be installed on external storage
9078     */
9079    private static boolean installOnSd(int installFlags) {
9080        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9081            return false;
9082        }
9083        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9084            return true;
9085        }
9086        return false;
9087    }
9088
9089    /**
9090     * Used during creation of InstallArgs
9091     *
9092     * @param installFlags package installation flags
9093     * @return true if should be installed as forward locked
9094     */
9095    private static boolean installForwardLocked(int installFlags) {
9096        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9097    }
9098
9099    private InstallArgs createInstallArgs(InstallParams params) {
9100        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9101            return new AsecInstallArgs(params);
9102        } else {
9103            return new FileInstallArgs(params);
9104        }
9105    }
9106
9107    /**
9108     * Create args that describe an existing installed package. Typically used
9109     * when cleaning up old installs, or used as a move source.
9110     */
9111    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9112            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9113        final boolean isInAsec;
9114        if (installOnSd(installFlags)) {
9115            /* Apps on SD card are always in ASEC containers. */
9116            isInAsec = true;
9117        } else if (installForwardLocked(installFlags)
9118                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9119            /*
9120             * Forward-locked apps are only in ASEC containers if they're the
9121             * new style
9122             */
9123            isInAsec = true;
9124        } else {
9125            isInAsec = false;
9126        }
9127
9128        if (isInAsec) {
9129            return new AsecInstallArgs(codePath, instructionSets,
9130                    installOnSd(installFlags), installForwardLocked(installFlags));
9131        } else {
9132            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9133                    instructionSets);
9134        }
9135    }
9136
9137    static abstract class InstallArgs {
9138        /** @see InstallParams#origin */
9139        final OriginInfo origin;
9140
9141        final IPackageInstallObserver2 observer;
9142        // Always refers to PackageManager flags only
9143        final int installFlags;
9144        final String installerPackageName;
9145        final ManifestDigest manifestDigest;
9146        final UserHandle user;
9147        final String abiOverride;
9148
9149        // The list of instruction sets supported by this app. This is currently
9150        // only used during the rmdex() phase to clean up resources. We can get rid of this
9151        // if we move dex files under the common app path.
9152        /* nullable */ String[] instructionSets;
9153
9154        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9155                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9156                String[] instructionSets, String abiOverride) {
9157            this.origin = origin;
9158            this.installFlags = installFlags;
9159            this.observer = observer;
9160            this.installerPackageName = installerPackageName;
9161            this.manifestDigest = manifestDigest;
9162            this.user = user;
9163            this.instructionSets = instructionSets;
9164            this.abiOverride = abiOverride;
9165        }
9166
9167        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9168        abstract int doPreInstall(int status);
9169
9170        /**
9171         * Rename package into final resting place. All paths on the given
9172         * scanned package should be updated to reflect the rename.
9173         */
9174        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9175        abstract int doPostInstall(int status, int uid);
9176
9177        /** @see PackageSettingBase#codePathString */
9178        abstract String getCodePath();
9179        /** @see PackageSettingBase#resourcePathString */
9180        abstract String getResourcePath();
9181        abstract String getLegacyNativeLibraryPath();
9182
9183        // Need installer lock especially for dex file removal.
9184        abstract void cleanUpResourcesLI();
9185        abstract boolean doPostDeleteLI(boolean delete);
9186        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9187
9188        /**
9189         * Called before the source arguments are copied. This is used mostly
9190         * for MoveParams when it needs to read the source file to put it in the
9191         * destination.
9192         */
9193        int doPreCopy() {
9194            return PackageManager.INSTALL_SUCCEEDED;
9195        }
9196
9197        /**
9198         * Called after the source arguments are copied. This is used mostly for
9199         * MoveParams when it needs to read the source file to put it in the
9200         * destination.
9201         *
9202         * @return
9203         */
9204        int doPostCopy(int uid) {
9205            return PackageManager.INSTALL_SUCCEEDED;
9206        }
9207
9208        protected boolean isFwdLocked() {
9209            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9210        }
9211
9212        protected boolean isExternal() {
9213            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9214        }
9215
9216        UserHandle getUser() {
9217            return user;
9218        }
9219    }
9220
9221    /**
9222     * Logic to handle installation of non-ASEC applications, including copying
9223     * and renaming logic.
9224     */
9225    class FileInstallArgs extends InstallArgs {
9226        private File codeFile;
9227        private File resourceFile;
9228        private File legacyNativeLibraryPath;
9229
9230        // Example topology:
9231        // /data/app/com.example/base.apk
9232        // /data/app/com.example/split_foo.apk
9233        // /data/app/com.example/lib/arm/libfoo.so
9234        // /data/app/com.example/lib/arm64/libfoo.so
9235        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9236
9237        /** New install */
9238        FileInstallArgs(InstallParams params) {
9239            super(params.origin, params.observer, params.installFlags,
9240                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9241                    null /* instruction sets */, params.packageAbiOverride);
9242            if (isFwdLocked()) {
9243                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9244            }
9245        }
9246
9247        /** Existing install */
9248        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9249                String[] instructionSets) {
9250            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9251            this.codeFile = (codePath != null) ? new File(codePath) : null;
9252            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9253            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9254                    new File(legacyNativeLibraryPath) : null;
9255        }
9256
9257        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9258            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9259                    isFwdLocked(), abiOverride);
9260
9261            final StorageManager storage = StorageManager.from(mContext);
9262            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9263        }
9264
9265        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9266            if (origin.staged) {
9267                Slog.d(TAG, origin.file + " already staged; skipping copy");
9268                codeFile = origin.file;
9269                resourceFile = origin.file;
9270                return PackageManager.INSTALL_SUCCEEDED;
9271            }
9272
9273            try {
9274                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9275                codeFile = tempDir;
9276                resourceFile = tempDir;
9277            } catch (IOException e) {
9278                Slog.w(TAG, "Failed to create copy file: " + e);
9279                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9280            }
9281
9282            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9283                @Override
9284                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9285                    if (!FileUtils.isValidExtFilename(name)) {
9286                        throw new IllegalArgumentException("Invalid filename: " + name);
9287                    }
9288                    try {
9289                        final File file = new File(codeFile, name);
9290                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9291                                O_RDWR | O_CREAT, 0644);
9292                        Os.chmod(file.getAbsolutePath(), 0644);
9293                        return new ParcelFileDescriptor(fd);
9294                    } catch (ErrnoException e) {
9295                        throw new RemoteException("Failed to open: " + e.getMessage());
9296                    }
9297                }
9298            };
9299
9300            int ret = PackageManager.INSTALL_SUCCEEDED;
9301            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9302            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9303                Slog.e(TAG, "Failed to copy package");
9304                return ret;
9305            }
9306
9307            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9308            NativeLibraryHelper.Handle handle = null;
9309            try {
9310                handle = NativeLibraryHelper.Handle.create(codeFile);
9311                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9312                        abiOverride);
9313            } catch (IOException e) {
9314                Slog.e(TAG, "Copying native libraries failed", e);
9315                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9316            } finally {
9317                IoUtils.closeQuietly(handle);
9318            }
9319
9320            return ret;
9321        }
9322
9323        int doPreInstall(int status) {
9324            if (status != PackageManager.INSTALL_SUCCEEDED) {
9325                cleanUp();
9326            }
9327            return status;
9328        }
9329
9330        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9331            if (status != PackageManager.INSTALL_SUCCEEDED) {
9332                cleanUp();
9333                return false;
9334            } else {
9335                final File beforeCodeFile = codeFile;
9336                final File afterCodeFile = getNextCodePath(pkg.packageName);
9337
9338                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9339                try {
9340                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9341                } catch (ErrnoException e) {
9342                    Slog.d(TAG, "Failed to rename", e);
9343                    return false;
9344                }
9345
9346                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9347                    Slog.d(TAG, "Failed to restorecon");
9348                    return false;
9349                }
9350
9351                // Reflect the rename internally
9352                codeFile = afterCodeFile;
9353                resourceFile = afterCodeFile;
9354
9355                // Reflect the rename in scanned details
9356                pkg.codePath = afterCodeFile.getAbsolutePath();
9357                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9358                        pkg.baseCodePath);
9359                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9360                        pkg.splitCodePaths);
9361
9362                // Reflect the rename in app info
9363                pkg.applicationInfo.setCodePath(pkg.codePath);
9364                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9365                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9366                pkg.applicationInfo.setResourcePath(pkg.codePath);
9367                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9368                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9369
9370                return true;
9371            }
9372        }
9373
9374        int doPostInstall(int status, int uid) {
9375            if (status != PackageManager.INSTALL_SUCCEEDED) {
9376                cleanUp();
9377            }
9378            return status;
9379        }
9380
9381        @Override
9382        String getCodePath() {
9383            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9384        }
9385
9386        @Override
9387        String getResourcePath() {
9388            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9389        }
9390
9391        @Override
9392        String getLegacyNativeLibraryPath() {
9393            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9394        }
9395
9396        private boolean cleanUp() {
9397            if (codeFile == null || !codeFile.exists()) {
9398                return false;
9399            }
9400
9401            if (codeFile.isDirectory()) {
9402                FileUtils.deleteContents(codeFile);
9403            }
9404            codeFile.delete();
9405
9406            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9407                resourceFile.delete();
9408            }
9409
9410            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9411                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9412                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9413                }
9414                legacyNativeLibraryPath.delete();
9415            }
9416
9417            return true;
9418        }
9419
9420        void cleanUpResourcesLI() {
9421            // Try enumerating all code paths before deleting
9422            List<String> allCodePaths = Collections.EMPTY_LIST;
9423            if (codeFile != null && codeFile.exists()) {
9424                try {
9425                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9426                    allCodePaths = pkg.getAllCodePaths();
9427                } catch (PackageParserException e) {
9428                    // Ignored; we tried our best
9429                }
9430            }
9431
9432            cleanUp();
9433
9434            if (!allCodePaths.isEmpty()) {
9435                if (instructionSets == null) {
9436                    throw new IllegalStateException("instructionSet == null");
9437                }
9438                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9439                for (String codePath : allCodePaths) {
9440                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9441                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9442                        if (retCode < 0) {
9443                            Slog.w(TAG, "Couldn't remove dex file for package: "
9444                                    + " at location " + codePath + ", retcode=" + retCode);
9445                            // we don't consider this to be a failure of the core package deletion
9446                        }
9447                    }
9448                }
9449            }
9450        }
9451
9452        boolean doPostDeleteLI(boolean delete) {
9453            // XXX err, shouldn't we respect the delete flag?
9454            cleanUpResourcesLI();
9455            return true;
9456        }
9457    }
9458
9459    private boolean isAsecExternal(String cid) {
9460        final String asecPath = PackageHelper.getSdFilesystem(cid);
9461        return !asecPath.startsWith(mAsecInternalPath);
9462    }
9463
9464    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9465            PackageManagerException {
9466        if (copyRet < 0) {
9467            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9468                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9469                throw new PackageManagerException(copyRet, message);
9470            }
9471        }
9472    }
9473
9474    /**
9475     * Extract the MountService "container ID" from the full code path of an
9476     * .apk.
9477     */
9478    static String cidFromCodePath(String fullCodePath) {
9479        int eidx = fullCodePath.lastIndexOf("/");
9480        String subStr1 = fullCodePath.substring(0, eidx);
9481        int sidx = subStr1.lastIndexOf("/");
9482        return subStr1.substring(sidx+1, eidx);
9483    }
9484
9485    /**
9486     * Logic to handle installation of ASEC applications, including copying and
9487     * renaming logic.
9488     */
9489    class AsecInstallArgs extends InstallArgs {
9490        static final String RES_FILE_NAME = "pkg.apk";
9491        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9492
9493        String cid;
9494        String packagePath;
9495        String resourcePath;
9496        String legacyNativeLibraryDir;
9497
9498        /** New install */
9499        AsecInstallArgs(InstallParams params) {
9500            super(params.origin, params.observer, params.installFlags,
9501                    params.installerPackageName, params.getManifestDigest(),
9502                    params.getUser(), null /* instruction sets */,
9503                    params.packageAbiOverride);
9504        }
9505
9506        /** Existing install */
9507        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9508                        boolean isExternal, boolean isForwardLocked) {
9509            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9510                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9511                    instructionSets, null);
9512            // Hackily pretend we're still looking at a full code path
9513            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9514                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9515            }
9516
9517            // Extract cid from fullCodePath
9518            int eidx = fullCodePath.lastIndexOf("/");
9519            String subStr1 = fullCodePath.substring(0, eidx);
9520            int sidx = subStr1.lastIndexOf("/");
9521            cid = subStr1.substring(sidx+1, eidx);
9522            setMountPath(subStr1);
9523        }
9524
9525        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9526            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9527                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9528                    instructionSets, null);
9529            this.cid = cid;
9530            setMountPath(PackageHelper.getSdDir(cid));
9531        }
9532
9533        void createCopyFile() {
9534            cid = mInstallerService.allocateExternalStageCidLegacy();
9535        }
9536
9537        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9538            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9539                    abiOverride);
9540
9541            final File target;
9542            if (isExternal()) {
9543                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9544            } else {
9545                target = Environment.getDataDirectory();
9546            }
9547
9548            final StorageManager storage = StorageManager.from(mContext);
9549            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9550        }
9551
9552        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9553            if (origin.staged) {
9554                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9555                cid = origin.cid;
9556                setMountPath(PackageHelper.getSdDir(cid));
9557                return PackageManager.INSTALL_SUCCEEDED;
9558            }
9559
9560            if (temp) {
9561                createCopyFile();
9562            } else {
9563                /*
9564                 * Pre-emptively destroy the container since it's destroyed if
9565                 * copying fails due to it existing anyway.
9566                 */
9567                PackageHelper.destroySdDir(cid);
9568            }
9569
9570            final String newMountPath = imcs.copyPackageToContainer(
9571                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9572                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9573
9574            if (newMountPath != null) {
9575                setMountPath(newMountPath);
9576                return PackageManager.INSTALL_SUCCEEDED;
9577            } else {
9578                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9579            }
9580        }
9581
9582        @Override
9583        String getCodePath() {
9584            return packagePath;
9585        }
9586
9587        @Override
9588        String getResourcePath() {
9589            return resourcePath;
9590        }
9591
9592        @Override
9593        String getLegacyNativeLibraryPath() {
9594            return legacyNativeLibraryDir;
9595        }
9596
9597        int doPreInstall(int status) {
9598            if (status != PackageManager.INSTALL_SUCCEEDED) {
9599                // Destroy container
9600                PackageHelper.destroySdDir(cid);
9601            } else {
9602                boolean mounted = PackageHelper.isContainerMounted(cid);
9603                if (!mounted) {
9604                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9605                            Process.SYSTEM_UID);
9606                    if (newMountPath != null) {
9607                        setMountPath(newMountPath);
9608                    } else {
9609                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9610                    }
9611                }
9612            }
9613            return status;
9614        }
9615
9616        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9617            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9618            String newMountPath = null;
9619            if (PackageHelper.isContainerMounted(cid)) {
9620                // Unmount the container
9621                if (!PackageHelper.unMountSdDir(cid)) {
9622                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9623                    return false;
9624                }
9625            }
9626            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9627                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9628                        " which might be stale. Will try to clean up.");
9629                // Clean up the stale container and proceed to recreate.
9630                if (!PackageHelper.destroySdDir(newCacheId)) {
9631                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9632                    return false;
9633                }
9634                // Successfully cleaned up stale container. Try to rename again.
9635                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9636                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9637                            + " inspite of cleaning it up.");
9638                    return false;
9639                }
9640            }
9641            if (!PackageHelper.isContainerMounted(newCacheId)) {
9642                Slog.w(TAG, "Mounting container " + newCacheId);
9643                newMountPath = PackageHelper.mountSdDir(newCacheId,
9644                        getEncryptKey(), Process.SYSTEM_UID);
9645            } else {
9646                newMountPath = PackageHelper.getSdDir(newCacheId);
9647            }
9648            if (newMountPath == null) {
9649                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9650                return false;
9651            }
9652            Log.i(TAG, "Succesfully renamed " + cid +
9653                    " to " + newCacheId +
9654                    " at new path: " + newMountPath);
9655            cid = newCacheId;
9656
9657            final File beforeCodeFile = new File(packagePath);
9658            setMountPath(newMountPath);
9659            final File afterCodeFile = new File(packagePath);
9660
9661            // Reflect the rename in scanned details
9662            pkg.codePath = afterCodeFile.getAbsolutePath();
9663            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9664                    pkg.baseCodePath);
9665            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9666                    pkg.splitCodePaths);
9667
9668            // Reflect the rename in app info
9669            pkg.applicationInfo.setCodePath(pkg.codePath);
9670            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9671            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9672            pkg.applicationInfo.setResourcePath(pkg.codePath);
9673            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9674            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9675
9676            return true;
9677        }
9678
9679        private void setMountPath(String mountPath) {
9680            final File mountFile = new File(mountPath);
9681
9682            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9683            if (monolithicFile.exists()) {
9684                packagePath = monolithicFile.getAbsolutePath();
9685                if (isFwdLocked()) {
9686                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9687                } else {
9688                    resourcePath = packagePath;
9689                }
9690            } else {
9691                packagePath = mountFile.getAbsolutePath();
9692                resourcePath = packagePath;
9693            }
9694
9695            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9696        }
9697
9698        int doPostInstall(int status, int uid) {
9699            if (status != PackageManager.INSTALL_SUCCEEDED) {
9700                cleanUp();
9701            } else {
9702                final int groupOwner;
9703                final String protectedFile;
9704                if (isFwdLocked()) {
9705                    groupOwner = UserHandle.getSharedAppGid(uid);
9706                    protectedFile = RES_FILE_NAME;
9707                } else {
9708                    groupOwner = -1;
9709                    protectedFile = null;
9710                }
9711
9712                if (uid < Process.FIRST_APPLICATION_UID
9713                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9714                    Slog.e(TAG, "Failed to finalize " + cid);
9715                    PackageHelper.destroySdDir(cid);
9716                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9717                }
9718
9719                boolean mounted = PackageHelper.isContainerMounted(cid);
9720                if (!mounted) {
9721                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9722                }
9723            }
9724            return status;
9725        }
9726
9727        private void cleanUp() {
9728            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9729
9730            // Destroy secure container
9731            PackageHelper.destroySdDir(cid);
9732        }
9733
9734        private List<String> getAllCodePaths() {
9735            final File codeFile = new File(getCodePath());
9736            if (codeFile != null && codeFile.exists()) {
9737                try {
9738                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9739                    return pkg.getAllCodePaths();
9740                } catch (PackageParserException e) {
9741                    // Ignored; we tried our best
9742                }
9743            }
9744            return Collections.EMPTY_LIST;
9745        }
9746
9747        void cleanUpResourcesLI() {
9748            // Enumerate all code paths before deleting
9749            cleanUpResourcesLI(getAllCodePaths());
9750        }
9751
9752        private void cleanUpResourcesLI(List<String> allCodePaths) {
9753            cleanUp();
9754
9755            if (!allCodePaths.isEmpty()) {
9756                if (instructionSets == null) {
9757                    throw new IllegalStateException("instructionSet == null");
9758                }
9759                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9760                for (String codePath : allCodePaths) {
9761                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9762                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9763                        if (retCode < 0) {
9764                            Slog.w(TAG, "Couldn't remove dex file for package: "
9765                                    + " at location " + codePath + ", retcode=" + retCode);
9766                            // we don't consider this to be a failure of the core package deletion
9767                        }
9768                    }
9769                }
9770            }
9771        }
9772
9773        boolean matchContainer(String app) {
9774            if (cid.startsWith(app)) {
9775                return true;
9776            }
9777            return false;
9778        }
9779
9780        String getPackageName() {
9781            return getAsecPackageName(cid);
9782        }
9783
9784        boolean doPostDeleteLI(boolean delete) {
9785            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9786            final List<String> allCodePaths = getAllCodePaths();
9787            boolean mounted = PackageHelper.isContainerMounted(cid);
9788            if (mounted) {
9789                // Unmount first
9790                if (PackageHelper.unMountSdDir(cid)) {
9791                    mounted = false;
9792                }
9793            }
9794            if (!mounted && delete) {
9795                cleanUpResourcesLI(allCodePaths);
9796            }
9797            return !mounted;
9798        }
9799
9800        @Override
9801        int doPreCopy() {
9802            if (isFwdLocked()) {
9803                if (!PackageHelper.fixSdPermissions(cid,
9804                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9805                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9806                }
9807            }
9808
9809            return PackageManager.INSTALL_SUCCEEDED;
9810        }
9811
9812        @Override
9813        int doPostCopy(int uid) {
9814            if (isFwdLocked()) {
9815                if (uid < Process.FIRST_APPLICATION_UID
9816                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9817                                RES_FILE_NAME)) {
9818                    Slog.e(TAG, "Failed to finalize " + cid);
9819                    PackageHelper.destroySdDir(cid);
9820                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9821                }
9822            }
9823
9824            return PackageManager.INSTALL_SUCCEEDED;
9825        }
9826    }
9827
9828    static String getAsecPackageName(String packageCid) {
9829        int idx = packageCid.lastIndexOf("-");
9830        if (idx == -1) {
9831            return packageCid;
9832        }
9833        return packageCid.substring(0, idx);
9834    }
9835
9836    // Utility method used to create code paths based on package name and available index.
9837    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9838        String idxStr = "";
9839        int idx = 1;
9840        // Fall back to default value of idx=1 if prefix is not
9841        // part of oldCodePath
9842        if (oldCodePath != null) {
9843            String subStr = oldCodePath;
9844            // Drop the suffix right away
9845            if (suffix != null && subStr.endsWith(suffix)) {
9846                subStr = subStr.substring(0, subStr.length() - suffix.length());
9847            }
9848            // If oldCodePath already contains prefix find out the
9849            // ending index to either increment or decrement.
9850            int sidx = subStr.lastIndexOf(prefix);
9851            if (sidx != -1) {
9852                subStr = subStr.substring(sidx + prefix.length());
9853                if (subStr != null) {
9854                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9855                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9856                    }
9857                    try {
9858                        idx = Integer.parseInt(subStr);
9859                        if (idx <= 1) {
9860                            idx++;
9861                        } else {
9862                            idx--;
9863                        }
9864                    } catch(NumberFormatException e) {
9865                    }
9866                }
9867            }
9868        }
9869        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9870        return prefix + idxStr;
9871    }
9872
9873    private File getNextCodePath(String packageName) {
9874        int suffix = 1;
9875        File result;
9876        do {
9877            result = new File(mAppInstallDir, packageName + "-" + suffix);
9878            suffix++;
9879        } while (result.exists());
9880        return result;
9881    }
9882
9883    // Utility method used to ignore ADD/REMOVE events
9884    // by directory observer.
9885    private static boolean ignoreCodePath(String fullPathStr) {
9886        String apkName = deriveCodePathName(fullPathStr);
9887        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9888        if (idx != -1 && ((idx+1) < apkName.length())) {
9889            // Make sure the package ends with a numeral
9890            String version = apkName.substring(idx+1);
9891            try {
9892                Integer.parseInt(version);
9893                return true;
9894            } catch (NumberFormatException e) {}
9895        }
9896        return false;
9897    }
9898
9899    // Utility method that returns the relative package path with respect
9900    // to the installation directory. Like say for /data/data/com.test-1.apk
9901    // string com.test-1 is returned.
9902    static String deriveCodePathName(String codePath) {
9903        if (codePath == null) {
9904            return null;
9905        }
9906        final File codeFile = new File(codePath);
9907        final String name = codeFile.getName();
9908        if (codeFile.isDirectory()) {
9909            return name;
9910        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9911            final int lastDot = name.lastIndexOf('.');
9912            return name.substring(0, lastDot);
9913        } else {
9914            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9915            return null;
9916        }
9917    }
9918
9919    class PackageInstalledInfo {
9920        String name;
9921        int uid;
9922        // The set of users that originally had this package installed.
9923        int[] origUsers;
9924        // The set of users that now have this package installed.
9925        int[] newUsers;
9926        PackageParser.Package pkg;
9927        int returnCode;
9928        String returnMsg;
9929        PackageRemovedInfo removedInfo;
9930
9931        public void setError(int code, String msg) {
9932            returnCode = code;
9933            returnMsg = msg;
9934            Slog.w(TAG, msg);
9935        }
9936
9937        public void setError(String msg, PackageParserException e) {
9938            returnCode = e.error;
9939            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9940            Slog.w(TAG, msg, e);
9941        }
9942
9943        public void setError(String msg, PackageManagerException e) {
9944            returnCode = e.error;
9945            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9946            Slog.w(TAG, msg, e);
9947        }
9948
9949        // In some error cases we want to convey more info back to the observer
9950        String origPackage;
9951        String origPermission;
9952    }
9953
9954    /*
9955     * Install a non-existing package.
9956     */
9957    private void installNewPackageLI(PackageParser.Package pkg,
9958            int parseFlags, int scanFlags, UserHandle user,
9959            String installerPackageName, PackageInstalledInfo res) {
9960        // Remember this for later, in case we need to rollback this install
9961        String pkgName = pkg.packageName;
9962
9963        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9964        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9965        synchronized(mPackages) {
9966            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9967                // A package with the same name is already installed, though
9968                // it has been renamed to an older name.  The package we
9969                // are trying to install should be installed as an update to
9970                // the existing one, but that has not been requested, so bail.
9971                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9972                        + " without first uninstalling package running as "
9973                        + mSettings.mRenamedPackages.get(pkgName));
9974                return;
9975            }
9976            if (mPackages.containsKey(pkgName)) {
9977                // Don't allow installation over an existing package with the same name.
9978                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9979                        + " without first uninstalling.");
9980                return;
9981            }
9982        }
9983
9984        try {
9985            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9986                    System.currentTimeMillis(), user);
9987
9988            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9989            // delete the partially installed application. the data directory will have to be
9990            // restored if it was already existing
9991            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9992                // remove package from internal structures.  Note that we want deletePackageX to
9993                // delete the package data and cache directories that it created in
9994                // scanPackageLocked, unless those directories existed before we even tried to
9995                // install.
9996                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9997                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9998                                res.removedInfo, true);
9999            }
10000
10001        } catch (PackageManagerException e) {
10002            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10003        }
10004    }
10005
10006    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10007        // Upgrade keysets are being used.  Determine if new package has a superset of the
10008        // required keys.
10009        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10010        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10011        for (int i = 0; i < upgradeKeySets.length; i++) {
10012            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10013            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10014                return true;
10015            }
10016        }
10017        return false;
10018    }
10019
10020    private void replacePackageLI(PackageParser.Package pkg,
10021            int parseFlags, int scanFlags, UserHandle user,
10022            String installerPackageName, PackageInstalledInfo res) {
10023        PackageParser.Package oldPackage;
10024        String pkgName = pkg.packageName;
10025        int[] allUsers;
10026        boolean[] perUserInstalled;
10027
10028        // First find the old package info and check signatures
10029        synchronized(mPackages) {
10030            oldPackage = mPackages.get(pkgName);
10031            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10032            PackageSetting ps = mSettings.mPackages.get(pkgName);
10033            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10034                // default to original signature matching
10035                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10036                    != PackageManager.SIGNATURE_MATCH) {
10037                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10038                            "New package has a different signature: " + pkgName);
10039                    return;
10040                }
10041            } else {
10042                if(!checkUpgradeKeySetLP(ps, pkg)) {
10043                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10044                            "New package not signed by keys specified by upgrade-keysets: "
10045                            + pkgName);
10046                    return;
10047                }
10048            }
10049
10050            // In case of rollback, remember per-user/profile install state
10051            allUsers = sUserManager.getUserIds();
10052            perUserInstalled = new boolean[allUsers.length];
10053            for (int i = 0; i < allUsers.length; i++) {
10054                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10055            }
10056        }
10057
10058        boolean sysPkg = (isSystemApp(oldPackage));
10059        if (sysPkg) {
10060            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10061                    user, allUsers, perUserInstalled, installerPackageName, res);
10062        } else {
10063            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10064                    user, allUsers, perUserInstalled, installerPackageName, res);
10065        }
10066    }
10067
10068    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10069            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10070            int[] allUsers, boolean[] perUserInstalled,
10071            String installerPackageName, PackageInstalledInfo res) {
10072        String pkgName = deletedPackage.packageName;
10073        boolean deletedPkg = true;
10074        boolean updatedSettings = false;
10075
10076        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10077                + deletedPackage);
10078        long origUpdateTime;
10079        if (pkg.mExtras != null) {
10080            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10081        } else {
10082            origUpdateTime = 0;
10083        }
10084
10085        // First delete the existing package while retaining the data directory
10086        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10087                res.removedInfo, true)) {
10088            // If the existing package wasn't successfully deleted
10089            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10090            deletedPkg = false;
10091        } else {
10092            // Successfully deleted the old package; proceed with replace.
10093
10094            // If deleted package lived in a container, give users a chance to
10095            // relinquish resources before killing.
10096            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10097                if (DEBUG_INSTALL) {
10098                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10099                }
10100                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10101                final ArrayList<String> pkgList = new ArrayList<String>(1);
10102                pkgList.add(deletedPackage.applicationInfo.packageName);
10103                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10104            }
10105
10106            deleteCodeCacheDirsLI(pkgName);
10107            try {
10108                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10109                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10110                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10111                updatedSettings = true;
10112            } catch (PackageManagerException e) {
10113                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10114            }
10115        }
10116
10117        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10118            // remove package from internal structures.  Note that we want deletePackageX to
10119            // delete the package data and cache directories that it created in
10120            // scanPackageLocked, unless those directories existed before we even tried to
10121            // install.
10122            if(updatedSettings) {
10123                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10124                deletePackageLI(
10125                        pkgName, null, true, allUsers, perUserInstalled,
10126                        PackageManager.DELETE_KEEP_DATA,
10127                                res.removedInfo, true);
10128            }
10129            // Since we failed to install the new package we need to restore the old
10130            // package that we deleted.
10131            if (deletedPkg) {
10132                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10133                File restoreFile = new File(deletedPackage.codePath);
10134                // Parse old package
10135                boolean oldOnSd = isExternal(deletedPackage);
10136                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10137                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10138                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10139                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10140                try {
10141                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10142                } catch (PackageManagerException e) {
10143                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10144                            + e.getMessage());
10145                    return;
10146                }
10147                // Restore of old package succeeded. Update permissions.
10148                // writer
10149                synchronized (mPackages) {
10150                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10151                            UPDATE_PERMISSIONS_ALL);
10152                    // can downgrade to reader
10153                    mSettings.writeLPr();
10154                }
10155                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10156            }
10157        }
10158    }
10159
10160    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10161            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10162            int[] allUsers, boolean[] perUserInstalled,
10163            String installerPackageName, PackageInstalledInfo res) {
10164        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10165                + ", old=" + deletedPackage);
10166        boolean disabledSystem = false;
10167        boolean updatedSettings = false;
10168        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10169        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10170            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10171        }
10172        String packageName = deletedPackage.packageName;
10173        if (packageName == null) {
10174            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10175                    "Attempt to delete null packageName.");
10176            return;
10177        }
10178        PackageParser.Package oldPkg;
10179        PackageSetting oldPkgSetting;
10180        // reader
10181        synchronized (mPackages) {
10182            oldPkg = mPackages.get(packageName);
10183            oldPkgSetting = mSettings.mPackages.get(packageName);
10184            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10185                    (oldPkgSetting == null)) {
10186                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10187                        "Couldn't find package:" + packageName + " information");
10188                return;
10189            }
10190        }
10191
10192        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10193
10194        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10195        res.removedInfo.removedPackage = packageName;
10196        // Remove existing system package
10197        removePackageLI(oldPkgSetting, true);
10198        // writer
10199        synchronized (mPackages) {
10200            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10201            if (!disabledSystem && deletedPackage != null) {
10202                // We didn't need to disable the .apk as a current system package,
10203                // which means we are replacing another update that is already
10204                // installed.  We need to make sure to delete the older one's .apk.
10205                res.removedInfo.args = createInstallArgsForExisting(0,
10206                        deletedPackage.applicationInfo.getCodePath(),
10207                        deletedPackage.applicationInfo.getResourcePath(),
10208                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10209                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10210            } else {
10211                res.removedInfo.args = null;
10212            }
10213        }
10214
10215        // Successfully disabled the old package. Now proceed with re-installation
10216        deleteCodeCacheDirsLI(packageName);
10217
10218        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10219        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10220
10221        PackageParser.Package newPackage = null;
10222        try {
10223            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10224            if (newPackage.mExtras != null) {
10225                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10226                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10227                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10228
10229                // is the update attempting to change shared user? that isn't going to work...
10230                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10231                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10232                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10233                            + " to " + newPkgSetting.sharedUser);
10234                    updatedSettings = true;
10235                }
10236            }
10237
10238            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10239                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10240                updatedSettings = true;
10241            }
10242
10243        } catch (PackageManagerException e) {
10244            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10245        }
10246
10247        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10248            // Re installation failed. Restore old information
10249            // Remove new pkg information
10250            if (newPackage != null) {
10251                removeInstalledPackageLI(newPackage, true);
10252            }
10253            // Add back the old system package
10254            try {
10255                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10256            } catch (PackageManagerException e) {
10257                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10258            }
10259            // Restore the old system information in Settings
10260            synchronized (mPackages) {
10261                if (disabledSystem) {
10262                    mSettings.enableSystemPackageLPw(packageName);
10263                }
10264                if (updatedSettings) {
10265                    mSettings.setInstallerPackageName(packageName,
10266                            oldPkgSetting.installerPackageName);
10267                }
10268                mSettings.writeLPr();
10269            }
10270        }
10271    }
10272
10273    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10274            int[] allUsers, boolean[] perUserInstalled,
10275            PackageInstalledInfo res) {
10276        String pkgName = newPackage.packageName;
10277        synchronized (mPackages) {
10278            //write settings. the installStatus will be incomplete at this stage.
10279            //note that the new package setting would have already been
10280            //added to mPackages. It hasn't been persisted yet.
10281            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10282            mSettings.writeLPr();
10283        }
10284
10285        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10286
10287        synchronized (mPackages) {
10288            updatePermissionsLPw(newPackage.packageName, newPackage,
10289                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10290                            ? UPDATE_PERMISSIONS_ALL : 0));
10291            // For system-bundled packages, we assume that installing an upgraded version
10292            // of the package implies that the user actually wants to run that new code,
10293            // so we enable the package.
10294            if (isSystemApp(newPackage)) {
10295                // NB: implicit assumption that system package upgrades apply to all users
10296                if (DEBUG_INSTALL) {
10297                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10298                }
10299                PackageSetting ps = mSettings.mPackages.get(pkgName);
10300                if (ps != null) {
10301                    if (res.origUsers != null) {
10302                        for (int userHandle : res.origUsers) {
10303                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10304                                    userHandle, installerPackageName);
10305                        }
10306                    }
10307                    // Also convey the prior install/uninstall state
10308                    if (allUsers != null && perUserInstalled != null) {
10309                        for (int i = 0; i < allUsers.length; i++) {
10310                            if (DEBUG_INSTALL) {
10311                                Slog.d(TAG, "    user " + allUsers[i]
10312                                        + " => " + perUserInstalled[i]);
10313                            }
10314                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10315                        }
10316                        // these install state changes will be persisted in the
10317                        // upcoming call to mSettings.writeLPr().
10318                    }
10319                }
10320            }
10321            res.name = pkgName;
10322            res.uid = newPackage.applicationInfo.uid;
10323            res.pkg = newPackage;
10324            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10325            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10326            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10327            //to update install status
10328            mSettings.writeLPr();
10329        }
10330    }
10331
10332    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10333        final int installFlags = args.installFlags;
10334        String installerPackageName = args.installerPackageName;
10335        File tmpPackageFile = new File(args.getCodePath());
10336        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10337        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10338        boolean replace = false;
10339        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10340        // Result object to be returned
10341        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10342
10343        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10344        // Retrieve PackageSettings and parse package
10345        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10346                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10347                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10348        PackageParser pp = new PackageParser();
10349        pp.setSeparateProcesses(mSeparateProcesses);
10350        pp.setDisplayMetrics(mMetrics);
10351
10352        final PackageParser.Package pkg;
10353        try {
10354            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10355        } catch (PackageParserException e) {
10356            res.setError("Failed parse during installPackageLI", e);
10357            return;
10358        }
10359
10360        // Mark that we have an install time CPU ABI override.
10361        pkg.cpuAbiOverride = args.abiOverride;
10362
10363        String pkgName = res.name = pkg.packageName;
10364        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10365            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10366                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10367                return;
10368            }
10369        }
10370
10371        try {
10372            pp.collectCertificates(pkg, parseFlags);
10373            pp.collectManifestDigest(pkg);
10374        } catch (PackageParserException e) {
10375            res.setError("Failed collect during installPackageLI", e);
10376            return;
10377        }
10378
10379        /* If the installer passed in a manifest digest, compare it now. */
10380        if (args.manifestDigest != null) {
10381            if (DEBUG_INSTALL) {
10382                final String parsedManifest = pkg.manifestDigest == null ? "null"
10383                        : pkg.manifestDigest.toString();
10384                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10385                        + parsedManifest);
10386            }
10387
10388            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10389                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10390                return;
10391            }
10392        } else if (DEBUG_INSTALL) {
10393            final String parsedManifest = pkg.manifestDigest == null
10394                    ? "null" : pkg.manifestDigest.toString();
10395            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10396        }
10397
10398        // Get rid of all references to package scan path via parser.
10399        pp = null;
10400        String oldCodePath = null;
10401        boolean systemApp = false;
10402        synchronized (mPackages) {
10403            // Check whether the newly-scanned package wants to define an already-defined perm
10404            int N = pkg.permissions.size();
10405            for (int i = N-1; i >= 0; i--) {
10406                PackageParser.Permission perm = pkg.permissions.get(i);
10407                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10408                if (bp != null) {
10409                    // If the defining package is signed with our cert, it's okay.  This
10410                    // also includes the "updating the same package" case, of course.
10411                    // "updating same package" could also involve key-rotation.
10412                    final boolean sigsOk;
10413                    if (!bp.sourcePackage.equals(pkg.packageName)
10414                            || !(bp.packageSetting instanceof PackageSetting)
10415                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10416                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10417                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10418                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10419                    } else {
10420                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10421                    }
10422                    if (!sigsOk) {
10423                        // If the owning package is the system itself, we log but allow
10424                        // install to proceed; we fail the install on all other permission
10425                        // redefinitions.
10426                        if (!bp.sourcePackage.equals("android")) {
10427                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10428                                    + pkg.packageName + " attempting to redeclare permission "
10429                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10430                            res.origPermission = perm.info.name;
10431                            res.origPackage = bp.sourcePackage;
10432                            return;
10433                        } else {
10434                            Slog.w(TAG, "Package " + pkg.packageName
10435                                    + " attempting to redeclare system permission "
10436                                    + perm.info.name + "; ignoring new declaration");
10437                            pkg.permissions.remove(i);
10438                        }
10439                    }
10440                }
10441            }
10442
10443            // Check if installing already existing package
10444            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10445                String oldName = mSettings.mRenamedPackages.get(pkgName);
10446                if (pkg.mOriginalPackages != null
10447                        && pkg.mOriginalPackages.contains(oldName)
10448                        && mPackages.containsKey(oldName)) {
10449                    // This package is derived from an original package,
10450                    // and this device has been updating from that original
10451                    // name.  We must continue using the original name, so
10452                    // rename the new package here.
10453                    pkg.setPackageName(oldName);
10454                    pkgName = pkg.packageName;
10455                    replace = true;
10456                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10457                            + oldName + " pkgName=" + pkgName);
10458                } else if (mPackages.containsKey(pkgName)) {
10459                    // This package, under its official name, already exists
10460                    // on the device; we should replace it.
10461                    replace = true;
10462                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10463                }
10464            }
10465            PackageSetting ps = mSettings.mPackages.get(pkgName);
10466            if (ps != null) {
10467                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10468                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10469                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10470                    systemApp = (ps.pkg.applicationInfo.flags &
10471                            ApplicationInfo.FLAG_SYSTEM) != 0;
10472                }
10473                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10474            }
10475        }
10476
10477        if (systemApp && onSd) {
10478            // Disable updates to system apps on sdcard
10479            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10480                    "Cannot install updates to system apps on sdcard");
10481            return;
10482        }
10483
10484        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10485            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10486            return;
10487        }
10488
10489        if (replace) {
10490            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10491                    installerPackageName, res);
10492        } else {
10493            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10494                    args.user, installerPackageName, res);
10495        }
10496        synchronized (mPackages) {
10497            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10498            if (ps != null) {
10499                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10500            }
10501        }
10502    }
10503
10504    private static boolean isForwardLocked(PackageParser.Package pkg) {
10505        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10506    }
10507
10508    private static boolean isForwardLocked(ApplicationInfo info) {
10509        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10510    }
10511
10512    private boolean isForwardLocked(PackageSetting ps) {
10513        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10514    }
10515
10516    private static boolean isMultiArch(PackageSetting ps) {
10517        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10518    }
10519
10520    private static boolean isMultiArch(ApplicationInfo info) {
10521        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10522    }
10523
10524    private static boolean isExternal(PackageParser.Package pkg) {
10525        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10526    }
10527
10528    private static boolean isExternal(PackageSetting ps) {
10529        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10530    }
10531
10532    private static boolean isExternal(ApplicationInfo info) {
10533        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10534    }
10535
10536    private static boolean isSystemApp(PackageParser.Package pkg) {
10537        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10538    }
10539
10540    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10541        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10542    }
10543
10544    private static boolean isSystemApp(ApplicationInfo info) {
10545        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10546    }
10547
10548    private static boolean isSystemApp(PackageSetting ps) {
10549        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10550    }
10551
10552    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10553        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10554    }
10555
10556    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10557        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10558    }
10559
10560    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10561        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10562    }
10563
10564    private int packageFlagsToInstallFlags(PackageSetting ps) {
10565        int installFlags = 0;
10566        if (isExternal(ps)) {
10567            installFlags |= PackageManager.INSTALL_EXTERNAL;
10568        }
10569        if (isForwardLocked(ps)) {
10570            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10571        }
10572        return installFlags;
10573    }
10574
10575    private void deleteTempPackageFiles() {
10576        final FilenameFilter filter = new FilenameFilter() {
10577            public boolean accept(File dir, String name) {
10578                return name.startsWith("vmdl") && name.endsWith(".tmp");
10579            }
10580        };
10581        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10582            file.delete();
10583        }
10584    }
10585
10586    @Override
10587    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10588            int flags) {
10589        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10590                flags);
10591    }
10592
10593    @Override
10594    public void deletePackage(final String packageName,
10595            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10596        mContext.enforceCallingOrSelfPermission(
10597                android.Manifest.permission.DELETE_PACKAGES, null);
10598        final int uid = Binder.getCallingUid();
10599        if (UserHandle.getUserId(uid) != userId) {
10600            mContext.enforceCallingPermission(
10601                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10602                    "deletePackage for user " + userId);
10603        }
10604        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10605            try {
10606                observer.onPackageDeleted(packageName,
10607                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10608            } catch (RemoteException re) {
10609            }
10610            return;
10611        }
10612
10613        boolean uninstallBlocked = false;
10614        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10615            int[] users = sUserManager.getUserIds();
10616            for (int i = 0; i < users.length; ++i) {
10617                if (getBlockUninstallForUser(packageName, users[i])) {
10618                    uninstallBlocked = true;
10619                    break;
10620                }
10621            }
10622        } else {
10623            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10624        }
10625        if (uninstallBlocked) {
10626            try {
10627                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10628                        null);
10629            } catch (RemoteException re) {
10630            }
10631            return;
10632        }
10633
10634        if (DEBUG_REMOVE) {
10635            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10636        }
10637        // Queue up an async operation since the package deletion may take a little while.
10638        mHandler.post(new Runnable() {
10639            public void run() {
10640                mHandler.removeCallbacks(this);
10641                final int returnCode = deletePackageX(packageName, userId, flags);
10642                if (observer != null) {
10643                    try {
10644                        observer.onPackageDeleted(packageName, returnCode, null);
10645                    } catch (RemoteException e) {
10646                        Log.i(TAG, "Observer no longer exists.");
10647                    } //end catch
10648                } //end if
10649            } //end run
10650        });
10651    }
10652
10653    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10654        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10655                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10656        try {
10657            if (dpm != null) {
10658                if (dpm.isDeviceOwner(packageName)) {
10659                    return true;
10660                }
10661                int[] users;
10662                if (userId == UserHandle.USER_ALL) {
10663                    users = sUserManager.getUserIds();
10664                } else {
10665                    users = new int[]{userId};
10666                }
10667                for (int i = 0; i < users.length; ++i) {
10668                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10669                        return true;
10670                    }
10671                }
10672            }
10673        } catch (RemoteException e) {
10674        }
10675        return false;
10676    }
10677
10678    /**
10679     *  This method is an internal method that could be get invoked either
10680     *  to delete an installed package or to clean up a failed installation.
10681     *  After deleting an installed package, a broadcast is sent to notify any
10682     *  listeners that the package has been installed. For cleaning up a failed
10683     *  installation, the broadcast is not necessary since the package's
10684     *  installation wouldn't have sent the initial broadcast either
10685     *  The key steps in deleting a package are
10686     *  deleting the package information in internal structures like mPackages,
10687     *  deleting the packages base directories through installd
10688     *  updating mSettings to reflect current status
10689     *  persisting settings for later use
10690     *  sending a broadcast if necessary
10691     */
10692    private int deletePackageX(String packageName, int userId, int flags) {
10693        final PackageRemovedInfo info = new PackageRemovedInfo();
10694        final boolean res;
10695
10696        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10697                ? UserHandle.ALL : new UserHandle(userId);
10698
10699        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10700            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10701            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10702        }
10703
10704        boolean removedForAllUsers = false;
10705        boolean systemUpdate = false;
10706
10707        // for the uninstall-updates case and restricted profiles, remember the per-
10708        // userhandle installed state
10709        int[] allUsers;
10710        boolean[] perUserInstalled;
10711        synchronized (mPackages) {
10712            PackageSetting ps = mSettings.mPackages.get(packageName);
10713            allUsers = sUserManager.getUserIds();
10714            perUserInstalled = new boolean[allUsers.length];
10715            for (int i = 0; i < allUsers.length; i++) {
10716                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10717            }
10718        }
10719
10720        synchronized (mInstallLock) {
10721            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10722            res = deletePackageLI(packageName, removeForUser,
10723                    true, allUsers, perUserInstalled,
10724                    flags | REMOVE_CHATTY, info, true);
10725            systemUpdate = info.isRemovedPackageSystemUpdate;
10726            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10727                removedForAllUsers = true;
10728            }
10729            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10730                    + " removedForAllUsers=" + removedForAllUsers);
10731        }
10732
10733        if (res) {
10734            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10735
10736            // If the removed package was a system update, the old system package
10737            // was re-enabled; we need to broadcast this information
10738            if (systemUpdate) {
10739                Bundle extras = new Bundle(1);
10740                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10741                        ? info.removedAppId : info.uid);
10742                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10743
10744                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10745                        extras, null, null, null);
10746                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10747                        extras, null, null, null);
10748                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10749                        null, packageName, null, null);
10750            }
10751        }
10752        // Force a gc here.
10753        Runtime.getRuntime().gc();
10754        // Delete the resources here after sending the broadcast to let
10755        // other processes clean up before deleting resources.
10756        if (info.args != null) {
10757            synchronized (mInstallLock) {
10758                info.args.doPostDeleteLI(true);
10759            }
10760        }
10761
10762        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10763    }
10764
10765    static class PackageRemovedInfo {
10766        String removedPackage;
10767        int uid = -1;
10768        int removedAppId = -1;
10769        int[] removedUsers = null;
10770        boolean isRemovedPackageSystemUpdate = false;
10771        // Clean up resources deleted packages.
10772        InstallArgs args = null;
10773
10774        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10775            Bundle extras = new Bundle(1);
10776            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10777            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10778            if (replacing) {
10779                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10780            }
10781            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10782            if (removedPackage != null) {
10783                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10784                        extras, null, null, removedUsers);
10785                if (fullRemove && !replacing) {
10786                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10787                            extras, null, null, removedUsers);
10788                }
10789            }
10790            if (removedAppId >= 0) {
10791                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10792                        removedUsers);
10793            }
10794        }
10795    }
10796
10797    /*
10798     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10799     * flag is not set, the data directory is removed as well.
10800     * make sure this flag is set for partially installed apps. If not its meaningless to
10801     * delete a partially installed application.
10802     */
10803    private void removePackageDataLI(PackageSetting ps,
10804            int[] allUserHandles, boolean[] perUserInstalled,
10805            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10806        String packageName = ps.name;
10807        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10808        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10809        // Retrieve object to delete permissions for shared user later on
10810        final PackageSetting deletedPs;
10811        // reader
10812        synchronized (mPackages) {
10813            deletedPs = mSettings.mPackages.get(packageName);
10814            if (outInfo != null) {
10815                outInfo.removedPackage = packageName;
10816                outInfo.removedUsers = deletedPs != null
10817                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10818                        : null;
10819            }
10820        }
10821        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10822            removeDataDirsLI(packageName);
10823            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10824        }
10825        // writer
10826        synchronized (mPackages) {
10827            if (deletedPs != null) {
10828                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10829                    if (outInfo != null) {
10830                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10831                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10832                    }
10833                    if (deletedPs != null) {
10834                        updatePermissionsLPw(deletedPs.name, null, 0);
10835                        if (deletedPs.sharedUser != null) {
10836                            // remove permissions associated with package
10837                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10838                        }
10839                    }
10840                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10841                }
10842                // make sure to preserve per-user disabled state if this removal was just
10843                // a downgrade of a system app to the factory package
10844                if (allUserHandles != null && perUserInstalled != null) {
10845                    if (DEBUG_REMOVE) {
10846                        Slog.d(TAG, "Propagating install state across downgrade");
10847                    }
10848                    for (int i = 0; i < allUserHandles.length; i++) {
10849                        if (DEBUG_REMOVE) {
10850                            Slog.d(TAG, "    user " + allUserHandles[i]
10851                                    + " => " + perUserInstalled[i]);
10852                        }
10853                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10854                    }
10855                }
10856            }
10857            // can downgrade to reader
10858            if (writeSettings) {
10859                // Save settings now
10860                mSettings.writeLPr();
10861            }
10862        }
10863        if (outInfo != null) {
10864            // A user ID was deleted here. Go through all users and remove it
10865            // from KeyStore.
10866            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10867        }
10868    }
10869
10870    static boolean locationIsPrivileged(File path) {
10871        try {
10872            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10873                    .getCanonicalPath();
10874            return path.getCanonicalPath().startsWith(privilegedAppDir);
10875        } catch (IOException e) {
10876            Slog.e(TAG, "Unable to access code path " + path);
10877        }
10878        return false;
10879    }
10880
10881    /*
10882     * Tries to delete system package.
10883     */
10884    private boolean deleteSystemPackageLI(PackageSetting newPs,
10885            int[] allUserHandles, boolean[] perUserInstalled,
10886            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10887        final boolean applyUserRestrictions
10888                = (allUserHandles != null) && (perUserInstalled != null);
10889        PackageSetting disabledPs = null;
10890        // Confirm if the system package has been updated
10891        // An updated system app can be deleted. This will also have to restore
10892        // the system pkg from system partition
10893        // reader
10894        synchronized (mPackages) {
10895            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10896        }
10897        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10898                + " disabledPs=" + disabledPs);
10899        if (disabledPs == null) {
10900            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10901            return false;
10902        } else if (DEBUG_REMOVE) {
10903            Slog.d(TAG, "Deleting system pkg from data partition");
10904        }
10905        if (DEBUG_REMOVE) {
10906            if (applyUserRestrictions) {
10907                Slog.d(TAG, "Remembering install states:");
10908                for (int i = 0; i < allUserHandles.length; i++) {
10909                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10910                }
10911            }
10912        }
10913        // Delete the updated package
10914        outInfo.isRemovedPackageSystemUpdate = true;
10915        if (disabledPs.versionCode < newPs.versionCode) {
10916            // Delete data for downgrades
10917            flags &= ~PackageManager.DELETE_KEEP_DATA;
10918        } else {
10919            // Preserve data by setting flag
10920            flags |= PackageManager.DELETE_KEEP_DATA;
10921        }
10922        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10923                allUserHandles, perUserInstalled, outInfo, writeSettings);
10924        if (!ret) {
10925            return false;
10926        }
10927        // writer
10928        synchronized (mPackages) {
10929            // Reinstate the old system package
10930            mSettings.enableSystemPackageLPw(newPs.name);
10931            // Remove any native libraries from the upgraded package.
10932            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10933        }
10934        // Install the system package
10935        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10936        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10937        if (locationIsPrivileged(disabledPs.codePath)) {
10938            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10939        }
10940
10941        final PackageParser.Package newPkg;
10942        try {
10943            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10944        } catch (PackageManagerException e) {
10945            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10946            return false;
10947        }
10948
10949        // writer
10950        synchronized (mPackages) {
10951            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10952            updatePermissionsLPw(newPkg.packageName, newPkg,
10953                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10954            if (applyUserRestrictions) {
10955                if (DEBUG_REMOVE) {
10956                    Slog.d(TAG, "Propagating install state across reinstall");
10957                }
10958                for (int i = 0; i < allUserHandles.length; i++) {
10959                    if (DEBUG_REMOVE) {
10960                        Slog.d(TAG, "    user " + allUserHandles[i]
10961                                + " => " + perUserInstalled[i]);
10962                    }
10963                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10964                }
10965                // Regardless of writeSettings we need to ensure that this restriction
10966                // state propagation is persisted
10967                mSettings.writeAllUsersPackageRestrictionsLPr();
10968            }
10969            // can downgrade to reader here
10970            if (writeSettings) {
10971                mSettings.writeLPr();
10972            }
10973        }
10974        return true;
10975    }
10976
10977    private boolean deleteInstalledPackageLI(PackageSetting ps,
10978            boolean deleteCodeAndResources, int flags,
10979            int[] allUserHandles, boolean[] perUserInstalled,
10980            PackageRemovedInfo outInfo, boolean writeSettings) {
10981        if (outInfo != null) {
10982            outInfo.uid = ps.appId;
10983        }
10984
10985        // Delete package data from internal structures and also remove data if flag is set
10986        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10987
10988        // Delete application code and resources
10989        if (deleteCodeAndResources && (outInfo != null)) {
10990            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10991                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10992                    getAppDexInstructionSets(ps));
10993            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10994        }
10995        return true;
10996    }
10997
10998    @Override
10999    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11000            int userId) {
11001        mContext.enforceCallingOrSelfPermission(
11002                android.Manifest.permission.DELETE_PACKAGES, null);
11003        synchronized (mPackages) {
11004            PackageSetting ps = mSettings.mPackages.get(packageName);
11005            if (ps == null) {
11006                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11007                return false;
11008            }
11009            if (!ps.getInstalled(userId)) {
11010                // Can't block uninstall for an app that is not installed or enabled.
11011                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11012                return false;
11013            }
11014            ps.setBlockUninstall(blockUninstall, userId);
11015            mSettings.writePackageRestrictionsLPr(userId);
11016        }
11017        return true;
11018    }
11019
11020    @Override
11021    public boolean getBlockUninstallForUser(String packageName, int userId) {
11022        synchronized (mPackages) {
11023            PackageSetting ps = mSettings.mPackages.get(packageName);
11024            if (ps == null) {
11025                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11026                return false;
11027            }
11028            return ps.getBlockUninstall(userId);
11029        }
11030    }
11031
11032    /*
11033     * This method handles package deletion in general
11034     */
11035    private boolean deletePackageLI(String packageName, UserHandle user,
11036            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11037            int flags, PackageRemovedInfo outInfo,
11038            boolean writeSettings) {
11039        if (packageName == null) {
11040            Slog.w(TAG, "Attempt to delete null packageName.");
11041            return false;
11042        }
11043        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11044        PackageSetting ps;
11045        boolean dataOnly = false;
11046        int removeUser = -1;
11047        int appId = -1;
11048        synchronized (mPackages) {
11049            ps = mSettings.mPackages.get(packageName);
11050            if (ps == null) {
11051                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11052                return false;
11053            }
11054            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11055                    && user.getIdentifier() != UserHandle.USER_ALL) {
11056                // The caller is asking that the package only be deleted for a single
11057                // user.  To do this, we just mark its uninstalled state and delete
11058                // its data.  If this is a system app, we only allow this to happen if
11059                // they have set the special DELETE_SYSTEM_APP which requests different
11060                // semantics than normal for uninstalling system apps.
11061                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11062                ps.setUserState(user.getIdentifier(),
11063                        COMPONENT_ENABLED_STATE_DEFAULT,
11064                        false, //installed
11065                        true,  //stopped
11066                        true,  //notLaunched
11067                        false, //hidden
11068                        null, null, null,
11069                        false // blockUninstall
11070                        );
11071                if (!isSystemApp(ps)) {
11072                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11073                        // Other user still have this package installed, so all
11074                        // we need to do is clear this user's data and save that
11075                        // it is uninstalled.
11076                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11077                        removeUser = user.getIdentifier();
11078                        appId = ps.appId;
11079                        mSettings.writePackageRestrictionsLPr(removeUser);
11080                    } else {
11081                        // We need to set it back to 'installed' so the uninstall
11082                        // broadcasts will be sent correctly.
11083                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11084                        ps.setInstalled(true, user.getIdentifier());
11085                    }
11086                } else {
11087                    // This is a system app, so we assume that the
11088                    // other users still have this package installed, so all
11089                    // we need to do is clear this user's data and save that
11090                    // it is uninstalled.
11091                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11092                    removeUser = user.getIdentifier();
11093                    appId = ps.appId;
11094                    mSettings.writePackageRestrictionsLPr(removeUser);
11095                }
11096            }
11097        }
11098
11099        if (removeUser >= 0) {
11100            // From above, we determined that we are deleting this only
11101            // for a single user.  Continue the work here.
11102            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11103            if (outInfo != null) {
11104                outInfo.removedPackage = packageName;
11105                outInfo.removedAppId = appId;
11106                outInfo.removedUsers = new int[] {removeUser};
11107            }
11108            mInstaller.clearUserData(packageName, removeUser);
11109            removeKeystoreDataIfNeeded(removeUser, appId);
11110            schedulePackageCleaning(packageName, removeUser, false);
11111            return true;
11112        }
11113
11114        if (dataOnly) {
11115            // Delete application data first
11116            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11117            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11118            return true;
11119        }
11120
11121        boolean ret = false;
11122        if (isSystemApp(ps)) {
11123            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11124            // When an updated system application is deleted we delete the existing resources as well and
11125            // fall back to existing code in system partition
11126            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11127                    flags, outInfo, writeSettings);
11128        } else {
11129            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11130            // Kill application pre-emptively especially for apps on sd.
11131            killApplication(packageName, ps.appId, "uninstall pkg");
11132            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11133                    allUserHandles, perUserInstalled,
11134                    outInfo, writeSettings);
11135        }
11136
11137        return ret;
11138    }
11139
11140    private final class ClearStorageConnection implements ServiceConnection {
11141        IMediaContainerService mContainerService;
11142
11143        @Override
11144        public void onServiceConnected(ComponentName name, IBinder service) {
11145            synchronized (this) {
11146                mContainerService = IMediaContainerService.Stub.asInterface(service);
11147                notifyAll();
11148            }
11149        }
11150
11151        @Override
11152        public void onServiceDisconnected(ComponentName name) {
11153        }
11154    }
11155
11156    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11157        final boolean mounted;
11158        if (Environment.isExternalStorageEmulated()) {
11159            mounted = true;
11160        } else {
11161            final String status = Environment.getExternalStorageState();
11162
11163            mounted = status.equals(Environment.MEDIA_MOUNTED)
11164                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11165        }
11166
11167        if (!mounted) {
11168            return;
11169        }
11170
11171        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11172        int[] users;
11173        if (userId == UserHandle.USER_ALL) {
11174            users = sUserManager.getUserIds();
11175        } else {
11176            users = new int[] { userId };
11177        }
11178        final ClearStorageConnection conn = new ClearStorageConnection();
11179        if (mContext.bindServiceAsUser(
11180                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11181            try {
11182                for (int curUser : users) {
11183                    long timeout = SystemClock.uptimeMillis() + 5000;
11184                    synchronized (conn) {
11185                        long now = SystemClock.uptimeMillis();
11186                        while (conn.mContainerService == null && now < timeout) {
11187                            try {
11188                                conn.wait(timeout - now);
11189                            } catch (InterruptedException e) {
11190                            }
11191                        }
11192                    }
11193                    if (conn.mContainerService == null) {
11194                        return;
11195                    }
11196
11197                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11198                    clearDirectory(conn.mContainerService,
11199                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11200                    if (allData) {
11201                        clearDirectory(conn.mContainerService,
11202                                userEnv.buildExternalStorageAppDataDirs(packageName));
11203                        clearDirectory(conn.mContainerService,
11204                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11205                    }
11206                }
11207            } finally {
11208                mContext.unbindService(conn);
11209            }
11210        }
11211    }
11212
11213    @Override
11214    public void clearApplicationUserData(final String packageName,
11215            final IPackageDataObserver observer, final int userId) {
11216        mContext.enforceCallingOrSelfPermission(
11217                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11218        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11219        // Queue up an async operation since the package deletion may take a little while.
11220        mHandler.post(new Runnable() {
11221            public void run() {
11222                mHandler.removeCallbacks(this);
11223                final boolean succeeded;
11224                synchronized (mInstallLock) {
11225                    succeeded = clearApplicationUserDataLI(packageName, userId);
11226                }
11227                clearExternalStorageDataSync(packageName, userId, true);
11228                if (succeeded) {
11229                    // invoke DeviceStorageMonitor's update method to clear any notifications
11230                    DeviceStorageMonitorInternal
11231                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11232                    if (dsm != null) {
11233                        dsm.checkMemory();
11234                    }
11235                }
11236                if(observer != null) {
11237                    try {
11238                        observer.onRemoveCompleted(packageName, succeeded);
11239                    } catch (RemoteException e) {
11240                        Log.i(TAG, "Observer no longer exists.");
11241                    }
11242                } //end if observer
11243            } //end run
11244        });
11245    }
11246
11247    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11248        if (packageName == null) {
11249            Slog.w(TAG, "Attempt to delete null packageName.");
11250            return false;
11251        }
11252
11253        // Try finding details about the requested package
11254        PackageParser.Package pkg;
11255        synchronized (mPackages) {
11256            pkg = mPackages.get(packageName);
11257            if (pkg == null) {
11258                final PackageSetting ps = mSettings.mPackages.get(packageName);
11259                if (ps != null) {
11260                    pkg = ps.pkg;
11261                }
11262            }
11263        }
11264
11265        if (pkg == null) {
11266            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11267        }
11268
11269        // Always delete data directories for package, even if we found no other
11270        // record of app. This helps users recover from UID mismatches without
11271        // resorting to a full data wipe.
11272        int retCode = mInstaller.clearUserData(packageName, userId);
11273        if (retCode < 0) {
11274            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11275            return false;
11276        }
11277
11278        if (pkg == null) {
11279            return false;
11280        }
11281
11282        if (pkg != null && pkg.applicationInfo != null) {
11283            final int appId = pkg.applicationInfo.uid;
11284            removeKeystoreDataIfNeeded(userId, appId);
11285        }
11286
11287        // Create a native library symlink only if we have native libraries
11288        // and if the native libraries are 32 bit libraries. We do not provide
11289        // this symlink for 64 bit libraries.
11290        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11291                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11292            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11293            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11294                Slog.w(TAG, "Failed linking native library dir");
11295                return false;
11296            }
11297        }
11298
11299        return true;
11300    }
11301
11302    /**
11303     * Remove entries from the keystore daemon. Will only remove it if the
11304     * {@code appId} is valid.
11305     */
11306    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11307        if (appId < 0) {
11308            return;
11309        }
11310
11311        final KeyStore keyStore = KeyStore.getInstance();
11312        if (keyStore != null) {
11313            if (userId == UserHandle.USER_ALL) {
11314                for (final int individual : sUserManager.getUserIds()) {
11315                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11316                }
11317            } else {
11318                keyStore.clearUid(UserHandle.getUid(userId, appId));
11319            }
11320        } else {
11321            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11322        }
11323    }
11324
11325    @Override
11326    public void deleteApplicationCacheFiles(final String packageName,
11327            final IPackageDataObserver observer) {
11328        mContext.enforceCallingOrSelfPermission(
11329                android.Manifest.permission.DELETE_CACHE_FILES, null);
11330        // Queue up an async operation since the package deletion may take a little while.
11331        final int userId = UserHandle.getCallingUserId();
11332        mHandler.post(new Runnable() {
11333            public void run() {
11334                mHandler.removeCallbacks(this);
11335                final boolean succeded;
11336                synchronized (mInstallLock) {
11337                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11338                }
11339                clearExternalStorageDataSync(packageName, userId, false);
11340                if(observer != null) {
11341                    try {
11342                        observer.onRemoveCompleted(packageName, succeded);
11343                    } catch (RemoteException e) {
11344                        Log.i(TAG, "Observer no longer exists.");
11345                    }
11346                } //end if observer
11347            } //end run
11348        });
11349    }
11350
11351    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11352        if (packageName == null) {
11353            Slog.w(TAG, "Attempt to delete null packageName.");
11354            return false;
11355        }
11356        PackageParser.Package p;
11357        synchronized (mPackages) {
11358            p = mPackages.get(packageName);
11359        }
11360        if (p == null) {
11361            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11362            return false;
11363        }
11364        final ApplicationInfo applicationInfo = p.applicationInfo;
11365        if (applicationInfo == null) {
11366            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11367            return false;
11368        }
11369        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11370        if (retCode < 0) {
11371            Slog.w(TAG, "Couldn't remove cache files for package: "
11372                       + packageName + " u" + userId);
11373            return false;
11374        }
11375        return true;
11376    }
11377
11378    @Override
11379    public void getPackageSizeInfo(final String packageName, int userHandle,
11380            final IPackageStatsObserver observer) {
11381        mContext.enforceCallingOrSelfPermission(
11382                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11383        if (packageName == null) {
11384            throw new IllegalArgumentException("Attempt to get size of null packageName");
11385        }
11386
11387        PackageStats stats = new PackageStats(packageName, userHandle);
11388
11389        /*
11390         * Queue up an async operation since the package measurement may take a
11391         * little while.
11392         */
11393        Message msg = mHandler.obtainMessage(INIT_COPY);
11394        msg.obj = new MeasureParams(stats, observer);
11395        mHandler.sendMessage(msg);
11396    }
11397
11398    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11399            PackageStats pStats) {
11400        if (packageName == null) {
11401            Slog.w(TAG, "Attempt to get size of null packageName.");
11402            return false;
11403        }
11404        PackageParser.Package p;
11405        boolean dataOnly = false;
11406        String libDirRoot = null;
11407        String asecPath = null;
11408        PackageSetting ps = null;
11409        synchronized (mPackages) {
11410            p = mPackages.get(packageName);
11411            ps = mSettings.mPackages.get(packageName);
11412            if(p == null) {
11413                dataOnly = true;
11414                if((ps == null) || (ps.pkg == null)) {
11415                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11416                    return false;
11417                }
11418                p = ps.pkg;
11419            }
11420            if (ps != null) {
11421                libDirRoot = ps.legacyNativeLibraryPathString;
11422            }
11423            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11424                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11425                if (secureContainerId != null) {
11426                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11427                }
11428            }
11429        }
11430        String publicSrcDir = null;
11431        if(!dataOnly) {
11432            final ApplicationInfo applicationInfo = p.applicationInfo;
11433            if (applicationInfo == null) {
11434                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11435                return false;
11436            }
11437            if (isForwardLocked(p)) {
11438                publicSrcDir = applicationInfo.getBaseResourcePath();
11439            }
11440        }
11441        // TODO: extend to measure size of split APKs
11442        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11443        // not just the first level.
11444        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11445        // just the primary.
11446        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11447        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11448                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11449        if (res < 0) {
11450            return false;
11451        }
11452
11453        // Fix-up for forward-locked applications in ASEC containers.
11454        if (!isExternal(p)) {
11455            pStats.codeSize += pStats.externalCodeSize;
11456            pStats.externalCodeSize = 0L;
11457        }
11458
11459        return true;
11460    }
11461
11462
11463    @Override
11464    public void addPackageToPreferred(String packageName) {
11465        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11466    }
11467
11468    @Override
11469    public void removePackageFromPreferred(String packageName) {
11470        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11471    }
11472
11473    @Override
11474    public List<PackageInfo> getPreferredPackages(int flags) {
11475        return new ArrayList<PackageInfo>();
11476    }
11477
11478    private int getUidTargetSdkVersionLockedLPr(int uid) {
11479        Object obj = mSettings.getUserIdLPr(uid);
11480        if (obj instanceof SharedUserSetting) {
11481            final SharedUserSetting sus = (SharedUserSetting) obj;
11482            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11483            final Iterator<PackageSetting> it = sus.packages.iterator();
11484            while (it.hasNext()) {
11485                final PackageSetting ps = it.next();
11486                if (ps.pkg != null) {
11487                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11488                    if (v < vers) vers = v;
11489                }
11490            }
11491            return vers;
11492        } else if (obj instanceof PackageSetting) {
11493            final PackageSetting ps = (PackageSetting) obj;
11494            if (ps.pkg != null) {
11495                return ps.pkg.applicationInfo.targetSdkVersion;
11496            }
11497        }
11498        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11499    }
11500
11501    @Override
11502    public void addPreferredActivity(IntentFilter filter, int match,
11503            ComponentName[] set, ComponentName activity, int userId) {
11504        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11505                "Adding preferred");
11506    }
11507
11508    private void addPreferredActivityInternal(IntentFilter filter, int match,
11509            ComponentName[] set, ComponentName activity, boolean always, int userId,
11510            String opname) {
11511        // writer
11512        int callingUid = Binder.getCallingUid();
11513        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11514        if (filter.countActions() == 0) {
11515            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11516            return;
11517        }
11518        synchronized (mPackages) {
11519            if (mContext.checkCallingOrSelfPermission(
11520                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11521                    != PackageManager.PERMISSION_GRANTED) {
11522                if (getUidTargetSdkVersionLockedLPr(callingUid)
11523                        < Build.VERSION_CODES.FROYO) {
11524                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11525                            + callingUid);
11526                    return;
11527                }
11528                mContext.enforceCallingOrSelfPermission(
11529                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11530            }
11531
11532            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11533            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11534                    + userId + ":");
11535            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11536            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11537            mSettings.writePackageRestrictionsLPr(userId);
11538        }
11539    }
11540
11541    @Override
11542    public void replacePreferredActivity(IntentFilter filter, int match,
11543            ComponentName[] set, ComponentName activity, int userId) {
11544        if (filter.countActions() != 1) {
11545            throw new IllegalArgumentException(
11546                    "replacePreferredActivity expects filter to have only 1 action.");
11547        }
11548        if (filter.countDataAuthorities() != 0
11549                || filter.countDataPaths() != 0
11550                || filter.countDataSchemes() > 1
11551                || filter.countDataTypes() != 0) {
11552            throw new IllegalArgumentException(
11553                    "replacePreferredActivity expects filter to have no data authorities, " +
11554                    "paths, or types; and at most one scheme.");
11555        }
11556
11557        final int callingUid = Binder.getCallingUid();
11558        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11559        synchronized (mPackages) {
11560            if (mContext.checkCallingOrSelfPermission(
11561                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11562                    != PackageManager.PERMISSION_GRANTED) {
11563                if (getUidTargetSdkVersionLockedLPr(callingUid)
11564                        < Build.VERSION_CODES.FROYO) {
11565                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11566                            + Binder.getCallingUid());
11567                    return;
11568                }
11569                mContext.enforceCallingOrSelfPermission(
11570                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11571            }
11572
11573            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11574            if (pir != null) {
11575                // Get all of the existing entries that exactly match this filter.
11576                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11577                if (existing != null && existing.size() == 1) {
11578                    PreferredActivity cur = existing.get(0);
11579                    if (DEBUG_PREFERRED) {
11580                        Slog.i(TAG, "Checking replace of preferred:");
11581                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11582                        if (!cur.mPref.mAlways) {
11583                            Slog.i(TAG, "  -- CUR; not mAlways!");
11584                        } else {
11585                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11586                            Slog.i(TAG, "  -- CUR: mSet="
11587                                    + Arrays.toString(cur.mPref.mSetComponents));
11588                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11589                            Slog.i(TAG, "  -- NEW: mMatch="
11590                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11591                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11592                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11593                        }
11594                    }
11595                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11596                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11597                            && cur.mPref.sameSet(set)) {
11598                        // Setting the preferred activity to what it happens to be already
11599                        if (DEBUG_PREFERRED) {
11600                            Slog.i(TAG, "Replacing with same preferred activity "
11601                                    + cur.mPref.mShortComponent + " for user "
11602                                    + userId + ":");
11603                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11604                        }
11605                        return;
11606                    }
11607                }
11608
11609                if (existing != null) {
11610                    if (DEBUG_PREFERRED) {
11611                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11612                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11613                    }
11614                    for (int i = 0; i < existing.size(); i++) {
11615                        PreferredActivity pa = existing.get(i);
11616                        if (DEBUG_PREFERRED) {
11617                            Slog.i(TAG, "Removing existing preferred activity "
11618                                    + pa.mPref.mComponent + ":");
11619                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11620                        }
11621                        pir.removeFilter(pa);
11622                    }
11623                }
11624            }
11625            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11626                    "Replacing preferred");
11627        }
11628    }
11629
11630    @Override
11631    public void clearPackagePreferredActivities(String packageName) {
11632        final int uid = Binder.getCallingUid();
11633        // writer
11634        synchronized (mPackages) {
11635            PackageParser.Package pkg = mPackages.get(packageName);
11636            if (pkg == null || pkg.applicationInfo.uid != uid) {
11637                if (mContext.checkCallingOrSelfPermission(
11638                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11639                        != PackageManager.PERMISSION_GRANTED) {
11640                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11641                            < Build.VERSION_CODES.FROYO) {
11642                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11643                                + Binder.getCallingUid());
11644                        return;
11645                    }
11646                    mContext.enforceCallingOrSelfPermission(
11647                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11648                }
11649            }
11650
11651            int user = UserHandle.getCallingUserId();
11652            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11653                mSettings.writePackageRestrictionsLPr(user);
11654                scheduleWriteSettingsLocked();
11655            }
11656        }
11657    }
11658
11659    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11660    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11661        ArrayList<PreferredActivity> removed = null;
11662        boolean changed = false;
11663        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11664            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11665            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11666            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11667                continue;
11668            }
11669            Iterator<PreferredActivity> it = pir.filterIterator();
11670            while (it.hasNext()) {
11671                PreferredActivity pa = it.next();
11672                // Mark entry for removal only if it matches the package name
11673                // and the entry is of type "always".
11674                if (packageName == null ||
11675                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11676                                && pa.mPref.mAlways)) {
11677                    if (removed == null) {
11678                        removed = new ArrayList<PreferredActivity>();
11679                    }
11680                    removed.add(pa);
11681                }
11682            }
11683            if (removed != null) {
11684                for (int j=0; j<removed.size(); j++) {
11685                    PreferredActivity pa = removed.get(j);
11686                    pir.removeFilter(pa);
11687                }
11688                changed = true;
11689            }
11690        }
11691        return changed;
11692    }
11693
11694    @Override
11695    public void resetPreferredActivities(int userId) {
11696        /* TODO: Actually use userId. Why is it being passed in? */
11697        mContext.enforceCallingOrSelfPermission(
11698                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11699        // writer
11700        synchronized (mPackages) {
11701            int user = UserHandle.getCallingUserId();
11702            clearPackagePreferredActivitiesLPw(null, user);
11703            mSettings.readDefaultPreferredAppsLPw(this, user);
11704            mSettings.writePackageRestrictionsLPr(user);
11705            scheduleWriteSettingsLocked();
11706        }
11707    }
11708
11709    @Override
11710    public int getPreferredActivities(List<IntentFilter> outFilters,
11711            List<ComponentName> outActivities, String packageName) {
11712
11713        int num = 0;
11714        final int userId = UserHandle.getCallingUserId();
11715        // reader
11716        synchronized (mPackages) {
11717            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11718            if (pir != null) {
11719                final Iterator<PreferredActivity> it = pir.filterIterator();
11720                while (it.hasNext()) {
11721                    final PreferredActivity pa = it.next();
11722                    if (packageName == null
11723                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11724                                    && pa.mPref.mAlways)) {
11725                        if (outFilters != null) {
11726                            outFilters.add(new IntentFilter(pa));
11727                        }
11728                        if (outActivities != null) {
11729                            outActivities.add(pa.mPref.mComponent);
11730                        }
11731                    }
11732                }
11733            }
11734        }
11735
11736        return num;
11737    }
11738
11739    @Override
11740    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11741            int userId) {
11742        int callingUid = Binder.getCallingUid();
11743        if (callingUid != Process.SYSTEM_UID) {
11744            throw new SecurityException(
11745                    "addPersistentPreferredActivity can only be run by the system");
11746        }
11747        if (filter.countActions() == 0) {
11748            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11749            return;
11750        }
11751        synchronized (mPackages) {
11752            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11753                    " :");
11754            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11755            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11756                    new PersistentPreferredActivity(filter, activity));
11757            mSettings.writePackageRestrictionsLPr(userId);
11758        }
11759    }
11760
11761    @Override
11762    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11763        int callingUid = Binder.getCallingUid();
11764        if (callingUid != Process.SYSTEM_UID) {
11765            throw new SecurityException(
11766                    "clearPackagePersistentPreferredActivities can only be run by the system");
11767        }
11768        ArrayList<PersistentPreferredActivity> removed = null;
11769        boolean changed = false;
11770        synchronized (mPackages) {
11771            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11772                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11773                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11774                        .valueAt(i);
11775                if (userId != thisUserId) {
11776                    continue;
11777                }
11778                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11779                while (it.hasNext()) {
11780                    PersistentPreferredActivity ppa = it.next();
11781                    // Mark entry for removal only if it matches the package name.
11782                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11783                        if (removed == null) {
11784                            removed = new ArrayList<PersistentPreferredActivity>();
11785                        }
11786                        removed.add(ppa);
11787                    }
11788                }
11789                if (removed != null) {
11790                    for (int j=0; j<removed.size(); j++) {
11791                        PersistentPreferredActivity ppa = removed.get(j);
11792                        ppir.removeFilter(ppa);
11793                    }
11794                    changed = true;
11795                }
11796            }
11797
11798            if (changed) {
11799                mSettings.writePackageRestrictionsLPr(userId);
11800            }
11801        }
11802    }
11803
11804    @Override
11805    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11806            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11807        mContext.enforceCallingOrSelfPermission(
11808                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11809        int callingUid = Binder.getCallingUid();
11810        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11811        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11812        if (intentFilter.countActions() == 0) {
11813            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11814            return;
11815        }
11816        synchronized (mPackages) {
11817            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11818                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11819            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11820            mSettings.writePackageRestrictionsLPr(sourceUserId);
11821        }
11822    }
11823
11824    @Override
11825    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11826            int ownerUserId) {
11827        mContext.enforceCallingOrSelfPermission(
11828                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11829        int callingUid = Binder.getCallingUid();
11830        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11831        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11832        int callingUserId = UserHandle.getUserId(callingUid);
11833        synchronized (mPackages) {
11834            CrossProfileIntentResolver resolver =
11835                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11836            ArraySet<CrossProfileIntentFilter> set =
11837                    new ArraySet<CrossProfileIntentFilter>(resolver.filterSet());
11838            for (CrossProfileIntentFilter filter : set) {
11839                if (filter.getOwnerPackage().equals(ownerPackage)
11840                        && filter.getOwnerUserId() == callingUserId) {
11841                    resolver.removeFilter(filter);
11842                }
11843            }
11844            mSettings.writePackageRestrictionsLPr(sourceUserId);
11845        }
11846    }
11847
11848    // Enforcing that callingUid is owning pkg on userId
11849    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11850        // The system owns everything.
11851        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11852            return;
11853        }
11854        int callingUserId = UserHandle.getUserId(callingUid);
11855        if (callingUserId != userId) {
11856            throw new SecurityException("calling uid " + callingUid
11857                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11858                    + callingUserId);
11859        }
11860        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11861        if (pi == null) {
11862            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11863                    + callingUserId);
11864        }
11865        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11866            throw new SecurityException("Calling uid " + callingUid
11867                    + " does not own package " + pkg);
11868        }
11869    }
11870
11871    @Override
11872    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11873        Intent intent = new Intent(Intent.ACTION_MAIN);
11874        intent.addCategory(Intent.CATEGORY_HOME);
11875
11876        final int callingUserId = UserHandle.getCallingUserId();
11877        List<ResolveInfo> list = queryIntentActivities(intent, null,
11878                PackageManager.GET_META_DATA, callingUserId);
11879        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11880                true, false, false, callingUserId);
11881
11882        allHomeCandidates.clear();
11883        if (list != null) {
11884            for (ResolveInfo ri : list) {
11885                allHomeCandidates.add(ri);
11886            }
11887        }
11888        return (preferred == null || preferred.activityInfo == null)
11889                ? null
11890                : new ComponentName(preferred.activityInfo.packageName,
11891                        preferred.activityInfo.name);
11892    }
11893
11894    @Override
11895    public void setApplicationEnabledSetting(String appPackageName,
11896            int newState, int flags, int userId, String callingPackage) {
11897        if (!sUserManager.exists(userId)) return;
11898        if (callingPackage == null) {
11899            callingPackage = Integer.toString(Binder.getCallingUid());
11900        }
11901        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11902    }
11903
11904    @Override
11905    public void setComponentEnabledSetting(ComponentName componentName,
11906            int newState, int flags, int userId) {
11907        if (!sUserManager.exists(userId)) return;
11908        setEnabledSetting(componentName.getPackageName(),
11909                componentName.getClassName(), newState, flags, userId, null);
11910    }
11911
11912    private void setEnabledSetting(final String packageName, String className, int newState,
11913            final int flags, int userId, String callingPackage) {
11914        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11915              || newState == COMPONENT_ENABLED_STATE_ENABLED
11916              || newState == COMPONENT_ENABLED_STATE_DISABLED
11917              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11918              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11919            throw new IllegalArgumentException("Invalid new component state: "
11920                    + newState);
11921        }
11922        PackageSetting pkgSetting;
11923        final int uid = Binder.getCallingUid();
11924        final int permission = mContext.checkCallingOrSelfPermission(
11925                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11926        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11927        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11928        boolean sendNow = false;
11929        boolean isApp = (className == null);
11930        String componentName = isApp ? packageName : className;
11931        int packageUid = -1;
11932        ArrayList<String> components;
11933
11934        // writer
11935        synchronized (mPackages) {
11936            pkgSetting = mSettings.mPackages.get(packageName);
11937            if (pkgSetting == null) {
11938                if (className == null) {
11939                    throw new IllegalArgumentException(
11940                            "Unknown package: " + packageName);
11941                }
11942                throw new IllegalArgumentException(
11943                        "Unknown component: " + packageName
11944                        + "/" + className);
11945            }
11946            // Allow root and verify that userId is not being specified by a different user
11947            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11948                throw new SecurityException(
11949                        "Permission Denial: attempt to change component state from pid="
11950                        + Binder.getCallingPid()
11951                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11952            }
11953            if (className == null) {
11954                // We're dealing with an application/package level state change
11955                if (pkgSetting.getEnabled(userId) == newState) {
11956                    // Nothing to do
11957                    return;
11958                }
11959                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11960                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11961                    // Don't care about who enables an app.
11962                    callingPackage = null;
11963                }
11964                pkgSetting.setEnabled(newState, userId, callingPackage);
11965                // pkgSetting.pkg.mSetEnabled = newState;
11966            } else {
11967                // We're dealing with a component level state change
11968                // First, verify that this is a valid class name.
11969                PackageParser.Package pkg = pkgSetting.pkg;
11970                if (pkg == null || !pkg.hasComponentClassName(className)) {
11971                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11972                        throw new IllegalArgumentException("Component class " + className
11973                                + " does not exist in " + packageName);
11974                    } else {
11975                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11976                                + className + " does not exist in " + packageName);
11977                    }
11978                }
11979                switch (newState) {
11980                case COMPONENT_ENABLED_STATE_ENABLED:
11981                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11982                        return;
11983                    }
11984                    break;
11985                case COMPONENT_ENABLED_STATE_DISABLED:
11986                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11987                        return;
11988                    }
11989                    break;
11990                case COMPONENT_ENABLED_STATE_DEFAULT:
11991                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11992                        return;
11993                    }
11994                    break;
11995                default:
11996                    Slog.e(TAG, "Invalid new component state: " + newState);
11997                    return;
11998                }
11999            }
12000            mSettings.writePackageRestrictionsLPr(userId);
12001            components = mPendingBroadcasts.get(userId, packageName);
12002            final boolean newPackage = components == null;
12003            if (newPackage) {
12004                components = new ArrayList<String>();
12005            }
12006            if (!components.contains(componentName)) {
12007                components.add(componentName);
12008            }
12009            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12010                sendNow = true;
12011                // Purge entry from pending broadcast list if another one exists already
12012                // since we are sending one right away.
12013                mPendingBroadcasts.remove(userId, packageName);
12014            } else {
12015                if (newPackage) {
12016                    mPendingBroadcasts.put(userId, packageName, components);
12017                }
12018                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12019                    // Schedule a message
12020                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12021                }
12022            }
12023        }
12024
12025        long callingId = Binder.clearCallingIdentity();
12026        try {
12027            if (sendNow) {
12028                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12029                sendPackageChangedBroadcast(packageName,
12030                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12031            }
12032        } finally {
12033            Binder.restoreCallingIdentity(callingId);
12034        }
12035    }
12036
12037    private void sendPackageChangedBroadcast(String packageName,
12038            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12039        if (DEBUG_INSTALL)
12040            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12041                    + componentNames);
12042        Bundle extras = new Bundle(4);
12043        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12044        String nameList[] = new String[componentNames.size()];
12045        componentNames.toArray(nameList);
12046        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12047        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12048        extras.putInt(Intent.EXTRA_UID, packageUid);
12049        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12050                new int[] {UserHandle.getUserId(packageUid)});
12051    }
12052
12053    @Override
12054    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12055        if (!sUserManager.exists(userId)) return;
12056        final int uid = Binder.getCallingUid();
12057        final int permission = mContext.checkCallingOrSelfPermission(
12058                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12059        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12060        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12061        // writer
12062        synchronized (mPackages) {
12063            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12064                    uid, userId)) {
12065                scheduleWritePackageRestrictionsLocked(userId);
12066            }
12067        }
12068    }
12069
12070    @Override
12071    public String getInstallerPackageName(String packageName) {
12072        // reader
12073        synchronized (mPackages) {
12074            return mSettings.getInstallerPackageNameLPr(packageName);
12075        }
12076    }
12077
12078    @Override
12079    public int getApplicationEnabledSetting(String packageName, int userId) {
12080        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12081        int uid = Binder.getCallingUid();
12082        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12083        // reader
12084        synchronized (mPackages) {
12085            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12086        }
12087    }
12088
12089    @Override
12090    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12091        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12092        int uid = Binder.getCallingUid();
12093        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12094        // reader
12095        synchronized (mPackages) {
12096            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12097        }
12098    }
12099
12100    @Override
12101    public void enterSafeMode() {
12102        enforceSystemOrRoot("Only the system can request entering safe mode");
12103
12104        if (!mSystemReady) {
12105            mSafeMode = true;
12106        }
12107    }
12108
12109    @Override
12110    public void systemReady() {
12111        mSystemReady = true;
12112
12113        // Read the compatibilty setting when the system is ready.
12114        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12115                mContext.getContentResolver(),
12116                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12117        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12118        if (DEBUG_SETTINGS) {
12119            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12120        }
12121
12122        synchronized (mPackages) {
12123            // Verify that all of the preferred activity components actually
12124            // exist.  It is possible for applications to be updated and at
12125            // that point remove a previously declared activity component that
12126            // had been set as a preferred activity.  We try to clean this up
12127            // the next time we encounter that preferred activity, but it is
12128            // possible for the user flow to never be able to return to that
12129            // situation so here we do a sanity check to make sure we haven't
12130            // left any junk around.
12131            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12132            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12133                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12134                removed.clear();
12135                for (PreferredActivity pa : pir.filterSet()) {
12136                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12137                        removed.add(pa);
12138                    }
12139                }
12140                if (removed.size() > 0) {
12141                    for (int r=0; r<removed.size(); r++) {
12142                        PreferredActivity pa = removed.get(r);
12143                        Slog.w(TAG, "Removing dangling preferred activity: "
12144                                + pa.mPref.mComponent);
12145                        pir.removeFilter(pa);
12146                    }
12147                    mSettings.writePackageRestrictionsLPr(
12148                            mSettings.mPreferredActivities.keyAt(i));
12149                }
12150            }
12151        }
12152        sUserManager.systemReady();
12153
12154        // Kick off any messages waiting for system ready
12155        if (mPostSystemReadyMessages != null) {
12156            for (Message msg : mPostSystemReadyMessages) {
12157                msg.sendToTarget();
12158            }
12159            mPostSystemReadyMessages = null;
12160        }
12161    }
12162
12163    @Override
12164    public boolean isSafeMode() {
12165        return mSafeMode;
12166    }
12167
12168    @Override
12169    public boolean hasSystemUidErrors() {
12170        return mHasSystemUidErrors;
12171    }
12172
12173    static String arrayToString(int[] array) {
12174        StringBuffer buf = new StringBuffer(128);
12175        buf.append('[');
12176        if (array != null) {
12177            for (int i=0; i<array.length; i++) {
12178                if (i > 0) buf.append(", ");
12179                buf.append(array[i]);
12180            }
12181        }
12182        buf.append(']');
12183        return buf.toString();
12184    }
12185
12186    static class DumpState {
12187        public static final int DUMP_LIBS = 1 << 0;
12188        public static final int DUMP_FEATURES = 1 << 1;
12189        public static final int DUMP_RESOLVERS = 1 << 2;
12190        public static final int DUMP_PERMISSIONS = 1 << 3;
12191        public static final int DUMP_PACKAGES = 1 << 4;
12192        public static final int DUMP_SHARED_USERS = 1 << 5;
12193        public static final int DUMP_MESSAGES = 1 << 6;
12194        public static final int DUMP_PROVIDERS = 1 << 7;
12195        public static final int DUMP_VERIFIERS = 1 << 8;
12196        public static final int DUMP_PREFERRED = 1 << 9;
12197        public static final int DUMP_PREFERRED_XML = 1 << 10;
12198        public static final int DUMP_KEYSETS = 1 << 11;
12199        public static final int DUMP_VERSION = 1 << 12;
12200        public static final int DUMP_INSTALLS = 1 << 13;
12201
12202        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12203
12204        private int mTypes;
12205
12206        private int mOptions;
12207
12208        private boolean mTitlePrinted;
12209
12210        private SharedUserSetting mSharedUser;
12211
12212        public boolean isDumping(int type) {
12213            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12214                return true;
12215            }
12216
12217            return (mTypes & type) != 0;
12218        }
12219
12220        public void setDump(int type) {
12221            mTypes |= type;
12222        }
12223
12224        public boolean isOptionEnabled(int option) {
12225            return (mOptions & option) != 0;
12226        }
12227
12228        public void setOptionEnabled(int option) {
12229            mOptions |= option;
12230        }
12231
12232        public boolean onTitlePrinted() {
12233            final boolean printed = mTitlePrinted;
12234            mTitlePrinted = true;
12235            return printed;
12236        }
12237
12238        public boolean getTitlePrinted() {
12239            return mTitlePrinted;
12240        }
12241
12242        public void setTitlePrinted(boolean enabled) {
12243            mTitlePrinted = enabled;
12244        }
12245
12246        public SharedUserSetting getSharedUser() {
12247            return mSharedUser;
12248        }
12249
12250        public void setSharedUser(SharedUserSetting user) {
12251            mSharedUser = user;
12252        }
12253    }
12254
12255    @Override
12256    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12257        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12258                != PackageManager.PERMISSION_GRANTED) {
12259            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12260                    + Binder.getCallingPid()
12261                    + ", uid=" + Binder.getCallingUid()
12262                    + " without permission "
12263                    + android.Manifest.permission.DUMP);
12264            return;
12265        }
12266
12267        DumpState dumpState = new DumpState();
12268        boolean fullPreferred = false;
12269        boolean checkin = false;
12270
12271        String packageName = null;
12272
12273        int opti = 0;
12274        while (opti < args.length) {
12275            String opt = args[opti];
12276            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12277                break;
12278            }
12279            opti++;
12280
12281            if ("-a".equals(opt)) {
12282                // Right now we only know how to print all.
12283            } else if ("-h".equals(opt)) {
12284                pw.println("Package manager dump options:");
12285                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12286                pw.println("    --checkin: dump for a checkin");
12287                pw.println("    -f: print details of intent filters");
12288                pw.println("    -h: print this help");
12289                pw.println("  cmd may be one of:");
12290                pw.println("    l[ibraries]: list known shared libraries");
12291                pw.println("    f[ibraries]: list device features");
12292                pw.println("    k[eysets]: print known keysets");
12293                pw.println("    r[esolvers]: dump intent resolvers");
12294                pw.println("    perm[issions]: dump permissions");
12295                pw.println("    pref[erred]: print preferred package settings");
12296                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12297                pw.println("    prov[iders]: dump content providers");
12298                pw.println("    p[ackages]: dump installed packages");
12299                pw.println("    s[hared-users]: dump shared user IDs");
12300                pw.println("    m[essages]: print collected runtime messages");
12301                pw.println("    v[erifiers]: print package verifier info");
12302                pw.println("    version: print database version info");
12303                pw.println("    write: write current settings now");
12304                pw.println("    <package.name>: info about given package");
12305                pw.println("    installs: details about install sessions");
12306                return;
12307            } else if ("--checkin".equals(opt)) {
12308                checkin = true;
12309            } else if ("-f".equals(opt)) {
12310                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12311            } else {
12312                pw.println("Unknown argument: " + opt + "; use -h for help");
12313            }
12314        }
12315
12316        // Is the caller requesting to dump a particular piece of data?
12317        if (opti < args.length) {
12318            String cmd = args[opti];
12319            opti++;
12320            // Is this a package name?
12321            if ("android".equals(cmd) || cmd.contains(".")) {
12322                packageName = cmd;
12323                // When dumping a single package, we always dump all of its
12324                // filter information since the amount of data will be reasonable.
12325                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12326            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12327                dumpState.setDump(DumpState.DUMP_LIBS);
12328            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12329                dumpState.setDump(DumpState.DUMP_FEATURES);
12330            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12331                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12332            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12333                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12334            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12335                dumpState.setDump(DumpState.DUMP_PREFERRED);
12336            } else if ("preferred-xml".equals(cmd)) {
12337                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12338                if (opti < args.length && "--full".equals(args[opti])) {
12339                    fullPreferred = true;
12340                    opti++;
12341                }
12342            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12343                dumpState.setDump(DumpState.DUMP_PACKAGES);
12344            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12345                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12346            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12347                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12348            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12349                dumpState.setDump(DumpState.DUMP_MESSAGES);
12350            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12351                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12352            } else if ("version".equals(cmd)) {
12353                dumpState.setDump(DumpState.DUMP_VERSION);
12354            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12355                dumpState.setDump(DumpState.DUMP_KEYSETS);
12356            } else if ("installs".equals(cmd)) {
12357                dumpState.setDump(DumpState.DUMP_INSTALLS);
12358            } else if ("write".equals(cmd)) {
12359                synchronized (mPackages) {
12360                    mSettings.writeLPr();
12361                    pw.println("Settings written.");
12362                    return;
12363                }
12364            }
12365        }
12366
12367        if (checkin) {
12368            pw.println("vers,1");
12369        }
12370
12371        // reader
12372        synchronized (mPackages) {
12373            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12374                if (!checkin) {
12375                    if (dumpState.onTitlePrinted())
12376                        pw.println();
12377                    pw.println("Database versions:");
12378                    pw.print("  SDK Version:");
12379                    pw.print(" internal=");
12380                    pw.print(mSettings.mInternalSdkPlatform);
12381                    pw.print(" external=");
12382                    pw.println(mSettings.mExternalSdkPlatform);
12383                    pw.print("  DB Version:");
12384                    pw.print(" internal=");
12385                    pw.print(mSettings.mInternalDatabaseVersion);
12386                    pw.print(" external=");
12387                    pw.println(mSettings.mExternalDatabaseVersion);
12388                }
12389            }
12390
12391            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12392                if (!checkin) {
12393                    if (dumpState.onTitlePrinted())
12394                        pw.println();
12395                    pw.println("Verifiers:");
12396                    pw.print("  Required: ");
12397                    pw.print(mRequiredVerifierPackage);
12398                    pw.print(" (uid=");
12399                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12400                    pw.println(")");
12401                } else if (mRequiredVerifierPackage != null) {
12402                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12403                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12404                }
12405            }
12406
12407            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12408                boolean printedHeader = false;
12409                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12410                while (it.hasNext()) {
12411                    String name = it.next();
12412                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12413                    if (!checkin) {
12414                        if (!printedHeader) {
12415                            if (dumpState.onTitlePrinted())
12416                                pw.println();
12417                            pw.println("Libraries:");
12418                            printedHeader = true;
12419                        }
12420                        pw.print("  ");
12421                    } else {
12422                        pw.print("lib,");
12423                    }
12424                    pw.print(name);
12425                    if (!checkin) {
12426                        pw.print(" -> ");
12427                    }
12428                    if (ent.path != null) {
12429                        if (!checkin) {
12430                            pw.print("(jar) ");
12431                            pw.print(ent.path);
12432                        } else {
12433                            pw.print(",jar,");
12434                            pw.print(ent.path);
12435                        }
12436                    } else {
12437                        if (!checkin) {
12438                            pw.print("(apk) ");
12439                            pw.print(ent.apk);
12440                        } else {
12441                            pw.print(",apk,");
12442                            pw.print(ent.apk);
12443                        }
12444                    }
12445                    pw.println();
12446                }
12447            }
12448
12449            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12450                if (dumpState.onTitlePrinted())
12451                    pw.println();
12452                if (!checkin) {
12453                    pw.println("Features:");
12454                }
12455                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12456                while (it.hasNext()) {
12457                    String name = it.next();
12458                    if (!checkin) {
12459                        pw.print("  ");
12460                    } else {
12461                        pw.print("feat,");
12462                    }
12463                    pw.println(name);
12464                }
12465            }
12466
12467            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12468                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12469                        : "Activity Resolver Table:", "  ", packageName,
12470                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12471                    dumpState.setTitlePrinted(true);
12472                }
12473                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12474                        : "Receiver Resolver Table:", "  ", packageName,
12475                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12476                    dumpState.setTitlePrinted(true);
12477                }
12478                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12479                        : "Service Resolver Table:", "  ", packageName,
12480                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12481                    dumpState.setTitlePrinted(true);
12482                }
12483                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12484                        : "Provider Resolver Table:", "  ", packageName,
12485                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12486                    dumpState.setTitlePrinted(true);
12487                }
12488            }
12489
12490            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12491                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12492                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12493                    int user = mSettings.mPreferredActivities.keyAt(i);
12494                    if (pir.dump(pw,
12495                            dumpState.getTitlePrinted()
12496                                ? "\nPreferred Activities User " + user + ":"
12497                                : "Preferred Activities User " + user + ":", "  ",
12498                            packageName, true)) {
12499                        dumpState.setTitlePrinted(true);
12500                    }
12501                }
12502            }
12503
12504            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12505                pw.flush();
12506                FileOutputStream fout = new FileOutputStream(fd);
12507                BufferedOutputStream str = new BufferedOutputStream(fout);
12508                XmlSerializer serializer = new FastXmlSerializer();
12509                try {
12510                    serializer.setOutput(str, "utf-8");
12511                    serializer.startDocument(null, true);
12512                    serializer.setFeature(
12513                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12514                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12515                    serializer.endDocument();
12516                    serializer.flush();
12517                } catch (IllegalArgumentException e) {
12518                    pw.println("Failed writing: " + e);
12519                } catch (IllegalStateException e) {
12520                    pw.println("Failed writing: " + e);
12521                } catch (IOException e) {
12522                    pw.println("Failed writing: " + e);
12523                }
12524            }
12525
12526            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12527                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12528                if (packageName == null) {
12529                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12530                        if (iperm == 0) {
12531                            if (dumpState.onTitlePrinted())
12532                                pw.println();
12533                            pw.println("AppOp Permissions:");
12534                        }
12535                        pw.print("  AppOp Permission ");
12536                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12537                        pw.println(":");
12538                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12539                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12540                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12541                        }
12542                    }
12543                }
12544            }
12545
12546            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12547                boolean printedSomething = false;
12548                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12549                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12550                        continue;
12551                    }
12552                    if (!printedSomething) {
12553                        if (dumpState.onTitlePrinted())
12554                            pw.println();
12555                        pw.println("Registered ContentProviders:");
12556                        printedSomething = true;
12557                    }
12558                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12559                    pw.print("    "); pw.println(p.toString());
12560                }
12561                printedSomething = false;
12562                for (Map.Entry<String, PackageParser.Provider> entry :
12563                        mProvidersByAuthority.entrySet()) {
12564                    PackageParser.Provider p = entry.getValue();
12565                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12566                        continue;
12567                    }
12568                    if (!printedSomething) {
12569                        if (dumpState.onTitlePrinted())
12570                            pw.println();
12571                        pw.println("ContentProvider Authorities:");
12572                        printedSomething = true;
12573                    }
12574                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12575                    pw.print("    "); pw.println(p.toString());
12576                    if (p.info != null && p.info.applicationInfo != null) {
12577                        final String appInfo = p.info.applicationInfo.toString();
12578                        pw.print("      applicationInfo="); pw.println(appInfo);
12579                    }
12580                }
12581            }
12582
12583            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12584                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12585            }
12586
12587            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12588                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12589            }
12590
12591            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12592                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12593            }
12594
12595            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12596                // XXX should handle packageName != null by dumping only install data that
12597                // the given package is involved with.
12598                if (dumpState.onTitlePrinted()) pw.println();
12599                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12600            }
12601
12602            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12603                if (dumpState.onTitlePrinted()) pw.println();
12604                mSettings.dumpReadMessagesLPr(pw, dumpState);
12605
12606                pw.println();
12607                pw.println("Package warning messages:");
12608                final File fname = getSettingsProblemFile();
12609                FileInputStream in = null;
12610                try {
12611                    in = new FileInputStream(fname);
12612                    final int avail = in.available();
12613                    final byte[] data = new byte[avail];
12614                    in.read(data);
12615                    pw.print(new String(data));
12616                } catch (FileNotFoundException e) {
12617                } catch (IOException e) {
12618                } finally {
12619                    if (in != null) {
12620                        try {
12621                            in.close();
12622                        } catch (IOException e) {
12623                        }
12624                    }
12625                }
12626            }
12627
12628            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12629                BufferedReader in = null;
12630                String line = null;
12631                try {
12632                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12633                    while ((line = in.readLine()) != null) {
12634                        pw.print("msg,");
12635                        pw.println(line);
12636                    }
12637                } catch (IOException ignored) {
12638                } finally {
12639                    IoUtils.closeQuietly(in);
12640                }
12641            }
12642        }
12643    }
12644
12645    // ------- apps on sdcard specific code -------
12646    static final boolean DEBUG_SD_INSTALL = false;
12647
12648    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12649
12650    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12651
12652    private boolean mMediaMounted = false;
12653
12654    static String getEncryptKey() {
12655        try {
12656            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12657                    SD_ENCRYPTION_KEYSTORE_NAME);
12658            if (sdEncKey == null) {
12659                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12660                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12661                if (sdEncKey == null) {
12662                    Slog.e(TAG, "Failed to create encryption keys");
12663                    return null;
12664                }
12665            }
12666            return sdEncKey;
12667        } catch (NoSuchAlgorithmException nsae) {
12668            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12669            return null;
12670        } catch (IOException ioe) {
12671            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12672            return null;
12673        }
12674    }
12675
12676    /*
12677     * Update media status on PackageManager.
12678     */
12679    @Override
12680    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12681        int callingUid = Binder.getCallingUid();
12682        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12683            throw new SecurityException("Media status can only be updated by the system");
12684        }
12685        // reader; this apparently protects mMediaMounted, but should probably
12686        // be a different lock in that case.
12687        synchronized (mPackages) {
12688            Log.i(TAG, "Updating external media status from "
12689                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12690                    + (mediaStatus ? "mounted" : "unmounted"));
12691            if (DEBUG_SD_INSTALL)
12692                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12693                        + ", mMediaMounted=" + mMediaMounted);
12694            if (mediaStatus == mMediaMounted) {
12695                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12696                        : 0, -1);
12697                mHandler.sendMessage(msg);
12698                return;
12699            }
12700            mMediaMounted = mediaStatus;
12701        }
12702        // Queue up an async operation since the package installation may take a
12703        // little while.
12704        mHandler.post(new Runnable() {
12705            public void run() {
12706                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12707            }
12708        });
12709    }
12710
12711    /**
12712     * Called by MountService when the initial ASECs to scan are available.
12713     * Should block until all the ASEC containers are finished being scanned.
12714     */
12715    public void scanAvailableAsecs() {
12716        updateExternalMediaStatusInner(true, false, false);
12717        if (mShouldRestoreconData) {
12718            SELinuxMMAC.setRestoreconDone();
12719            mShouldRestoreconData = false;
12720        }
12721    }
12722
12723    /*
12724     * Collect information of applications on external media, map them against
12725     * existing containers and update information based on current mount status.
12726     * Please note that we always have to report status if reportStatus has been
12727     * set to true especially when unloading packages.
12728     */
12729    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12730            boolean externalStorage) {
12731        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12732        int[] uidArr = EmptyArray.INT;
12733
12734        final String[] list = PackageHelper.getSecureContainerList();
12735        if (ArrayUtils.isEmpty(list)) {
12736            Log.i(TAG, "No secure containers found");
12737        } else {
12738            // Process list of secure containers and categorize them
12739            // as active or stale based on their package internal state.
12740
12741            // reader
12742            synchronized (mPackages) {
12743                for (String cid : list) {
12744                    // Leave stages untouched for now; installer service owns them
12745                    if (PackageInstallerService.isStageName(cid)) continue;
12746
12747                    if (DEBUG_SD_INSTALL)
12748                        Log.i(TAG, "Processing container " + cid);
12749                    String pkgName = getAsecPackageName(cid);
12750                    if (pkgName == null) {
12751                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12752                        continue;
12753                    }
12754                    if (DEBUG_SD_INSTALL)
12755                        Log.i(TAG, "Looking for pkg : " + pkgName);
12756
12757                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12758                    if (ps == null) {
12759                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12760                        continue;
12761                    }
12762
12763                    /*
12764                     * Skip packages that are not external if we're unmounting
12765                     * external storage.
12766                     */
12767                    if (externalStorage && !isMounted && !isExternal(ps)) {
12768                        continue;
12769                    }
12770
12771                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12772                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12773                    // The package status is changed only if the code path
12774                    // matches between settings and the container id.
12775                    if (ps.codePathString != null
12776                            && ps.codePathString.startsWith(args.getCodePath())) {
12777                        if (DEBUG_SD_INSTALL) {
12778                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12779                                    + " at code path: " + ps.codePathString);
12780                        }
12781
12782                        // We do have a valid package installed on sdcard
12783                        processCids.put(args, ps.codePathString);
12784                        final int uid = ps.appId;
12785                        if (uid != -1) {
12786                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12787                        }
12788                    } else {
12789                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12790                                + ps.codePathString);
12791                    }
12792                }
12793            }
12794
12795            Arrays.sort(uidArr);
12796        }
12797
12798        // Process packages with valid entries.
12799        if (isMounted) {
12800            if (DEBUG_SD_INSTALL)
12801                Log.i(TAG, "Loading packages");
12802            loadMediaPackages(processCids, uidArr);
12803            startCleaningPackages();
12804            mInstallerService.onSecureContainersAvailable();
12805        } else {
12806            if (DEBUG_SD_INSTALL)
12807                Log.i(TAG, "Unloading packages");
12808            unloadMediaPackages(processCids, uidArr, reportStatus);
12809        }
12810    }
12811
12812    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12813            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12814        int size = pkgList.size();
12815        if (size > 0) {
12816            // Send broadcasts here
12817            Bundle extras = new Bundle();
12818            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12819                    .toArray(new String[size]));
12820            if (uidArr != null) {
12821                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12822            }
12823            if (replacing) {
12824                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12825            }
12826            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12827                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12828            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12829        }
12830    }
12831
12832   /*
12833     * Look at potentially valid container ids from processCids If package
12834     * information doesn't match the one on record or package scanning fails,
12835     * the cid is added to list of removeCids. We currently don't delete stale
12836     * containers.
12837     */
12838    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12839        ArrayList<String> pkgList = new ArrayList<String>();
12840        Set<AsecInstallArgs> keys = processCids.keySet();
12841
12842        for (AsecInstallArgs args : keys) {
12843            String codePath = processCids.get(args);
12844            if (DEBUG_SD_INSTALL)
12845                Log.i(TAG, "Loading container : " + args.cid);
12846            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12847            try {
12848                // Make sure there are no container errors first.
12849                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12850                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12851                            + " when installing from sdcard");
12852                    continue;
12853                }
12854                // Check code path here.
12855                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12856                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12857                            + " does not match one in settings " + codePath);
12858                    continue;
12859                }
12860                // Parse package
12861                int parseFlags = mDefParseFlags;
12862                if (args.isExternal()) {
12863                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12864                }
12865                if (args.isFwdLocked()) {
12866                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12867                }
12868
12869                synchronized (mInstallLock) {
12870                    PackageParser.Package pkg = null;
12871                    try {
12872                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12873                    } catch (PackageManagerException e) {
12874                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12875                    }
12876                    // Scan the package
12877                    if (pkg != null) {
12878                        /*
12879                         * TODO why is the lock being held? doPostInstall is
12880                         * called in other places without the lock. This needs
12881                         * to be straightened out.
12882                         */
12883                        // writer
12884                        synchronized (mPackages) {
12885                            retCode = PackageManager.INSTALL_SUCCEEDED;
12886                            pkgList.add(pkg.packageName);
12887                            // Post process args
12888                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12889                                    pkg.applicationInfo.uid);
12890                        }
12891                    } else {
12892                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12893                    }
12894                }
12895
12896            } finally {
12897                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12898                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12899                }
12900            }
12901        }
12902        // writer
12903        synchronized (mPackages) {
12904            // If the platform SDK has changed since the last time we booted,
12905            // we need to re-grant app permission to catch any new ones that
12906            // appear. This is really a hack, and means that apps can in some
12907            // cases get permissions that the user didn't initially explicitly
12908            // allow... it would be nice to have some better way to handle
12909            // this situation.
12910            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12911            if (regrantPermissions)
12912                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12913                        + mSdkVersion + "; regranting permissions for external storage");
12914            mSettings.mExternalSdkPlatform = mSdkVersion;
12915
12916            // Make sure group IDs have been assigned, and any permission
12917            // changes in other apps are accounted for
12918            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12919                    | (regrantPermissions
12920                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12921                            : 0));
12922
12923            mSettings.updateExternalDatabaseVersion();
12924
12925            // can downgrade to reader
12926            // Persist settings
12927            mSettings.writeLPr();
12928        }
12929        // Send a broadcast to let everyone know we are done processing
12930        if (pkgList.size() > 0) {
12931            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12932        }
12933    }
12934
12935   /*
12936     * Utility method to unload a list of specified containers
12937     */
12938    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12939        // Just unmount all valid containers.
12940        for (AsecInstallArgs arg : cidArgs) {
12941            synchronized (mInstallLock) {
12942                arg.doPostDeleteLI(false);
12943           }
12944       }
12945   }
12946
12947    /*
12948     * Unload packages mounted on external media. This involves deleting package
12949     * data from internal structures, sending broadcasts about diabled packages,
12950     * gc'ing to free up references, unmounting all secure containers
12951     * corresponding to packages on external media, and posting a
12952     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12953     * that we always have to post this message if status has been requested no
12954     * matter what.
12955     */
12956    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12957            final boolean reportStatus) {
12958        if (DEBUG_SD_INSTALL)
12959            Log.i(TAG, "unloading media packages");
12960        ArrayList<String> pkgList = new ArrayList<String>();
12961        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12962        final Set<AsecInstallArgs> keys = processCids.keySet();
12963        for (AsecInstallArgs args : keys) {
12964            String pkgName = args.getPackageName();
12965            if (DEBUG_SD_INSTALL)
12966                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12967            // Delete package internally
12968            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12969            synchronized (mInstallLock) {
12970                boolean res = deletePackageLI(pkgName, null, false, null, null,
12971                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12972                if (res) {
12973                    pkgList.add(pkgName);
12974                } else {
12975                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12976                    failedList.add(args);
12977                }
12978            }
12979        }
12980
12981        // reader
12982        synchronized (mPackages) {
12983            // We didn't update the settings after removing each package;
12984            // write them now for all packages.
12985            mSettings.writeLPr();
12986        }
12987
12988        // We have to absolutely send UPDATED_MEDIA_STATUS only
12989        // after confirming that all the receivers processed the ordered
12990        // broadcast when packages get disabled, force a gc to clean things up.
12991        // and unload all the containers.
12992        if (pkgList.size() > 0) {
12993            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12994                    new IIntentReceiver.Stub() {
12995                public void performReceive(Intent intent, int resultCode, String data,
12996                        Bundle extras, boolean ordered, boolean sticky,
12997                        int sendingUser) throws RemoteException {
12998                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12999                            reportStatus ? 1 : 0, 1, keys);
13000                    mHandler.sendMessage(msg);
13001                }
13002            });
13003        } else {
13004            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13005                    keys);
13006            mHandler.sendMessage(msg);
13007        }
13008    }
13009
13010    /** Binder call */
13011    @Override
13012    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13013            final int flags) {
13014        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13015        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13016        int returnCode = PackageManager.MOVE_SUCCEEDED;
13017        int currInstallFlags = 0;
13018        int newInstallFlags = 0;
13019
13020        File codeFile = null;
13021        String installerPackageName = null;
13022        String packageAbiOverride = null;
13023
13024        // reader
13025        synchronized (mPackages) {
13026            final PackageParser.Package pkg = mPackages.get(packageName);
13027            final PackageSetting ps = mSettings.mPackages.get(packageName);
13028            if (pkg == null || ps == null) {
13029                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13030            } else {
13031                // Disable moving fwd locked apps and system packages
13032                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13033                    Slog.w(TAG, "Cannot move system application");
13034                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13035                } else if (pkg.mOperationPending) {
13036                    Slog.w(TAG, "Attempt to move package which has pending operations");
13037                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13038                } else {
13039                    // Find install location first
13040                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13041                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13042                        Slog.w(TAG, "Ambigous flags specified for move location.");
13043                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13044                    } else {
13045                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13046                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13047                        currInstallFlags = isExternal(pkg)
13048                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13049
13050                        if (newInstallFlags == currInstallFlags) {
13051                            Slog.w(TAG, "No move required. Trying to move to same location");
13052                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13053                        } else {
13054                            if (isForwardLocked(pkg)) {
13055                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13056                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13057                            }
13058                        }
13059                    }
13060                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13061                        pkg.mOperationPending = true;
13062                    }
13063                }
13064
13065                codeFile = new File(pkg.codePath);
13066                installerPackageName = ps.installerPackageName;
13067                packageAbiOverride = ps.cpuAbiOverrideString;
13068            }
13069        }
13070
13071        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13072            try {
13073                observer.packageMoved(packageName, returnCode);
13074            } catch (RemoteException ignored) {
13075            }
13076            return;
13077        }
13078
13079        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13080            @Override
13081            public void onUserActionRequired(Intent intent) throws RemoteException {
13082                throw new IllegalStateException();
13083            }
13084
13085            @Override
13086            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13087                    Bundle extras) throws RemoteException {
13088                Slog.d(TAG, "Install result for move: "
13089                        + PackageManager.installStatusToString(returnCode, msg));
13090
13091                // We usually have a new package now after the install, but if
13092                // we failed we need to clear the pending flag on the original
13093                // package object.
13094                synchronized (mPackages) {
13095                    final PackageParser.Package pkg = mPackages.get(packageName);
13096                    if (pkg != null) {
13097                        pkg.mOperationPending = false;
13098                    }
13099                }
13100
13101                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13102                switch (status) {
13103                    case PackageInstaller.STATUS_SUCCESS:
13104                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13105                        break;
13106                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13107                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13108                        break;
13109                    default:
13110                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13111                        break;
13112                }
13113            }
13114        };
13115
13116        // Treat a move like reinstalling an existing app, which ensures that we
13117        // process everythign uniformly, like unpacking native libraries.
13118        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13119
13120        final Message msg = mHandler.obtainMessage(INIT_COPY);
13121        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13122        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13123                installerPackageName, null, user, packageAbiOverride);
13124        mHandler.sendMessage(msg);
13125    }
13126
13127    @Override
13128    public boolean setInstallLocation(int loc) {
13129        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13130                null);
13131        if (getInstallLocation() == loc) {
13132            return true;
13133        }
13134        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13135                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13136            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13137                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13138            return true;
13139        }
13140        return false;
13141   }
13142
13143    @Override
13144    public int getInstallLocation() {
13145        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13146                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13147                PackageHelper.APP_INSTALL_AUTO);
13148    }
13149
13150    /** Called by UserManagerService */
13151    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13152        mDirtyUsers.remove(userHandle);
13153        mSettings.removeUserLPw(userHandle);
13154        mPendingBroadcasts.remove(userHandle);
13155        if (mInstaller != null) {
13156            // Technically, we shouldn't be doing this with the package lock
13157            // held.  However, this is very rare, and there is already so much
13158            // other disk I/O going on, that we'll let it slide for now.
13159            mInstaller.removeUserDataDirs(userHandle);
13160        }
13161        mUserNeedsBadging.delete(userHandle);
13162        removeUnusedPackagesLILPw(userManager, userHandle);
13163    }
13164
13165    /**
13166     * We're removing userHandle and would like to remove any downloaded packages
13167     * that are no longer in use by any other user.
13168     * @param userHandle the user being removed
13169     */
13170    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13171        final boolean DEBUG_CLEAN_APKS = false;
13172        int [] users = userManager.getUserIdsLPr();
13173        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13174        while (psit.hasNext()) {
13175            PackageSetting ps = psit.next();
13176            if (ps.pkg == null) {
13177                continue;
13178            }
13179            final String packageName = ps.pkg.packageName;
13180            // Skip over if system app
13181            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13182                continue;
13183            }
13184            if (DEBUG_CLEAN_APKS) {
13185                Slog.i(TAG, "Checking package " + packageName);
13186            }
13187            boolean keep = false;
13188            for (int i = 0; i < users.length; i++) {
13189                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13190                    keep = true;
13191                    if (DEBUG_CLEAN_APKS) {
13192                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13193                                + users[i]);
13194                    }
13195                    break;
13196                }
13197            }
13198            if (!keep) {
13199                if (DEBUG_CLEAN_APKS) {
13200                    Slog.i(TAG, "  Removing package " + packageName);
13201                }
13202                mHandler.post(new Runnable() {
13203                    public void run() {
13204                        deletePackageX(packageName, userHandle, 0);
13205                    } //end run
13206                });
13207            }
13208        }
13209    }
13210
13211    /** Called by UserManagerService */
13212    void createNewUserLILPw(int userHandle, File path) {
13213        if (mInstaller != null) {
13214            mInstaller.createUserConfig(userHandle);
13215            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13216        }
13217    }
13218
13219    @Override
13220    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13221        mContext.enforceCallingOrSelfPermission(
13222                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13223                "Only package verification agents can read the verifier device identity");
13224
13225        synchronized (mPackages) {
13226            return mSettings.getVerifierDeviceIdentityLPw();
13227        }
13228    }
13229
13230    @Override
13231    public void setPermissionEnforced(String permission, boolean enforced) {
13232        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13233        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13234            synchronized (mPackages) {
13235                if (mSettings.mReadExternalStorageEnforced == null
13236                        || mSettings.mReadExternalStorageEnforced != enforced) {
13237                    mSettings.mReadExternalStorageEnforced = enforced;
13238                    mSettings.writeLPr();
13239                }
13240            }
13241            // kill any non-foreground processes so we restart them and
13242            // grant/revoke the GID.
13243            final IActivityManager am = ActivityManagerNative.getDefault();
13244            if (am != null) {
13245                final long token = Binder.clearCallingIdentity();
13246                try {
13247                    am.killProcessesBelowForeground("setPermissionEnforcement");
13248                } catch (RemoteException e) {
13249                } finally {
13250                    Binder.restoreCallingIdentity(token);
13251                }
13252            }
13253        } else {
13254            throw new IllegalArgumentException("No selective enforcement for " + permission);
13255        }
13256    }
13257
13258    @Override
13259    @Deprecated
13260    public boolean isPermissionEnforced(String permission) {
13261        return true;
13262    }
13263
13264    @Override
13265    public boolean isStorageLow() {
13266        final long token = Binder.clearCallingIdentity();
13267        try {
13268            final DeviceStorageMonitorInternal
13269                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13270            if (dsm != null) {
13271                return dsm.isMemoryLow();
13272            } else {
13273                return false;
13274            }
13275        } finally {
13276            Binder.restoreCallingIdentity(token);
13277        }
13278    }
13279
13280    @Override
13281    public IPackageInstaller getPackageInstaller() {
13282        return mInstallerService;
13283    }
13284
13285    private boolean userNeedsBadging(int userId) {
13286        int index = mUserNeedsBadging.indexOfKey(userId);
13287        if (index < 0) {
13288            final UserInfo userInfo;
13289            final long token = Binder.clearCallingIdentity();
13290            try {
13291                userInfo = sUserManager.getUserInfo(userId);
13292            } finally {
13293                Binder.restoreCallingIdentity(token);
13294            }
13295            final boolean b;
13296            if (userInfo != null && userInfo.isManagedProfile()) {
13297                b = true;
13298            } else {
13299                b = false;
13300            }
13301            mUserNeedsBadging.put(userId, b);
13302            return b;
13303        }
13304        return mUserNeedsBadging.valueAt(index);
13305    }
13306
13307    @Override
13308    public KeySet getKeySetByAlias(String packageName, String alias) {
13309        if (packageName == null || alias == null) {
13310            return null;
13311        }
13312        synchronized(mPackages) {
13313            final PackageParser.Package pkg = mPackages.get(packageName);
13314            if (pkg == null) {
13315                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13316                throw new IllegalArgumentException("Unknown package: " + packageName);
13317            }
13318            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13319            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13320        }
13321    }
13322
13323    @Override
13324    public KeySet getSigningKeySet(String packageName) {
13325        if (packageName == null) {
13326            return null;
13327        }
13328        synchronized(mPackages) {
13329            final PackageParser.Package pkg = mPackages.get(packageName);
13330            if (pkg == null) {
13331                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13332                throw new IllegalArgumentException("Unknown package: " + packageName);
13333            }
13334            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13335                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13336                throw new SecurityException("May not access signing KeySet of other apps.");
13337            }
13338            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13339            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13340        }
13341    }
13342
13343    @Override
13344    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13345        if (packageName == null || ks == null) {
13346            return false;
13347        }
13348        synchronized(mPackages) {
13349            final PackageParser.Package pkg = mPackages.get(packageName);
13350            if (pkg == null) {
13351                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13352                throw new IllegalArgumentException("Unknown package: " + packageName);
13353            }
13354            IBinder ksh = ks.getToken();
13355            if (ksh instanceof KeySetHandle) {
13356                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13357                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13358            }
13359            return false;
13360        }
13361    }
13362
13363    @Override
13364    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13365        if (packageName == null || ks == null) {
13366            return false;
13367        }
13368        synchronized(mPackages) {
13369            final PackageParser.Package pkg = mPackages.get(packageName);
13370            if (pkg == null) {
13371                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13372                throw new IllegalArgumentException("Unknown package: " + packageName);
13373            }
13374            IBinder ksh = ks.getToken();
13375            if (ksh instanceof KeySetHandle) {
13376                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13377                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13378            }
13379            return false;
13380        }
13381    }
13382}
13383