PackageManagerService.java revision 4c88087776305f54bec0aae59b8e63bc803c1401
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageParser;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.storage.StorageManager;
141import android.os.Debug;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.BufferedReader;
179import java.io.File;
180import java.io.FileDescriptor;
181import java.io.FileInputStream;
182import java.io.FileNotFoundException;
183import java.io.FileOutputStream;
184import java.io.FileReader;
185import java.io.FilenameFilter;
186import java.io.IOException;
187import java.io.InputStream;
188import java.io.PrintWriter;
189import java.nio.charset.StandardCharsets;
190import java.security.NoSuchAlgorithmException;
191import java.security.PublicKey;
192import java.security.cert.CertificateEncodingException;
193import java.security.cert.CertificateException;
194import java.text.SimpleDateFormat;
195import java.util.ArrayList;
196import java.util.Arrays;
197import java.util.Collection;
198import java.util.Collections;
199import java.util.Comparator;
200import java.util.Date;
201import java.util.HashMap;
202import java.util.HashSet;
203import java.util.Iterator;
204import java.util.List;
205import java.util.Map;
206import java.util.Objects;
207import java.util.Set;
208import java.util.concurrent.atomic.AtomicBoolean;
209import java.util.concurrent.atomic.AtomicLong;
210
211import dalvik.system.DexFile;
212import dalvik.system.StaleDexCacheError;
213import dalvik.system.VMRuntime;
214
215import libcore.io.IoUtils;
216import libcore.util.EmptyArray;
217
218/**
219 * Keep track of all those .apks everywhere.
220 *
221 * This is very central to the platform's security; please run the unit
222 * tests whenever making modifications here:
223 *
224mmm frameworks/base/tests/AndroidTests
225adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
226adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
227 *
228 * {@hide}
229 */
230public class PackageManagerService extends IPackageManager.Stub {
231    static final String TAG = "PackageManager";
232    static final boolean DEBUG_SETTINGS = false;
233    static final boolean DEBUG_PREFERRED = false;
234    static final boolean DEBUG_UPGRADE = false;
235    private static final boolean DEBUG_INSTALL = false;
236    private static final boolean DEBUG_REMOVE = false;
237    private static final boolean DEBUG_BROADCASTS = false;
238    private static final boolean DEBUG_SHOW_INFO = false;
239    private static final boolean DEBUG_PACKAGE_INFO = false;
240    private static final boolean DEBUG_INTENT_MATCHING = false;
241    private static final boolean DEBUG_PACKAGE_SCANNING = false;
242    private static final boolean DEBUG_VERIFY = false;
243    private static final boolean DEBUG_DEXOPT = false;
244    private static final boolean DEBUG_ABI_SELECTION = false;
245
246    private static final int RADIO_UID = Process.PHONE_UID;
247    private static final int LOG_UID = Process.LOG_UID;
248    private static final int NFC_UID = Process.NFC_UID;
249    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
250    private static final int SHELL_UID = Process.SHELL_UID;
251
252    // Cap the size of permission trees that 3rd party apps can define
253    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
254
255    // Suffix used during package installation when copying/moving
256    // package apks to install directory.
257    private static final String INSTALL_PACKAGE_SUFFIX = "-";
258
259    static final int SCAN_NO_DEX = 1<<1;
260    static final int SCAN_FORCE_DEX = 1<<2;
261    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
262    static final int SCAN_NEW_INSTALL = 1<<4;
263    static final int SCAN_NO_PATHS = 1<<5;
264    static final int SCAN_UPDATE_TIME = 1<<6;
265    static final int SCAN_DEFER_DEX = 1<<7;
266    static final int SCAN_BOOTING = 1<<8;
267    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
268    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
269    static final int SCAN_REPLACING = 1<<11;
270
271    static final int REMOVE_CHATTY = 1<<16;
272
273    /**
274     * Timeout (in milliseconds) after which the watchdog should declare that
275     * our handler thread is wedged.  The usual default for such things is one
276     * minute but we sometimes do very lengthy I/O operations on this thread,
277     * such as installing multi-gigabyte applications, so ours needs to be longer.
278     */
279    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
280
281    /**
282     * Whether verification is enabled by default.
283     */
284    private static final boolean DEFAULT_VERIFY_ENABLE = true;
285
286    /**
287     * The default maximum time to wait for the verification agent to return in
288     * milliseconds.
289     */
290    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
291
292    /**
293     * The default response for package verification timeout.
294     *
295     * This can be either PackageManager.VERIFICATION_ALLOW or
296     * PackageManager.VERIFICATION_REJECT.
297     */
298    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
299
300    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
301
302    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
303            DEFAULT_CONTAINER_PACKAGE,
304            "com.android.defcontainer.DefaultContainerService");
305
306    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
307
308    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
309
310    private static String sPreferredInstructionSet;
311
312    final ServiceThread mHandlerThread;
313
314    private static final String IDMAP_PREFIX = "/data/resource-cache/";
315    private static final String IDMAP_SUFFIX = "@idmap";
316
317    final PackageHandler mHandler;
318
319    /**
320     * Messages for {@link #mHandler} that need to wait for system ready before
321     * being dispatched.
322     */
323    private ArrayList<Message> mPostSystemReadyMessages;
324
325    final int mSdkVersion = Build.VERSION.SDK_INT;
326
327    final Context mContext;
328    final boolean mFactoryTest;
329    final boolean mOnlyCore;
330    final boolean mLazyDexOpt;
331    final DisplayMetrics mMetrics;
332    final int mDefParseFlags;
333    final String[] mSeparateProcesses;
334
335    // This is where all application persistent data goes.
336    final File mAppDataDir;
337
338    // This is where all application persistent data goes for secondary users.
339    final File mUserAppDataDir;
340
341    /** The location for ASEC container files on internal storage. */
342    final String mAsecInternalPath;
343
344    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
345    // LOCK HELD.  Can be called with mInstallLock held.
346    final Installer mInstaller;
347
348    /** Directory where installed third-party apps stored */
349    final File mAppInstallDir;
350
351    /**
352     * Directory to which applications installed internally have their
353     * 32 bit native libraries copied.
354     */
355    private File mAppLib32InstallDir;
356
357    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
358    // apps.
359    final File mDrmAppPrivateInstallDir;
360
361    // ----------------------------------------------------------------
362
363    // Lock for state used when installing and doing other long running
364    // operations.  Methods that must be called with this lock held have
365    // the suffix "LI".
366    final Object mInstallLock = new Object();
367
368    // ----------------------------------------------------------------
369
370    // Keys are String (package name), values are Package.  This also serves
371    // as the lock for the global state.  Methods that must be called with
372    // this lock held have the prefix "LP".
373    final HashMap<String, PackageParser.Package> mPackages =
374            new HashMap<String, PackageParser.Package>();
375
376    // Tracks available target package names -> overlay package paths.
377    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
378        new HashMap<String, HashMap<String, PackageParser.Package>>();
379
380    final Settings mSettings;
381    boolean mRestoredSettings;
382
383    // System configuration read by SystemConfig.
384    final int[] mGlobalGids;
385    final SparseArray<HashSet<String>> mSystemPermissions;
386    final HashMap<String, FeatureInfo> mAvailableFeatures;
387
388    // If mac_permissions.xml was found for seinfo labeling.
389    boolean mFoundPolicyFile;
390
391    // If a recursive restorecon of /data/data/<pkg> is needed.
392    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
393
394    public static final class SharedLibraryEntry {
395        public final String path;
396        public final String apk;
397
398        SharedLibraryEntry(String _path, String _apk) {
399            path = _path;
400            apk = _apk;
401        }
402    }
403
404    // Currently known shared libraries.
405    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
406            new HashMap<String, SharedLibraryEntry>();
407
408    // All available activities, for your resolving pleasure.
409    final ActivityIntentResolver mActivities =
410            new ActivityIntentResolver();
411
412    // All available receivers, for your resolving pleasure.
413    final ActivityIntentResolver mReceivers =
414            new ActivityIntentResolver();
415
416    // All available services, for your resolving pleasure.
417    final ServiceIntentResolver mServices = new ServiceIntentResolver();
418
419    // All available providers, for your resolving pleasure.
420    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
421
422    // Mapping from provider base names (first directory in content URI codePath)
423    // to the provider information.
424    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
425            new HashMap<String, PackageParser.Provider>();
426
427    // Mapping from instrumentation class names to info about them.
428    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
429            new HashMap<ComponentName, PackageParser.Instrumentation>();
430
431    // Mapping from permission names to info about them.
432    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
433            new HashMap<String, PackageParser.PermissionGroup>();
434
435    // Packages whose data we have transfered into another package, thus
436    // should no longer exist.
437    final HashSet<String> mTransferedPackages = new HashSet<String>();
438
439    // Broadcast actions that are only available to the system.
440    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
441
442    /** List of packages waiting for verification. */
443    final SparseArray<PackageVerificationState> mPendingVerification
444            = new SparseArray<PackageVerificationState>();
445
446    /** Set of packages associated with each app op permission. */
447    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
448
449    final PackageInstallerService mInstallerService;
450
451    HashSet<PackageParser.Package> mDeferredDexOpt = null;
452
453    // Cache of users who need badging.
454    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
455
456    /** Token for keys in mPendingVerification. */
457    private int mPendingVerificationToken = 0;
458
459    volatile boolean mSystemReady;
460    volatile boolean mSafeMode;
461    volatile boolean mHasSystemUidErrors;
462
463    ApplicationInfo mAndroidApplication;
464    final ActivityInfo mResolveActivity = new ActivityInfo();
465    final ResolveInfo mResolveInfo = new ResolveInfo();
466    ComponentName mResolveComponentName;
467    PackageParser.Package mPlatformPackage;
468    ComponentName mCustomResolverComponentName;
469
470    boolean mResolverReplaced = false;
471
472    // Set of pending broadcasts for aggregating enable/disable of components.
473    static class PendingPackageBroadcasts {
474        // for each user id, a map of <package name -> components within that package>
475        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
476
477        public PendingPackageBroadcasts() {
478            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
479        }
480
481        public ArrayList<String> get(int userId, String packageName) {
482            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
483            return packages.get(packageName);
484        }
485
486        public void put(int userId, String packageName, ArrayList<String> components) {
487            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
488            packages.put(packageName, components);
489        }
490
491        public void remove(int userId, String packageName) {
492            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
493            if (packages != null) {
494                packages.remove(packageName);
495            }
496        }
497
498        public void remove(int userId) {
499            mUidMap.remove(userId);
500        }
501
502        public int userIdCount() {
503            return mUidMap.size();
504        }
505
506        public int userIdAt(int n) {
507            return mUidMap.keyAt(n);
508        }
509
510        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
511            return mUidMap.get(userId);
512        }
513
514        public int size() {
515            // total number of pending broadcast entries across all userIds
516            int num = 0;
517            for (int i = 0; i< mUidMap.size(); i++) {
518                num += mUidMap.valueAt(i).size();
519            }
520            return num;
521        }
522
523        public void clear() {
524            mUidMap.clear();
525        }
526
527        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
528            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
529            if (map == null) {
530                map = new HashMap<String, ArrayList<String>>();
531                mUidMap.put(userId, map);
532            }
533            return map;
534        }
535    }
536    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
537
538    // Service Connection to remote media container service to copy
539    // package uri's from external media onto secure containers
540    // or internal storage.
541    private IMediaContainerService mContainerService = null;
542
543    static final int SEND_PENDING_BROADCAST = 1;
544    static final int MCS_BOUND = 3;
545    static final int END_COPY = 4;
546    static final int INIT_COPY = 5;
547    static final int MCS_UNBIND = 6;
548    static final int START_CLEANING_PACKAGE = 7;
549    static final int FIND_INSTALL_LOC = 8;
550    static final int POST_INSTALL = 9;
551    static final int MCS_RECONNECT = 10;
552    static final int MCS_GIVE_UP = 11;
553    static final int UPDATED_MEDIA_STATUS = 12;
554    static final int WRITE_SETTINGS = 13;
555    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
556    static final int PACKAGE_VERIFIED = 15;
557    static final int CHECK_PENDING_VERIFICATION = 16;
558
559    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
560
561    // Delay time in millisecs
562    static final int BROADCAST_DELAY = 10 * 1000;
563
564    static UserManagerService sUserManager;
565
566    // Stores a list of users whose package restrictions file needs to be updated
567    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
568
569    final private DefaultContainerConnection mDefContainerConn =
570            new DefaultContainerConnection();
571    class DefaultContainerConnection implements ServiceConnection {
572        public void onServiceConnected(ComponentName name, IBinder service) {
573            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
574            IMediaContainerService imcs =
575                IMediaContainerService.Stub.asInterface(service);
576            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
577        }
578
579        public void onServiceDisconnected(ComponentName name) {
580            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
581        }
582    };
583
584    // Recordkeeping of restore-after-install operations that are currently in flight
585    // between the Package Manager and the Backup Manager
586    class PostInstallData {
587        public InstallArgs args;
588        public PackageInstalledInfo res;
589
590        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
591            args = _a;
592            res = _r;
593        }
594    };
595    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
596    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
597
598    private final String mRequiredVerifierPackage;
599
600    private final PackageUsage mPackageUsage = new PackageUsage();
601
602    private class PackageUsage {
603        private static final int WRITE_INTERVAL
604            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
605
606        private final Object mFileLock = new Object();
607        private final AtomicLong mLastWritten = new AtomicLong(0);
608        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
609
610        private boolean mIsHistoricalPackageUsageAvailable = true;
611
612        boolean isHistoricalPackageUsageAvailable() {
613            return mIsHistoricalPackageUsageAvailable;
614        }
615
616        void write(boolean force) {
617            if (force) {
618                writeInternal();
619                return;
620            }
621            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
622                && !DEBUG_DEXOPT) {
623                return;
624            }
625            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
626                new Thread("PackageUsage_DiskWriter") {
627                    @Override
628                    public void run() {
629                        try {
630                            writeInternal();
631                        } finally {
632                            mBackgroundWriteRunning.set(false);
633                        }
634                    }
635                }.start();
636            }
637        }
638
639        private void writeInternal() {
640            synchronized (mPackages) {
641                synchronized (mFileLock) {
642                    AtomicFile file = getFile();
643                    FileOutputStream f = null;
644                    try {
645                        f = file.startWrite();
646                        BufferedOutputStream out = new BufferedOutputStream(f);
647                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
648                        StringBuilder sb = new StringBuilder();
649                        for (PackageParser.Package pkg : mPackages.values()) {
650                            if (pkg.mLastPackageUsageTimeInMills == 0) {
651                                continue;
652                            }
653                            sb.setLength(0);
654                            sb.append(pkg.packageName);
655                            sb.append(' ');
656                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
657                            sb.append('\n');
658                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
659                        }
660                        out.flush();
661                        file.finishWrite(f);
662                    } catch (IOException e) {
663                        if (f != null) {
664                            file.failWrite(f);
665                        }
666                        Log.e(TAG, "Failed to write package usage times", e);
667                    }
668                }
669            }
670            mLastWritten.set(SystemClock.elapsedRealtime());
671        }
672
673        void readLP() {
674            synchronized (mFileLock) {
675                AtomicFile file = getFile();
676                BufferedInputStream in = null;
677                try {
678                    in = new BufferedInputStream(file.openRead());
679                    StringBuffer sb = new StringBuffer();
680                    while (true) {
681                        String packageName = readToken(in, sb, ' ');
682                        if (packageName == null) {
683                            break;
684                        }
685                        String timeInMillisString = readToken(in, sb, '\n');
686                        if (timeInMillisString == null) {
687                            throw new IOException("Failed to find last usage time for package "
688                                                  + packageName);
689                        }
690                        PackageParser.Package pkg = mPackages.get(packageName);
691                        if (pkg == null) {
692                            continue;
693                        }
694                        long timeInMillis;
695                        try {
696                            timeInMillis = Long.parseLong(timeInMillisString.toString());
697                        } catch (NumberFormatException e) {
698                            throw new IOException("Failed to parse " + timeInMillisString
699                                                  + " as a long.", e);
700                        }
701                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
702                    }
703                } catch (FileNotFoundException expected) {
704                    mIsHistoricalPackageUsageAvailable = false;
705                } catch (IOException e) {
706                    Log.w(TAG, "Failed to read package usage times", e);
707                } finally {
708                    IoUtils.closeQuietly(in);
709                }
710            }
711            mLastWritten.set(SystemClock.elapsedRealtime());
712        }
713
714        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
715                throws IOException {
716            sb.setLength(0);
717            while (true) {
718                int ch = in.read();
719                if (ch == -1) {
720                    if (sb.length() == 0) {
721                        return null;
722                    }
723                    throw new IOException("Unexpected EOF");
724                }
725                if (ch == endOfToken) {
726                    return sb.toString();
727                }
728                sb.append((char)ch);
729            }
730        }
731
732        private AtomicFile getFile() {
733            File dataDir = Environment.getDataDirectory();
734            File systemDir = new File(dataDir, "system");
735            File fname = new File(systemDir, "package-usage.list");
736            return new AtomicFile(fname);
737        }
738    }
739
740    class PackageHandler extends Handler {
741        private boolean mBound = false;
742        final ArrayList<HandlerParams> mPendingInstalls =
743            new ArrayList<HandlerParams>();
744
745        private boolean connectToService() {
746            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
747                    " DefaultContainerService");
748            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
749            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
750            if (mContext.bindServiceAsUser(service, mDefContainerConn,
751                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
752                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
753                mBound = true;
754                return true;
755            }
756            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
757            return false;
758        }
759
760        private void disconnectService() {
761            mContainerService = null;
762            mBound = false;
763            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
764            mContext.unbindService(mDefContainerConn);
765            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
766        }
767
768        PackageHandler(Looper looper) {
769            super(looper);
770        }
771
772        public void handleMessage(Message msg) {
773            try {
774                doHandleMessage(msg);
775            } finally {
776                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
777            }
778        }
779
780        void doHandleMessage(Message msg) {
781            switch (msg.what) {
782                case INIT_COPY: {
783                    HandlerParams params = (HandlerParams) msg.obj;
784                    int idx = mPendingInstalls.size();
785                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
786                    // If a bind was already initiated we dont really
787                    // need to do anything. The pending install
788                    // will be processed later on.
789                    if (!mBound) {
790                        // If this is the only one pending we might
791                        // have to bind to the service again.
792                        if (!connectToService()) {
793                            Slog.e(TAG, "Failed to bind to media container service");
794                            params.serviceError();
795                            return;
796                        } else {
797                            // Once we bind to the service, the first
798                            // pending request will be processed.
799                            mPendingInstalls.add(idx, params);
800                        }
801                    } else {
802                        mPendingInstalls.add(idx, params);
803                        // Already bound to the service. Just make
804                        // sure we trigger off processing the first request.
805                        if (idx == 0) {
806                            mHandler.sendEmptyMessage(MCS_BOUND);
807                        }
808                    }
809                    break;
810                }
811                case MCS_BOUND: {
812                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
813                    if (msg.obj != null) {
814                        mContainerService = (IMediaContainerService) msg.obj;
815                    }
816                    if (mContainerService == null) {
817                        // Something seriously wrong. Bail out
818                        Slog.e(TAG, "Cannot bind to media container service");
819                        for (HandlerParams params : mPendingInstalls) {
820                            // Indicate service bind error
821                            params.serviceError();
822                        }
823                        mPendingInstalls.clear();
824                    } else if (mPendingInstalls.size() > 0) {
825                        HandlerParams params = mPendingInstalls.get(0);
826                        if (params != null) {
827                            if (params.startCopy()) {
828                                // We are done...  look for more work or to
829                                // go idle.
830                                if (DEBUG_SD_INSTALL) Log.i(TAG,
831                                        "Checking for more work or unbind...");
832                                // Delete pending install
833                                if (mPendingInstalls.size() > 0) {
834                                    mPendingInstalls.remove(0);
835                                }
836                                if (mPendingInstalls.size() == 0) {
837                                    if (mBound) {
838                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
839                                                "Posting delayed MCS_UNBIND");
840                                        removeMessages(MCS_UNBIND);
841                                        Message ubmsg = obtainMessage(MCS_UNBIND);
842                                        // Unbind after a little delay, to avoid
843                                        // continual thrashing.
844                                        sendMessageDelayed(ubmsg, 10000);
845                                    }
846                                } else {
847                                    // There are more pending requests in queue.
848                                    // Just post MCS_BOUND message to trigger processing
849                                    // of next pending install.
850                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
851                                            "Posting MCS_BOUND for next work");
852                                    mHandler.sendEmptyMessage(MCS_BOUND);
853                                }
854                            }
855                        }
856                    } else {
857                        // Should never happen ideally.
858                        Slog.w(TAG, "Empty queue");
859                    }
860                    break;
861                }
862                case MCS_RECONNECT: {
863                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
864                    if (mPendingInstalls.size() > 0) {
865                        if (mBound) {
866                            disconnectService();
867                        }
868                        if (!connectToService()) {
869                            Slog.e(TAG, "Failed to bind to media container service");
870                            for (HandlerParams params : mPendingInstalls) {
871                                // Indicate service bind error
872                                params.serviceError();
873                            }
874                            mPendingInstalls.clear();
875                        }
876                    }
877                    break;
878                }
879                case MCS_UNBIND: {
880                    // If there is no actual work left, then time to unbind.
881                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
882
883                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
884                        if (mBound) {
885                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
886
887                            disconnectService();
888                        }
889                    } else if (mPendingInstalls.size() > 0) {
890                        // There are more pending requests in queue.
891                        // Just post MCS_BOUND message to trigger processing
892                        // of next pending install.
893                        mHandler.sendEmptyMessage(MCS_BOUND);
894                    }
895
896                    break;
897                }
898                case MCS_GIVE_UP: {
899                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
900                    mPendingInstalls.remove(0);
901                    break;
902                }
903                case SEND_PENDING_BROADCAST: {
904                    String packages[];
905                    ArrayList<String> components[];
906                    int size = 0;
907                    int uids[];
908                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
909                    synchronized (mPackages) {
910                        if (mPendingBroadcasts == null) {
911                            return;
912                        }
913                        size = mPendingBroadcasts.size();
914                        if (size <= 0) {
915                            // Nothing to be done. Just return
916                            return;
917                        }
918                        packages = new String[size];
919                        components = new ArrayList[size];
920                        uids = new int[size];
921                        int i = 0;  // filling out the above arrays
922
923                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
924                            int packageUserId = mPendingBroadcasts.userIdAt(n);
925                            Iterator<Map.Entry<String, ArrayList<String>>> it
926                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
927                                            .entrySet().iterator();
928                            while (it.hasNext() && i < size) {
929                                Map.Entry<String, ArrayList<String>> ent = it.next();
930                                packages[i] = ent.getKey();
931                                components[i] = ent.getValue();
932                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
933                                uids[i] = (ps != null)
934                                        ? UserHandle.getUid(packageUserId, ps.appId)
935                                        : -1;
936                                i++;
937                            }
938                        }
939                        size = i;
940                        mPendingBroadcasts.clear();
941                    }
942                    // Send broadcasts
943                    for (int i = 0; i < size; i++) {
944                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
945                    }
946                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
947                    break;
948                }
949                case START_CLEANING_PACKAGE: {
950                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
951                    final String packageName = (String)msg.obj;
952                    final int userId = msg.arg1;
953                    final boolean andCode = msg.arg2 != 0;
954                    synchronized (mPackages) {
955                        if (userId == UserHandle.USER_ALL) {
956                            int[] users = sUserManager.getUserIds();
957                            for (int user : users) {
958                                mSettings.addPackageToCleanLPw(
959                                        new PackageCleanItem(user, packageName, andCode));
960                            }
961                        } else {
962                            mSettings.addPackageToCleanLPw(
963                                    new PackageCleanItem(userId, packageName, andCode));
964                        }
965                    }
966                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
967                    startCleaningPackages();
968                } break;
969                case POST_INSTALL: {
970                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
971                    PostInstallData data = mRunningInstalls.get(msg.arg1);
972                    mRunningInstalls.delete(msg.arg1);
973                    boolean deleteOld = false;
974
975                    if (data != null) {
976                        InstallArgs args = data.args;
977                        PackageInstalledInfo res = data.res;
978
979                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
980                            res.removedInfo.sendBroadcast(false, true, false);
981                            Bundle extras = new Bundle(1);
982                            extras.putInt(Intent.EXTRA_UID, res.uid);
983                            // Determine the set of users who are adding this
984                            // package for the first time vs. those who are seeing
985                            // an update.
986                            int[] firstUsers;
987                            int[] updateUsers = new int[0];
988                            if (res.origUsers == null || res.origUsers.length == 0) {
989                                firstUsers = res.newUsers;
990                            } else {
991                                firstUsers = new int[0];
992                                for (int i=0; i<res.newUsers.length; i++) {
993                                    int user = res.newUsers[i];
994                                    boolean isNew = true;
995                                    for (int j=0; j<res.origUsers.length; j++) {
996                                        if (res.origUsers[j] == user) {
997                                            isNew = false;
998                                            break;
999                                        }
1000                                    }
1001                                    if (isNew) {
1002                                        int[] newFirst = new int[firstUsers.length+1];
1003                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1004                                                firstUsers.length);
1005                                        newFirst[firstUsers.length] = user;
1006                                        firstUsers = newFirst;
1007                                    } else {
1008                                        int[] newUpdate = new int[updateUsers.length+1];
1009                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1010                                                updateUsers.length);
1011                                        newUpdate[updateUsers.length] = user;
1012                                        updateUsers = newUpdate;
1013                                    }
1014                                }
1015                            }
1016                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1017                                    res.pkg.applicationInfo.packageName,
1018                                    extras, null, null, firstUsers);
1019                            final boolean update = res.removedInfo.removedPackage != null;
1020                            if (update) {
1021                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1022                            }
1023                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1024                                    res.pkg.applicationInfo.packageName,
1025                                    extras, null, null, updateUsers);
1026                            if (update) {
1027                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1028                                        res.pkg.applicationInfo.packageName,
1029                                        extras, null, null, updateUsers);
1030                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1031                                        null, null,
1032                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1033
1034                                // treat asec-hosted packages like removable media on upgrade
1035                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1036                                    if (DEBUG_INSTALL) {
1037                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1038                                                + " is ASEC-hosted -> AVAILABLE");
1039                                    }
1040                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1041                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1042                                    pkgList.add(res.pkg.applicationInfo.packageName);
1043                                    sendResourcesChangedBroadcast(true, true,
1044                                            pkgList,uidArray, null);
1045                                }
1046                            }
1047                            if (res.removedInfo.args != null) {
1048                                // Remove the replaced package's older resources safely now
1049                                deleteOld = true;
1050                            }
1051
1052                            // Log current value of "unknown sources" setting
1053                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1054                                getUnknownSourcesSettings());
1055                        }
1056                        // Force a gc to clear up things
1057                        Runtime.getRuntime().gc();
1058                        // We delete after a gc for applications  on sdcard.
1059                        if (deleteOld) {
1060                            synchronized (mInstallLock) {
1061                                res.removedInfo.args.doPostDeleteLI(true);
1062                            }
1063                        }
1064                        if (args.observer != null) {
1065                            try {
1066                                Bundle extras = extrasForInstallResult(res);
1067                                args.observer.onPackageInstalled(res.name, res.returnCode,
1068                                        res.returnMsg, extras);
1069                            } catch (RemoteException e) {
1070                                Slog.i(TAG, "Observer no longer exists.");
1071                            }
1072                        }
1073                    } else {
1074                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1075                    }
1076                } break;
1077                case UPDATED_MEDIA_STATUS: {
1078                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1079                    boolean reportStatus = msg.arg1 == 1;
1080                    boolean doGc = msg.arg2 == 1;
1081                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1082                    if (doGc) {
1083                        // Force a gc to clear up stale containers.
1084                        Runtime.getRuntime().gc();
1085                    }
1086                    if (msg.obj != null) {
1087                        @SuppressWarnings("unchecked")
1088                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1089                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1090                        // Unload containers
1091                        unloadAllContainers(args);
1092                    }
1093                    if (reportStatus) {
1094                        try {
1095                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1096                            PackageHelper.getMountService().finishMediaUpdate();
1097                        } catch (RemoteException e) {
1098                            Log.e(TAG, "MountService not running?");
1099                        }
1100                    }
1101                } break;
1102                case WRITE_SETTINGS: {
1103                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1104                    synchronized (mPackages) {
1105                        removeMessages(WRITE_SETTINGS);
1106                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1107                        mSettings.writeLPr();
1108                        mDirtyUsers.clear();
1109                    }
1110                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1111                } break;
1112                case WRITE_PACKAGE_RESTRICTIONS: {
1113                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1114                    synchronized (mPackages) {
1115                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1116                        for (int userId : mDirtyUsers) {
1117                            mSettings.writePackageRestrictionsLPr(userId);
1118                        }
1119                        mDirtyUsers.clear();
1120                    }
1121                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1122                } break;
1123                case CHECK_PENDING_VERIFICATION: {
1124                    final int verificationId = msg.arg1;
1125                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1126
1127                    if ((state != null) && !state.timeoutExtended()) {
1128                        final InstallArgs args = state.getInstallArgs();
1129                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1130
1131                        Slog.i(TAG, "Verification timed out for " + originUri);
1132                        mPendingVerification.remove(verificationId);
1133
1134                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1135
1136                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1137                            Slog.i(TAG, "Continuing with installation of " + originUri);
1138                            state.setVerifierResponse(Binder.getCallingUid(),
1139                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1140                            broadcastPackageVerified(verificationId, originUri,
1141                                    PackageManager.VERIFICATION_ALLOW,
1142                                    state.getInstallArgs().getUser());
1143                            try {
1144                                ret = args.copyApk(mContainerService, true);
1145                            } catch (RemoteException e) {
1146                                Slog.e(TAG, "Could not contact the ContainerService");
1147                            }
1148                        } else {
1149                            broadcastPackageVerified(verificationId, originUri,
1150                                    PackageManager.VERIFICATION_REJECT,
1151                                    state.getInstallArgs().getUser());
1152                        }
1153
1154                        processPendingInstall(args, ret);
1155                        mHandler.sendEmptyMessage(MCS_UNBIND);
1156                    }
1157                    break;
1158                }
1159                case PACKAGE_VERIFIED: {
1160                    final int verificationId = msg.arg1;
1161
1162                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1163                    if (state == null) {
1164                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1165                        break;
1166                    }
1167
1168                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1169
1170                    state.setVerifierResponse(response.callerUid, response.code);
1171
1172                    if (state.isVerificationComplete()) {
1173                        mPendingVerification.remove(verificationId);
1174
1175                        final InstallArgs args = state.getInstallArgs();
1176                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1177
1178                        int ret;
1179                        if (state.isInstallAllowed()) {
1180                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1181                            broadcastPackageVerified(verificationId, originUri,
1182                                    response.code, state.getInstallArgs().getUser());
1183                            try {
1184                                ret = args.copyApk(mContainerService, true);
1185                            } catch (RemoteException e) {
1186                                Slog.e(TAG, "Could not contact the ContainerService");
1187                            }
1188                        } else {
1189                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1190                        }
1191
1192                        processPendingInstall(args, ret);
1193
1194                        mHandler.sendEmptyMessage(MCS_UNBIND);
1195                    }
1196
1197                    break;
1198                }
1199            }
1200        }
1201    }
1202
1203    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1204        Bundle extras = null;
1205        switch (res.returnCode) {
1206            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1207                extras = new Bundle();
1208                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1209                        res.origPermission);
1210                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1211                        res.origPackage);
1212                break;
1213            }
1214        }
1215        return extras;
1216    }
1217
1218    void scheduleWriteSettingsLocked() {
1219        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1220            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1221        }
1222    }
1223
1224    void scheduleWritePackageRestrictionsLocked(int userId) {
1225        if (!sUserManager.exists(userId)) return;
1226        mDirtyUsers.add(userId);
1227        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1228            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1229        }
1230    }
1231
1232    public static final PackageManagerService main(Context context, Installer installer,
1233            boolean factoryTest, boolean onlyCore) {
1234        PackageManagerService m = new PackageManagerService(context, installer,
1235                factoryTest, onlyCore);
1236        ServiceManager.addService("package", m);
1237        return m;
1238    }
1239
1240    static String[] splitString(String str, char sep) {
1241        int count = 1;
1242        int i = 0;
1243        while ((i=str.indexOf(sep, i)) >= 0) {
1244            count++;
1245            i++;
1246        }
1247
1248        String[] res = new String[count];
1249        i=0;
1250        count = 0;
1251        int lastI=0;
1252        while ((i=str.indexOf(sep, i)) >= 0) {
1253            res[count] = str.substring(lastI, i);
1254            count++;
1255            i++;
1256            lastI = i;
1257        }
1258        res[count] = str.substring(lastI, str.length());
1259        return res;
1260    }
1261
1262    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1263        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1264                Context.DISPLAY_SERVICE);
1265        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1266    }
1267
1268    public PackageManagerService(Context context, Installer installer,
1269            boolean factoryTest, boolean onlyCore) {
1270        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1271                SystemClock.uptimeMillis());
1272
1273        if (mSdkVersion <= 0) {
1274            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1275        }
1276
1277        mContext = context;
1278        mFactoryTest = factoryTest;
1279        mOnlyCore = onlyCore;
1280        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1281        mMetrics = new DisplayMetrics();
1282        mSettings = new Settings(context);
1283        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295
1296        String separateProcesses = SystemProperties.get("debug.separate_processes");
1297        if (separateProcesses != null && separateProcesses.length() > 0) {
1298            if ("*".equals(separateProcesses)) {
1299                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1300                mSeparateProcesses = null;
1301                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1302            } else {
1303                mDefParseFlags = 0;
1304                mSeparateProcesses = separateProcesses.split(",");
1305                Slog.w(TAG, "Running with debug.separate_processes: "
1306                        + separateProcesses);
1307            }
1308        } else {
1309            mDefParseFlags = 0;
1310            mSeparateProcesses = null;
1311        }
1312
1313        mInstaller = installer;
1314
1315        getDefaultDisplayMetrics(context, mMetrics);
1316
1317        SystemConfig systemConfig = SystemConfig.getInstance();
1318        mGlobalGids = systemConfig.getGlobalGids();
1319        mSystemPermissions = systemConfig.getSystemPermissions();
1320        mAvailableFeatures = systemConfig.getAvailableFeatures();
1321
1322        synchronized (mInstallLock) {
1323        // writer
1324        synchronized (mPackages) {
1325            mHandlerThread = new ServiceThread(TAG,
1326                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1327            mHandlerThread.start();
1328            mHandler = new PackageHandler(mHandlerThread.getLooper());
1329            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1330
1331            File dataDir = Environment.getDataDirectory();
1332            mAppDataDir = new File(dataDir, "data");
1333            mAppInstallDir = new File(dataDir, "app");
1334            mAppLib32InstallDir = new File(dataDir, "app-lib");
1335            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1336            mUserAppDataDir = new File(dataDir, "user");
1337            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1338
1339            sUserManager = new UserManagerService(context, this,
1340                    mInstallLock, mPackages);
1341
1342            // Propagate permission configuration in to package manager.
1343            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1344                    = systemConfig.getPermissions();
1345            for (int i=0; i<permConfig.size(); i++) {
1346                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1347                BasePermission bp = mSettings.mPermissions.get(perm.name);
1348                if (bp == null) {
1349                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1350                    mSettings.mPermissions.put(perm.name, bp);
1351                }
1352                if (perm.gids != null) {
1353                    bp.gids = appendInts(bp.gids, perm.gids);
1354                }
1355            }
1356
1357            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1358            for (int i=0; i<libConfig.size(); i++) {
1359                mSharedLibraries.put(libConfig.keyAt(i),
1360                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1361            }
1362
1363            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1364
1365            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1366                    mSdkVersion, mOnlyCore);
1367
1368            String customResolverActivity = Resources.getSystem().getString(
1369                    R.string.config_customResolverActivity);
1370            if (TextUtils.isEmpty(customResolverActivity)) {
1371                customResolverActivity = null;
1372            } else {
1373                mCustomResolverComponentName = ComponentName.unflattenFromString(
1374                        customResolverActivity);
1375            }
1376
1377            long startTime = SystemClock.uptimeMillis();
1378
1379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1380                    startTime);
1381
1382            // Set flag to monitor and not change apk file paths when
1383            // scanning install directories.
1384            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1385
1386            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1387
1388            /**
1389             * Add everything in the in the boot class path to the
1390             * list of process files because dexopt will have been run
1391             * if necessary during zygote startup.
1392             */
1393            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1394            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1395
1396            if (bootClassPath != null) {
1397                String[] bootClassPathElements = splitString(bootClassPath, ':');
1398                for (String element : bootClassPathElements) {
1399                    alreadyDexOpted.add(element);
1400                }
1401            } else {
1402                Slog.w(TAG, "No BOOTCLASSPATH found!");
1403            }
1404
1405            if (systemServerClassPath != null) {
1406                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1407                for (String element : systemServerClassPathElements) {
1408                    alreadyDexOpted.add(element);
1409                }
1410            } else {
1411                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1412            }
1413
1414            boolean didDexOptLibraryOrTool = false;
1415
1416            final List<String> allInstructionSets = getAllInstructionSets();
1417            final String[] dexCodeInstructionSets =
1418                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1419
1420            /**
1421             * Ensure all external libraries have had dexopt run on them.
1422             */
1423            if (mSharedLibraries.size() > 0) {
1424                // NOTE: For now, we're compiling these system "shared libraries"
1425                // (and framework jars) into all available architectures. It's possible
1426                // to compile them only when we come across an app that uses them (there's
1427                // already logic for that in scanPackageLI) but that adds some complexity.
1428                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1429                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1430                        final String lib = libEntry.path;
1431                        if (lib == null) {
1432                            continue;
1433                        }
1434
1435                        try {
1436                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1437                                                                                 dexCodeInstructionSet,
1438                                                                                 false);
1439                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1440                                alreadyDexOpted.add(lib);
1441
1442                                // The list of "shared libraries" we have at this point is
1443                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1444                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1445                                } else {
1446                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1447                                }
1448                                didDexOptLibraryOrTool = true;
1449                            }
1450                        } catch (FileNotFoundException e) {
1451                            Slog.w(TAG, "Library not found: " + lib);
1452                        } catch (IOException e) {
1453                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1454                                    + e.getMessage());
1455                        }
1456                    }
1457                }
1458            }
1459
1460            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1461
1462            // Gross hack for now: we know this file doesn't contain any
1463            // code, so don't dexopt it to avoid the resulting log spew.
1464            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1465
1466            // Gross hack for now: we know this file is only part of
1467            // the boot class path for art, so don't dexopt it to
1468            // avoid the resulting log spew.
1469            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1470
1471            /**
1472             * And there are a number of commands implemented in Java, which
1473             * we currently need to do the dexopt on so that they can be
1474             * run from a non-root shell.
1475             */
1476            String[] frameworkFiles = frameworkDir.list();
1477            if (frameworkFiles != null) {
1478                // TODO: We could compile these only for the most preferred ABI. We should
1479                // first double check that the dex files for these commands are not referenced
1480                // by other system apps.
1481                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1482                    for (int i=0; i<frameworkFiles.length; i++) {
1483                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1484                        String path = libPath.getPath();
1485                        // Skip the file if we already did it.
1486                        if (alreadyDexOpted.contains(path)) {
1487                            continue;
1488                        }
1489                        // Skip the file if it is not a type we want to dexopt.
1490                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1491                            continue;
1492                        }
1493                        try {
1494                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1495                                                                                 dexCodeInstructionSet,
1496                                                                                 false);
1497                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1498                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1499                                didDexOptLibraryOrTool = true;
1500                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1501                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1502                                didDexOptLibraryOrTool = true;
1503                            }
1504                        } catch (FileNotFoundException e) {
1505                            Slog.w(TAG, "Jar not found: " + path);
1506                        } catch (IOException e) {
1507                            Slog.w(TAG, "Exception reading jar: " + path, e);
1508                        }
1509                    }
1510                }
1511            }
1512
1513            // Collect vendor overlay packages.
1514            // (Do this before scanning any apps.)
1515            // For security and version matching reason, only consider
1516            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1517            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1518            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1519                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1520
1521            // Find base frameworks (resource packages without code).
1522            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1523                    | PackageParser.PARSE_IS_SYSTEM_DIR
1524                    | PackageParser.PARSE_IS_PRIVILEGED,
1525                    scanFlags | SCAN_NO_DEX, 0);
1526
1527            // Collected privileged system packages.
1528            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1529            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1530                    | PackageParser.PARSE_IS_SYSTEM_DIR
1531                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1532
1533            // Collect ordinary system packages.
1534            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1535            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1536                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1537
1538            // Collect all vendor packages.
1539            File vendorAppDir = new File("/vendor/app");
1540            try {
1541                vendorAppDir = vendorAppDir.getCanonicalFile();
1542            } catch (IOException e) {
1543                // failed to look up canonical path, continue with original one
1544            }
1545            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1546                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1547
1548            // Collect all OEM packages.
1549            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1550            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1551                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1552
1553            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1554            mInstaller.moveFiles();
1555
1556            // Prune any system packages that no longer exist.
1557            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1558            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1559            if (!mOnlyCore) {
1560                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1561                while (psit.hasNext()) {
1562                    PackageSetting ps = psit.next();
1563
1564                    /*
1565                     * If this is not a system app, it can't be a
1566                     * disable system app.
1567                     */
1568                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1569                        continue;
1570                    }
1571
1572                    /*
1573                     * If the package is scanned, it's not erased.
1574                     */
1575                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1576                    if (scannedPkg != null) {
1577                        /*
1578                         * If the system app is both scanned and in the
1579                         * disabled packages list, then it must have been
1580                         * added via OTA. Remove it from the currently
1581                         * scanned package so the previously user-installed
1582                         * application can be scanned.
1583                         */
1584                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1585                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1586                                    + ps.name + "; removing system app.  Last known codePath="
1587                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1588                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1589                                    + scannedPkg.mVersionCode);
1590                            removePackageLI(ps, true);
1591                            expectingBetter.put(ps.name, ps.codePath);
1592                        }
1593
1594                        continue;
1595                    }
1596
1597                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1598                        psit.remove();
1599                        logCriticalInfo(Log.WARN, "System package " + ps.name
1600                                + " no longer exists; wiping its data");
1601                        removeDataDirsLI(ps.name);
1602                    } else {
1603                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1604                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1605                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1606                        }
1607                    }
1608                }
1609            }
1610
1611            //look for any incomplete package installations
1612            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1613            //clean up list
1614            for(int i = 0; i < deletePkgsList.size(); i++) {
1615                //clean up here
1616                cleanupInstallFailedPackage(deletePkgsList.get(i));
1617            }
1618            //delete tmp files
1619            deleteTempPackageFiles();
1620
1621            // Remove any shared userIDs that have no associated packages
1622            mSettings.pruneSharedUsersLPw();
1623
1624            if (!mOnlyCore) {
1625                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1626                        SystemClock.uptimeMillis());
1627                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1628
1629                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1630                        scanFlags, 0);
1631
1632                /**
1633                 * Remove disable package settings for any updated system
1634                 * apps that were removed via an OTA. If they're not a
1635                 * previously-updated app, remove them completely.
1636                 * Otherwise, just revoke their system-level permissions.
1637                 */
1638                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1639                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1640                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1641
1642                    String msg;
1643                    if (deletedPkg == null) {
1644                        msg = "Updated system package " + deletedAppName
1645                                + " no longer exists; wiping its data";
1646                        removeDataDirsLI(deletedAppName);
1647                    } else {
1648                        msg = "Updated system app + " + deletedAppName
1649                                + " no longer present; removing system privileges for "
1650                                + deletedAppName;
1651
1652                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1653
1654                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1655                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1656                    }
1657                    logCriticalInfo(Log.WARN, msg);
1658                }
1659
1660                /**
1661                 * Make sure all system apps that we expected to appear on
1662                 * the userdata partition actually showed up. If they never
1663                 * appeared, crawl back and revive the system version.
1664                 */
1665                for (int i = 0; i < expectingBetter.size(); i++) {
1666                    final String packageName = expectingBetter.keyAt(i);
1667                    if (!mPackages.containsKey(packageName)) {
1668                        final File scanFile = expectingBetter.valueAt(i);
1669
1670                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1671                                + " but never showed up; reverting to system");
1672
1673                        final int reparseFlags;
1674                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1675                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1676                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1677                                    | PackageParser.PARSE_IS_PRIVILEGED;
1678                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1679                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1680                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1681                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1682                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1683                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1684                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1685                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1686                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1687                        } else {
1688                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1689                            continue;
1690                        }
1691
1692                        mSettings.enableSystemPackageLPw(packageName);
1693
1694                        try {
1695                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1696                        } catch (PackageManagerException e) {
1697                            Slog.e(TAG, "Failed to parse original system package: "
1698                                    + e.getMessage());
1699                        }
1700                    }
1701                }
1702            }
1703
1704            // Now that we know all of the shared libraries, update all clients to have
1705            // the correct library paths.
1706            updateAllSharedLibrariesLPw();
1707
1708            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1709                // NOTE: We ignore potential failures here during a system scan (like
1710                // the rest of the commands above) because there's precious little we
1711                // can do about it. A settings error is reported, though.
1712                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1713                        false /* force dexopt */, false /* defer dexopt */);
1714            }
1715
1716            // Now that we know all the packages we are keeping,
1717            // read and update their last usage times.
1718            mPackageUsage.readLP();
1719
1720            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1721                    SystemClock.uptimeMillis());
1722            Slog.i(TAG, "Time to scan packages: "
1723                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1724                    + " seconds");
1725
1726            // If the platform SDK has changed since the last time we booted,
1727            // we need to re-grant app permission to catch any new ones that
1728            // appear.  This is really a hack, and means that apps can in some
1729            // cases get permissions that the user didn't initially explicitly
1730            // allow...  it would be nice to have some better way to handle
1731            // this situation.
1732            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1733                    != mSdkVersion;
1734            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1735                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1736                    + "; regranting permissions for internal storage");
1737            mSettings.mInternalSdkPlatform = mSdkVersion;
1738
1739            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1740                    | (regrantPermissions
1741                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1742                            : 0));
1743
1744            // If this is the first boot, and it is a normal boot, then
1745            // we need to initialize the default preferred apps.
1746            if (!mRestoredSettings && !onlyCore) {
1747                mSettings.readDefaultPreferredAppsLPw(this, 0);
1748            }
1749
1750            // If this is first boot after an OTA, and a normal boot, then
1751            // we need to clear code cache directories.
1752            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1753                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1754                for (String pkgName : mSettings.mPackages.keySet()) {
1755                    deleteCodeCacheDirsLI(pkgName);
1756                }
1757                mSettings.mFingerprint = Build.FINGERPRINT;
1758            }
1759
1760            // All the changes are done during package scanning.
1761            mSettings.updateInternalDatabaseVersion();
1762
1763            // can downgrade to reader
1764            mSettings.writeLPr();
1765
1766            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1767                    SystemClock.uptimeMillis());
1768
1769
1770            mRequiredVerifierPackage = getRequiredVerifierLPr();
1771        } // synchronized (mPackages)
1772        } // synchronized (mInstallLock)
1773
1774        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1775
1776        // Now after opening every single application zip, make sure they
1777        // are all flushed.  Not really needed, but keeps things nice and
1778        // tidy.
1779        Runtime.getRuntime().gc();
1780    }
1781
1782    @Override
1783    public boolean isFirstBoot() {
1784        return !mRestoredSettings;
1785    }
1786
1787    @Override
1788    public boolean isOnlyCoreApps() {
1789        return mOnlyCore;
1790    }
1791
1792    private String getRequiredVerifierLPr() {
1793        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1794        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1795                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1796
1797        String requiredVerifier = null;
1798
1799        final int N = receivers.size();
1800        for (int i = 0; i < N; i++) {
1801            final ResolveInfo info = receivers.get(i);
1802
1803            if (info.activityInfo == null) {
1804                continue;
1805            }
1806
1807            final String packageName = info.activityInfo.packageName;
1808
1809            final PackageSetting ps = mSettings.mPackages.get(packageName);
1810            if (ps == null) {
1811                continue;
1812            }
1813
1814            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1815            if (!gp.grantedPermissions
1816                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1817                continue;
1818            }
1819
1820            if (requiredVerifier != null) {
1821                throw new RuntimeException("There can be only one required verifier");
1822            }
1823
1824            requiredVerifier = packageName;
1825        }
1826
1827        return requiredVerifier;
1828    }
1829
1830    @Override
1831    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1832            throws RemoteException {
1833        try {
1834            return super.onTransact(code, data, reply, flags);
1835        } catch (RuntimeException e) {
1836            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1837                Slog.wtf(TAG, "Package Manager Crash", e);
1838            }
1839            throw e;
1840        }
1841    }
1842
1843    void cleanupInstallFailedPackage(PackageSetting ps) {
1844        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1845
1846        removeDataDirsLI(ps.name);
1847        if (ps.codePath != null) {
1848            if (ps.codePath.isDirectory()) {
1849                FileUtils.deleteContents(ps.codePath);
1850            }
1851            ps.codePath.delete();
1852        }
1853        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1854            if (ps.resourcePath.isDirectory()) {
1855                FileUtils.deleteContents(ps.resourcePath);
1856            }
1857            ps.resourcePath.delete();
1858        }
1859        mSettings.removePackageLPw(ps.name);
1860    }
1861
1862    static int[] appendInts(int[] cur, int[] add) {
1863        if (add == null) return cur;
1864        if (cur == null) return add;
1865        final int N = add.length;
1866        for (int i=0; i<N; i++) {
1867            cur = appendInt(cur, add[i]);
1868        }
1869        return cur;
1870    }
1871
1872    static int[] removeInts(int[] cur, int[] rem) {
1873        if (rem == null) return cur;
1874        if (cur == null) return cur;
1875        final int N = rem.length;
1876        for (int i=0; i<N; i++) {
1877            cur = removeInt(cur, rem[i]);
1878        }
1879        return cur;
1880    }
1881
1882    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1883        if (!sUserManager.exists(userId)) return null;
1884        final PackageSetting ps = (PackageSetting) p.mExtras;
1885        if (ps == null) {
1886            return null;
1887        }
1888        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1889        final PackageUserState state = ps.readUserState(userId);
1890        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1891                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1892                state, userId);
1893    }
1894
1895    @Override
1896    public boolean isPackageAvailable(String packageName, int userId) {
1897        if (!sUserManager.exists(userId)) return false;
1898        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1899        synchronized (mPackages) {
1900            PackageParser.Package p = mPackages.get(packageName);
1901            if (p != null) {
1902                final PackageSetting ps = (PackageSetting) p.mExtras;
1903                if (ps != null) {
1904                    final PackageUserState state = ps.readUserState(userId);
1905                    if (state != null) {
1906                        return PackageParser.isAvailable(state);
1907                    }
1908                }
1909            }
1910        }
1911        return false;
1912    }
1913
1914    @Override
1915    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1916        if (!sUserManager.exists(userId)) return null;
1917        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1918        // reader
1919        synchronized (mPackages) {
1920            PackageParser.Package p = mPackages.get(packageName);
1921            if (DEBUG_PACKAGE_INFO)
1922                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1923            if (p != null) {
1924                return generatePackageInfo(p, flags, userId);
1925            }
1926            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1927                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1928            }
1929        }
1930        return null;
1931    }
1932
1933    @Override
1934    public String[] currentToCanonicalPackageNames(String[] names) {
1935        String[] out = new String[names.length];
1936        // reader
1937        synchronized (mPackages) {
1938            for (int i=names.length-1; i>=0; i--) {
1939                PackageSetting ps = mSettings.mPackages.get(names[i]);
1940                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1941            }
1942        }
1943        return out;
1944    }
1945
1946    @Override
1947    public String[] canonicalToCurrentPackageNames(String[] names) {
1948        String[] out = new String[names.length];
1949        // reader
1950        synchronized (mPackages) {
1951            for (int i=names.length-1; i>=0; i--) {
1952                String cur = mSettings.mRenamedPackages.get(names[i]);
1953                out[i] = cur != null ? cur : names[i];
1954            }
1955        }
1956        return out;
1957    }
1958
1959    @Override
1960    public int getPackageUid(String packageName, int userId) {
1961        if (!sUserManager.exists(userId)) return -1;
1962        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1963        // reader
1964        synchronized (mPackages) {
1965            PackageParser.Package p = mPackages.get(packageName);
1966            if(p != null) {
1967                return UserHandle.getUid(userId, p.applicationInfo.uid);
1968            }
1969            PackageSetting ps = mSettings.mPackages.get(packageName);
1970            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1971                return -1;
1972            }
1973            p = ps.pkg;
1974            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1975        }
1976    }
1977
1978    @Override
1979    public int[] getPackageGids(String packageName) {
1980        // reader
1981        synchronized (mPackages) {
1982            PackageParser.Package p = mPackages.get(packageName);
1983            if (DEBUG_PACKAGE_INFO)
1984                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1985            if (p != null) {
1986                final PackageSetting ps = (PackageSetting)p.mExtras;
1987                return ps.getGids();
1988            }
1989        }
1990        // stupid thing to indicate an error.
1991        return new int[0];
1992    }
1993
1994    static final PermissionInfo generatePermissionInfo(
1995            BasePermission bp, int flags) {
1996        if (bp.perm != null) {
1997            return PackageParser.generatePermissionInfo(bp.perm, flags);
1998        }
1999        PermissionInfo pi = new PermissionInfo();
2000        pi.name = bp.name;
2001        pi.packageName = bp.sourcePackage;
2002        pi.nonLocalizedLabel = bp.name;
2003        pi.protectionLevel = bp.protectionLevel;
2004        return pi;
2005    }
2006
2007    @Override
2008    public PermissionInfo getPermissionInfo(String name, int flags) {
2009        // reader
2010        synchronized (mPackages) {
2011            final BasePermission p = mSettings.mPermissions.get(name);
2012            if (p != null) {
2013                return generatePermissionInfo(p, flags);
2014            }
2015            return null;
2016        }
2017    }
2018
2019    @Override
2020    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2021        // reader
2022        synchronized (mPackages) {
2023            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2024            for (BasePermission p : mSettings.mPermissions.values()) {
2025                if (group == null) {
2026                    if (p.perm == null || p.perm.info.group == null) {
2027                        out.add(generatePermissionInfo(p, flags));
2028                    }
2029                } else {
2030                    if (p.perm != null && group.equals(p.perm.info.group)) {
2031                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2032                    }
2033                }
2034            }
2035
2036            if (out.size() > 0) {
2037                return out;
2038            }
2039            return mPermissionGroups.containsKey(group) ? out : null;
2040        }
2041    }
2042
2043    @Override
2044    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2045        // reader
2046        synchronized (mPackages) {
2047            return PackageParser.generatePermissionGroupInfo(
2048                    mPermissionGroups.get(name), flags);
2049        }
2050    }
2051
2052    @Override
2053    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2054        // reader
2055        synchronized (mPackages) {
2056            final int N = mPermissionGroups.size();
2057            ArrayList<PermissionGroupInfo> out
2058                    = new ArrayList<PermissionGroupInfo>(N);
2059            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2060                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2061            }
2062            return out;
2063        }
2064    }
2065
2066    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2067            int userId) {
2068        if (!sUserManager.exists(userId)) return null;
2069        PackageSetting ps = mSettings.mPackages.get(packageName);
2070        if (ps != null) {
2071            if (ps.pkg == null) {
2072                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2073                        flags, userId);
2074                if (pInfo != null) {
2075                    return pInfo.applicationInfo;
2076                }
2077                return null;
2078            }
2079            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2080                    ps.readUserState(userId), userId);
2081        }
2082        return null;
2083    }
2084
2085    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2086            int userId) {
2087        if (!sUserManager.exists(userId)) return null;
2088        PackageSetting ps = mSettings.mPackages.get(packageName);
2089        if (ps != null) {
2090            PackageParser.Package pkg = ps.pkg;
2091            if (pkg == null) {
2092                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2093                    return null;
2094                }
2095                // Only data remains, so we aren't worried about code paths
2096                pkg = new PackageParser.Package(packageName);
2097                pkg.applicationInfo.packageName = packageName;
2098                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2099                pkg.applicationInfo.dataDir =
2100                        getDataPathForPackage(packageName, 0).getPath();
2101                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2102                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2103            }
2104            return generatePackageInfo(pkg, flags, userId);
2105        }
2106        return null;
2107    }
2108
2109    @Override
2110    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2111        if (!sUserManager.exists(userId)) return null;
2112        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2113        // writer
2114        synchronized (mPackages) {
2115            PackageParser.Package p = mPackages.get(packageName);
2116            if (DEBUG_PACKAGE_INFO) Log.v(
2117                    TAG, "getApplicationInfo " + packageName
2118                    + ": " + p);
2119            if (p != null) {
2120                PackageSetting ps = mSettings.mPackages.get(packageName);
2121                if (ps == null) return null;
2122                // Note: isEnabledLP() does not apply here - always return info
2123                return PackageParser.generateApplicationInfo(
2124                        p, flags, ps.readUserState(userId), userId);
2125            }
2126            if ("android".equals(packageName)||"system".equals(packageName)) {
2127                return mAndroidApplication;
2128            }
2129            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2130                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2131            }
2132        }
2133        return null;
2134    }
2135
2136
2137    @Override
2138    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2139        mContext.enforceCallingOrSelfPermission(
2140                android.Manifest.permission.CLEAR_APP_CACHE, null);
2141        // Queue up an async operation since clearing cache may take a little while.
2142        mHandler.post(new Runnable() {
2143            public void run() {
2144                mHandler.removeCallbacks(this);
2145                int retCode = -1;
2146                synchronized (mInstallLock) {
2147                    retCode = mInstaller.freeCache(freeStorageSize);
2148                    if (retCode < 0) {
2149                        Slog.w(TAG, "Couldn't clear application caches");
2150                    }
2151                }
2152                if (observer != null) {
2153                    try {
2154                        observer.onRemoveCompleted(null, (retCode >= 0));
2155                    } catch (RemoteException e) {
2156                        Slog.w(TAG, "RemoveException when invoking call back");
2157                    }
2158                }
2159            }
2160        });
2161    }
2162
2163    @Override
2164    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2165        mContext.enforceCallingOrSelfPermission(
2166                android.Manifest.permission.CLEAR_APP_CACHE, null);
2167        // Queue up an async operation since clearing cache may take a little while.
2168        mHandler.post(new Runnable() {
2169            public void run() {
2170                mHandler.removeCallbacks(this);
2171                int retCode = -1;
2172                synchronized (mInstallLock) {
2173                    retCode = mInstaller.freeCache(freeStorageSize);
2174                    if (retCode < 0) {
2175                        Slog.w(TAG, "Couldn't clear application caches");
2176                    }
2177                }
2178                if(pi != null) {
2179                    try {
2180                        // Callback via pending intent
2181                        int code = (retCode >= 0) ? 1 : 0;
2182                        pi.sendIntent(null, code, null,
2183                                null, null);
2184                    } catch (SendIntentException e1) {
2185                        Slog.i(TAG, "Failed to send pending intent");
2186                    }
2187                }
2188            }
2189        });
2190    }
2191
2192    void freeStorage(long freeStorageSize) throws IOException {
2193        synchronized (mInstallLock) {
2194            if (mInstaller.freeCache(freeStorageSize) < 0) {
2195                throw new IOException("Failed to free enough space");
2196            }
2197        }
2198    }
2199
2200    @Override
2201    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2202        if (!sUserManager.exists(userId)) return null;
2203        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2204        synchronized (mPackages) {
2205            PackageParser.Activity a = mActivities.mActivities.get(component);
2206
2207            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2208            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2209                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2210                if (ps == null) return null;
2211                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2212                        userId);
2213            }
2214            if (mResolveComponentName.equals(component)) {
2215                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2216                        new PackageUserState(), userId);
2217            }
2218        }
2219        return null;
2220    }
2221
2222    @Override
2223    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2224            String resolvedType) {
2225        synchronized (mPackages) {
2226            PackageParser.Activity a = mActivities.mActivities.get(component);
2227            if (a == null) {
2228                return false;
2229            }
2230            for (int i=0; i<a.intents.size(); i++) {
2231                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2232                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2233                    return true;
2234                }
2235            }
2236            return false;
2237        }
2238    }
2239
2240    @Override
2241    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2242        if (!sUserManager.exists(userId)) return null;
2243        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2244        synchronized (mPackages) {
2245            PackageParser.Activity a = mReceivers.mActivities.get(component);
2246            if (DEBUG_PACKAGE_INFO) Log.v(
2247                TAG, "getReceiverInfo " + component + ": " + a);
2248            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2249                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2250                if (ps == null) return null;
2251                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2252                        userId);
2253            }
2254        }
2255        return null;
2256    }
2257
2258    @Override
2259    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2260        if (!sUserManager.exists(userId)) return null;
2261        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2262        synchronized (mPackages) {
2263            PackageParser.Service s = mServices.mServices.get(component);
2264            if (DEBUG_PACKAGE_INFO) Log.v(
2265                TAG, "getServiceInfo " + component + ": " + s);
2266            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2267                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2268                if (ps == null) return null;
2269                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2270                        userId);
2271            }
2272        }
2273        return null;
2274    }
2275
2276    @Override
2277    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2278        if (!sUserManager.exists(userId)) return null;
2279        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2280        synchronized (mPackages) {
2281            PackageParser.Provider p = mProviders.mProviders.get(component);
2282            if (DEBUG_PACKAGE_INFO) Log.v(
2283                TAG, "getProviderInfo " + component + ": " + p);
2284            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2285                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2286                if (ps == null) return null;
2287                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2288                        userId);
2289            }
2290        }
2291        return null;
2292    }
2293
2294    @Override
2295    public String[] getSystemSharedLibraryNames() {
2296        Set<String> libSet;
2297        synchronized (mPackages) {
2298            libSet = mSharedLibraries.keySet();
2299            int size = libSet.size();
2300            if (size > 0) {
2301                String[] libs = new String[size];
2302                libSet.toArray(libs);
2303                return libs;
2304            }
2305        }
2306        return null;
2307    }
2308
2309    @Override
2310    public FeatureInfo[] getSystemAvailableFeatures() {
2311        Collection<FeatureInfo> featSet;
2312        synchronized (mPackages) {
2313            featSet = mAvailableFeatures.values();
2314            int size = featSet.size();
2315            if (size > 0) {
2316                FeatureInfo[] features = new FeatureInfo[size+1];
2317                featSet.toArray(features);
2318                FeatureInfo fi = new FeatureInfo();
2319                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2320                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2321                features[size] = fi;
2322                return features;
2323            }
2324        }
2325        return null;
2326    }
2327
2328    @Override
2329    public boolean hasSystemFeature(String name) {
2330        synchronized (mPackages) {
2331            return mAvailableFeatures.containsKey(name);
2332        }
2333    }
2334
2335    private void checkValidCaller(int uid, int userId) {
2336        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2337            return;
2338
2339        throw new SecurityException("Caller uid=" + uid
2340                + " is not privileged to communicate with user=" + userId);
2341    }
2342
2343    @Override
2344    public int checkPermission(String permName, String pkgName) {
2345        synchronized (mPackages) {
2346            PackageParser.Package p = mPackages.get(pkgName);
2347            if (p != null && p.mExtras != null) {
2348                PackageSetting ps = (PackageSetting)p.mExtras;
2349                if (ps.sharedUser != null) {
2350                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2351                        return PackageManager.PERMISSION_GRANTED;
2352                    }
2353                } else if (ps.grantedPermissions.contains(permName)) {
2354                    return PackageManager.PERMISSION_GRANTED;
2355                }
2356            }
2357        }
2358        return PackageManager.PERMISSION_DENIED;
2359    }
2360
2361    @Override
2362    public int checkUidPermission(String permName, int uid) {
2363        synchronized (mPackages) {
2364            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2365            if (obj != null) {
2366                GrantedPermissions gp = (GrantedPermissions)obj;
2367                if (gp.grantedPermissions.contains(permName)) {
2368                    return PackageManager.PERMISSION_GRANTED;
2369                }
2370            } else {
2371                HashSet<String> perms = mSystemPermissions.get(uid);
2372                if (perms != null && perms.contains(permName)) {
2373                    return PackageManager.PERMISSION_GRANTED;
2374                }
2375            }
2376        }
2377        return PackageManager.PERMISSION_DENIED;
2378    }
2379
2380    /**
2381     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2382     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2383     * @param checkShell TODO(yamasani):
2384     * @param message the message to log on security exception
2385     */
2386    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2387            boolean checkShell, String message) {
2388        if (userId < 0) {
2389            throw new IllegalArgumentException("Invalid userId " + userId);
2390        }
2391        if (checkShell) {
2392            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2393        }
2394        if (userId == UserHandle.getUserId(callingUid)) return;
2395        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2396            if (requireFullPermission) {
2397                mContext.enforceCallingOrSelfPermission(
2398                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2399            } else {
2400                try {
2401                    mContext.enforceCallingOrSelfPermission(
2402                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2403                } catch (SecurityException se) {
2404                    mContext.enforceCallingOrSelfPermission(
2405                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2406                }
2407            }
2408        }
2409    }
2410
2411    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2412        if (callingUid == Process.SHELL_UID) {
2413            if (userHandle >= 0
2414                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2415                throw new SecurityException("Shell does not have permission to access user "
2416                        + userHandle);
2417            } else if (userHandle < 0) {
2418                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2419                        + Debug.getCallers(3));
2420            }
2421        }
2422    }
2423
2424    private BasePermission findPermissionTreeLP(String permName) {
2425        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2426            if (permName.startsWith(bp.name) &&
2427                    permName.length() > bp.name.length() &&
2428                    permName.charAt(bp.name.length()) == '.') {
2429                return bp;
2430            }
2431        }
2432        return null;
2433    }
2434
2435    private BasePermission checkPermissionTreeLP(String permName) {
2436        if (permName != null) {
2437            BasePermission bp = findPermissionTreeLP(permName);
2438            if (bp != null) {
2439                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2440                    return bp;
2441                }
2442                throw new SecurityException("Calling uid "
2443                        + Binder.getCallingUid()
2444                        + " is not allowed to add to permission tree "
2445                        + bp.name + " owned by uid " + bp.uid);
2446            }
2447        }
2448        throw new SecurityException("No permission tree found for " + permName);
2449    }
2450
2451    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2452        if (s1 == null) {
2453            return s2 == null;
2454        }
2455        if (s2 == null) {
2456            return false;
2457        }
2458        if (s1.getClass() != s2.getClass()) {
2459            return false;
2460        }
2461        return s1.equals(s2);
2462    }
2463
2464    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2465        if (pi1.icon != pi2.icon) return false;
2466        if (pi1.logo != pi2.logo) return false;
2467        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2468        if (!compareStrings(pi1.name, pi2.name)) return false;
2469        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2470        // We'll take care of setting this one.
2471        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2472        // These are not currently stored in settings.
2473        //if (!compareStrings(pi1.group, pi2.group)) return false;
2474        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2475        //if (pi1.labelRes != pi2.labelRes) return false;
2476        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2477        return true;
2478    }
2479
2480    int permissionInfoFootprint(PermissionInfo info) {
2481        int size = info.name.length();
2482        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2483        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2484        return size;
2485    }
2486
2487    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2488        int size = 0;
2489        for (BasePermission perm : mSettings.mPermissions.values()) {
2490            if (perm.uid == tree.uid) {
2491                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2492            }
2493        }
2494        return size;
2495    }
2496
2497    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2498        // We calculate the max size of permissions defined by this uid and throw
2499        // if that plus the size of 'info' would exceed our stated maximum.
2500        if (tree.uid != Process.SYSTEM_UID) {
2501            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2502            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2503                throw new SecurityException("Permission tree size cap exceeded");
2504            }
2505        }
2506    }
2507
2508    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2509        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2510            throw new SecurityException("Label must be specified in permission");
2511        }
2512        BasePermission tree = checkPermissionTreeLP(info.name);
2513        BasePermission bp = mSettings.mPermissions.get(info.name);
2514        boolean added = bp == null;
2515        boolean changed = true;
2516        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2517        if (added) {
2518            enforcePermissionCapLocked(info, tree);
2519            bp = new BasePermission(info.name, tree.sourcePackage,
2520                    BasePermission.TYPE_DYNAMIC);
2521        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2522            throw new SecurityException(
2523                    "Not allowed to modify non-dynamic permission "
2524                    + info.name);
2525        } else {
2526            if (bp.protectionLevel == fixedLevel
2527                    && bp.perm.owner.equals(tree.perm.owner)
2528                    && bp.uid == tree.uid
2529                    && comparePermissionInfos(bp.perm.info, info)) {
2530                changed = false;
2531            }
2532        }
2533        bp.protectionLevel = fixedLevel;
2534        info = new PermissionInfo(info);
2535        info.protectionLevel = fixedLevel;
2536        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2537        bp.perm.info.packageName = tree.perm.info.packageName;
2538        bp.uid = tree.uid;
2539        if (added) {
2540            mSettings.mPermissions.put(info.name, bp);
2541        }
2542        if (changed) {
2543            if (!async) {
2544                mSettings.writeLPr();
2545            } else {
2546                scheduleWriteSettingsLocked();
2547            }
2548        }
2549        return added;
2550    }
2551
2552    @Override
2553    public boolean addPermission(PermissionInfo info) {
2554        synchronized (mPackages) {
2555            return addPermissionLocked(info, false);
2556        }
2557    }
2558
2559    @Override
2560    public boolean addPermissionAsync(PermissionInfo info) {
2561        synchronized (mPackages) {
2562            return addPermissionLocked(info, true);
2563        }
2564    }
2565
2566    @Override
2567    public void removePermission(String name) {
2568        synchronized (mPackages) {
2569            checkPermissionTreeLP(name);
2570            BasePermission bp = mSettings.mPermissions.get(name);
2571            if (bp != null) {
2572                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2573                    throw new SecurityException(
2574                            "Not allowed to modify non-dynamic permission "
2575                            + name);
2576                }
2577                mSettings.mPermissions.remove(name);
2578                mSettings.writeLPr();
2579            }
2580        }
2581    }
2582
2583    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2584        int index = pkg.requestedPermissions.indexOf(bp.name);
2585        if (index == -1) {
2586            throw new SecurityException("Package " + pkg.packageName
2587                    + " has not requested permission " + bp.name);
2588        }
2589        boolean isNormal =
2590                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2591                        == PermissionInfo.PROTECTION_NORMAL);
2592        boolean isDangerous =
2593                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2594                        == PermissionInfo.PROTECTION_DANGEROUS);
2595        boolean isDevelopment =
2596                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2597
2598        if (!isNormal && !isDangerous && !isDevelopment) {
2599            throw new SecurityException("Permission " + bp.name
2600                    + " is not a changeable permission type");
2601        }
2602
2603        if (isNormal || isDangerous) {
2604            if (pkg.requestedPermissionsRequired.get(index)) {
2605                throw new SecurityException("Can't change " + bp.name
2606                        + ". It is required by the application");
2607            }
2608        }
2609    }
2610
2611    @Override
2612    public void grantPermission(String packageName, String permissionName) {
2613        mContext.enforceCallingOrSelfPermission(
2614                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2615        synchronized (mPackages) {
2616            final PackageParser.Package pkg = mPackages.get(packageName);
2617            if (pkg == null) {
2618                throw new IllegalArgumentException("Unknown package: " + packageName);
2619            }
2620            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2621            if (bp == null) {
2622                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2623            }
2624
2625            checkGrantRevokePermissions(pkg, bp);
2626
2627            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2628            if (ps == null) {
2629                return;
2630            }
2631            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2632            if (gp.grantedPermissions.add(permissionName)) {
2633                if (ps.haveGids) {
2634                    gp.gids = appendInts(gp.gids, bp.gids);
2635                }
2636                mSettings.writeLPr();
2637            }
2638        }
2639    }
2640
2641    @Override
2642    public void revokePermission(String packageName, String permissionName) {
2643        int changedAppId = -1;
2644
2645        synchronized (mPackages) {
2646            final PackageParser.Package pkg = mPackages.get(packageName);
2647            if (pkg == null) {
2648                throw new IllegalArgumentException("Unknown package: " + packageName);
2649            }
2650            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2651                mContext.enforceCallingOrSelfPermission(
2652                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2653            }
2654            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2655            if (bp == null) {
2656                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2657            }
2658
2659            checkGrantRevokePermissions(pkg, bp);
2660
2661            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2662            if (ps == null) {
2663                return;
2664            }
2665            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2666            if (gp.grantedPermissions.remove(permissionName)) {
2667                gp.grantedPermissions.remove(permissionName);
2668                if (ps.haveGids) {
2669                    gp.gids = removeInts(gp.gids, bp.gids);
2670                }
2671                mSettings.writeLPr();
2672                changedAppId = ps.appId;
2673            }
2674        }
2675
2676        if (changedAppId >= 0) {
2677            // We changed the perm on someone, kill its processes.
2678            IActivityManager am = ActivityManagerNative.getDefault();
2679            if (am != null) {
2680                final int callingUserId = UserHandle.getCallingUserId();
2681                final long ident = Binder.clearCallingIdentity();
2682                try {
2683                    //XXX we should only revoke for the calling user's app permissions,
2684                    // but for now we impact all users.
2685                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2686                    //        "revoke " + permissionName);
2687                    int[] users = sUserManager.getUserIds();
2688                    for (int user : users) {
2689                        am.killUid(UserHandle.getUid(user, changedAppId),
2690                                "revoke " + permissionName);
2691                    }
2692                } catch (RemoteException e) {
2693                } finally {
2694                    Binder.restoreCallingIdentity(ident);
2695                }
2696            }
2697        }
2698    }
2699
2700    @Override
2701    public boolean isProtectedBroadcast(String actionName) {
2702        synchronized (mPackages) {
2703            return mProtectedBroadcasts.contains(actionName);
2704        }
2705    }
2706
2707    @Override
2708    public int checkSignatures(String pkg1, String pkg2) {
2709        synchronized (mPackages) {
2710            final PackageParser.Package p1 = mPackages.get(pkg1);
2711            final PackageParser.Package p2 = mPackages.get(pkg2);
2712            if (p1 == null || p1.mExtras == null
2713                    || p2 == null || p2.mExtras == null) {
2714                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2715            }
2716            return compareSignatures(p1.mSignatures, p2.mSignatures);
2717        }
2718    }
2719
2720    @Override
2721    public int checkUidSignatures(int uid1, int uid2) {
2722        // Map to base uids.
2723        uid1 = UserHandle.getAppId(uid1);
2724        uid2 = UserHandle.getAppId(uid2);
2725        // reader
2726        synchronized (mPackages) {
2727            Signature[] s1;
2728            Signature[] s2;
2729            Object obj = mSettings.getUserIdLPr(uid1);
2730            if (obj != null) {
2731                if (obj instanceof SharedUserSetting) {
2732                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2733                } else if (obj instanceof PackageSetting) {
2734                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2735                } else {
2736                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2737                }
2738            } else {
2739                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2740            }
2741            obj = mSettings.getUserIdLPr(uid2);
2742            if (obj != null) {
2743                if (obj instanceof SharedUserSetting) {
2744                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2745                } else if (obj instanceof PackageSetting) {
2746                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2747                } else {
2748                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2749                }
2750            } else {
2751                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2752            }
2753            return compareSignatures(s1, s2);
2754        }
2755    }
2756
2757    /**
2758     * Compares two sets of signatures. Returns:
2759     * <br />
2760     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2761     * <br />
2762     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2763     * <br />
2764     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2765     * <br />
2766     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2767     * <br />
2768     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2769     */
2770    static int compareSignatures(Signature[] s1, Signature[] s2) {
2771        if (s1 == null) {
2772            return s2 == null
2773                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2774                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2775        }
2776
2777        if (s2 == null) {
2778            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2779        }
2780
2781        if (s1.length != s2.length) {
2782            return PackageManager.SIGNATURE_NO_MATCH;
2783        }
2784
2785        // Since both signature sets are of size 1, we can compare without HashSets.
2786        if (s1.length == 1) {
2787            return s1[0].equals(s2[0]) ?
2788                    PackageManager.SIGNATURE_MATCH :
2789                    PackageManager.SIGNATURE_NO_MATCH;
2790        }
2791
2792        HashSet<Signature> set1 = new HashSet<Signature>();
2793        for (Signature sig : s1) {
2794            set1.add(sig);
2795        }
2796        HashSet<Signature> set2 = new HashSet<Signature>();
2797        for (Signature sig : s2) {
2798            set2.add(sig);
2799        }
2800        // Make sure s2 contains all signatures in s1.
2801        if (set1.equals(set2)) {
2802            return PackageManager.SIGNATURE_MATCH;
2803        }
2804        return PackageManager.SIGNATURE_NO_MATCH;
2805    }
2806
2807    /**
2808     * If the database version for this type of package (internal storage or
2809     * external storage) is less than the version where package signatures
2810     * were updated, return true.
2811     */
2812    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2813        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2814                DatabaseVersion.SIGNATURE_END_ENTITY))
2815                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2816                        DatabaseVersion.SIGNATURE_END_ENTITY));
2817    }
2818
2819    /**
2820     * Used for backward compatibility to make sure any packages with
2821     * certificate chains get upgraded to the new style. {@code existingSigs}
2822     * will be in the old format (since they were stored on disk from before the
2823     * system upgrade) and {@code scannedSigs} will be in the newer format.
2824     */
2825    private int compareSignaturesCompat(PackageSignatures existingSigs,
2826            PackageParser.Package scannedPkg) {
2827        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2828            return PackageManager.SIGNATURE_NO_MATCH;
2829        }
2830
2831        HashSet<Signature> existingSet = new HashSet<Signature>();
2832        for (Signature sig : existingSigs.mSignatures) {
2833            existingSet.add(sig);
2834        }
2835        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2836        for (Signature sig : scannedPkg.mSignatures) {
2837            try {
2838                Signature[] chainSignatures = sig.getChainSignatures();
2839                for (Signature chainSig : chainSignatures) {
2840                    scannedCompatSet.add(chainSig);
2841                }
2842            } catch (CertificateEncodingException e) {
2843                scannedCompatSet.add(sig);
2844            }
2845        }
2846        /*
2847         * Make sure the expanded scanned set contains all signatures in the
2848         * existing one.
2849         */
2850        if (scannedCompatSet.equals(existingSet)) {
2851            // Migrate the old signatures to the new scheme.
2852            existingSigs.assignSignatures(scannedPkg.mSignatures);
2853            // The new KeySets will be re-added later in the scanning process.
2854            synchronized (mPackages) {
2855                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2856            }
2857            return PackageManager.SIGNATURE_MATCH;
2858        }
2859        return PackageManager.SIGNATURE_NO_MATCH;
2860    }
2861
2862    @Override
2863    public String[] getPackagesForUid(int uid) {
2864        uid = UserHandle.getAppId(uid);
2865        // reader
2866        synchronized (mPackages) {
2867            Object obj = mSettings.getUserIdLPr(uid);
2868            if (obj instanceof SharedUserSetting) {
2869                final SharedUserSetting sus = (SharedUserSetting) obj;
2870                final int N = sus.packages.size();
2871                final String[] res = new String[N];
2872                final Iterator<PackageSetting> it = sus.packages.iterator();
2873                int i = 0;
2874                while (it.hasNext()) {
2875                    res[i++] = it.next().name;
2876                }
2877                return res;
2878            } else if (obj instanceof PackageSetting) {
2879                final PackageSetting ps = (PackageSetting) obj;
2880                return new String[] { ps.name };
2881            }
2882        }
2883        return null;
2884    }
2885
2886    @Override
2887    public String getNameForUid(int uid) {
2888        // reader
2889        synchronized (mPackages) {
2890            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2891            if (obj instanceof SharedUserSetting) {
2892                final SharedUserSetting sus = (SharedUserSetting) obj;
2893                return sus.name + ":" + sus.userId;
2894            } else if (obj instanceof PackageSetting) {
2895                final PackageSetting ps = (PackageSetting) obj;
2896                return ps.name;
2897            }
2898        }
2899        return null;
2900    }
2901
2902    @Override
2903    public int getUidForSharedUser(String sharedUserName) {
2904        if(sharedUserName == null) {
2905            return -1;
2906        }
2907        // reader
2908        synchronized (mPackages) {
2909            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2910            if (suid == null) {
2911                return -1;
2912            }
2913            return suid.userId;
2914        }
2915    }
2916
2917    @Override
2918    public int getFlagsForUid(int uid) {
2919        synchronized (mPackages) {
2920            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2921            if (obj instanceof SharedUserSetting) {
2922                final SharedUserSetting sus = (SharedUserSetting) obj;
2923                return sus.pkgFlags;
2924            } else if (obj instanceof PackageSetting) {
2925                final PackageSetting ps = (PackageSetting) obj;
2926                return ps.pkgFlags;
2927            }
2928        }
2929        return 0;
2930    }
2931
2932    @Override
2933    public String[] getAppOpPermissionPackages(String permissionName) {
2934        synchronized (mPackages) {
2935            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2936            if (pkgs == null) {
2937                return null;
2938            }
2939            return pkgs.toArray(new String[pkgs.size()]);
2940        }
2941    }
2942
2943    @Override
2944    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2945            int flags, int userId) {
2946        if (!sUserManager.exists(userId)) return null;
2947        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2948        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2949        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2950    }
2951
2952    @Override
2953    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2954            IntentFilter filter, int match, ComponentName activity) {
2955        final int userId = UserHandle.getCallingUserId();
2956        if (DEBUG_PREFERRED) {
2957            Log.v(TAG, "setLastChosenActivity intent=" + intent
2958                + " resolvedType=" + resolvedType
2959                + " flags=" + flags
2960                + " filter=" + filter
2961                + " match=" + match
2962                + " activity=" + activity);
2963            filter.dump(new PrintStreamPrinter(System.out), "    ");
2964        }
2965        intent.setComponent(null);
2966        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2967        // Find any earlier preferred or last chosen entries and nuke them
2968        findPreferredActivity(intent, resolvedType,
2969                flags, query, 0, false, true, false, userId);
2970        // Add the new activity as the last chosen for this filter
2971        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2972                "Setting last chosen");
2973    }
2974
2975    @Override
2976    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2977        final int userId = UserHandle.getCallingUserId();
2978        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2979        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2980        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2981                false, false, false, userId);
2982    }
2983
2984    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2985            int flags, List<ResolveInfo> query, int userId) {
2986        if (query != null) {
2987            final int N = query.size();
2988            if (N == 1) {
2989                return query.get(0);
2990            } else if (N > 1) {
2991                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2992                // If there is more than one activity with the same priority,
2993                // then let the user decide between them.
2994                ResolveInfo r0 = query.get(0);
2995                ResolveInfo r1 = query.get(1);
2996                if (DEBUG_INTENT_MATCHING || debug) {
2997                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2998                            + r1.activityInfo.name + "=" + r1.priority);
2999                }
3000                // If the first activity has a higher priority, or a different
3001                // default, then it is always desireable to pick it.
3002                if (r0.priority != r1.priority
3003                        || r0.preferredOrder != r1.preferredOrder
3004                        || r0.isDefault != r1.isDefault) {
3005                    return query.get(0);
3006                }
3007                // If we have saved a preference for a preferred activity for
3008                // this Intent, use that.
3009                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3010                        flags, query, r0.priority, true, false, debug, userId);
3011                if (ri != null) {
3012                    return ri;
3013                }
3014                if (userId != 0) {
3015                    ri = new ResolveInfo(mResolveInfo);
3016                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3017                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3018                            ri.activityInfo.applicationInfo);
3019                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3020                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3021                    return ri;
3022                }
3023                return mResolveInfo;
3024            }
3025        }
3026        return null;
3027    }
3028
3029    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3030            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3031        final int N = query.size();
3032        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3033                .get(userId);
3034        // Get the list of persistent preferred activities that handle the intent
3035        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3036        List<PersistentPreferredActivity> pprefs = ppir != null
3037                ? ppir.queryIntent(intent, resolvedType,
3038                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3039                : null;
3040        if (pprefs != null && pprefs.size() > 0) {
3041            final int M = pprefs.size();
3042            for (int i=0; i<M; i++) {
3043                final PersistentPreferredActivity ppa = pprefs.get(i);
3044                if (DEBUG_PREFERRED || debug) {
3045                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3046                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3047                            + "\n  component=" + ppa.mComponent);
3048                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3049                }
3050                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3051                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3052                if (DEBUG_PREFERRED || debug) {
3053                    Slog.v(TAG, "Found persistent preferred activity:");
3054                    if (ai != null) {
3055                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3056                    } else {
3057                        Slog.v(TAG, "  null");
3058                    }
3059                }
3060                if (ai == null) {
3061                    // This previously registered persistent preferred activity
3062                    // component is no longer known. Ignore it and do NOT remove it.
3063                    continue;
3064                }
3065                for (int j=0; j<N; j++) {
3066                    final ResolveInfo ri = query.get(j);
3067                    if (!ri.activityInfo.applicationInfo.packageName
3068                            .equals(ai.applicationInfo.packageName)) {
3069                        continue;
3070                    }
3071                    if (!ri.activityInfo.name.equals(ai.name)) {
3072                        continue;
3073                    }
3074                    //  Found a persistent preference that can handle the intent.
3075                    if (DEBUG_PREFERRED || debug) {
3076                        Slog.v(TAG, "Returning persistent preferred activity: " +
3077                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3078                    }
3079                    return ri;
3080                }
3081            }
3082        }
3083        return null;
3084    }
3085
3086    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3087            List<ResolveInfo> query, int priority, boolean always,
3088            boolean removeMatches, boolean debug, int userId) {
3089        if (!sUserManager.exists(userId)) return null;
3090        // writer
3091        synchronized (mPackages) {
3092            if (intent.getSelector() != null) {
3093                intent = intent.getSelector();
3094            }
3095            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3096
3097            // Try to find a matching persistent preferred activity.
3098            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3099                    debug, userId);
3100
3101            // If a persistent preferred activity matched, use it.
3102            if (pri != null) {
3103                return pri;
3104            }
3105
3106            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3107            // Get the list of preferred activities that handle the intent
3108            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3109            List<PreferredActivity> prefs = pir != null
3110                    ? pir.queryIntent(intent, resolvedType,
3111                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3112                    : null;
3113            if (prefs != null && prefs.size() > 0) {
3114                boolean changed = false;
3115                try {
3116                    // First figure out how good the original match set is.
3117                    // We will only allow preferred activities that came
3118                    // from the same match quality.
3119                    int match = 0;
3120
3121                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3122
3123                    final int N = query.size();
3124                    for (int j=0; j<N; j++) {
3125                        final ResolveInfo ri = query.get(j);
3126                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3127                                + ": 0x" + Integer.toHexString(match));
3128                        if (ri.match > match) {
3129                            match = ri.match;
3130                        }
3131                    }
3132
3133                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3134                            + Integer.toHexString(match));
3135
3136                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3137                    final int M = prefs.size();
3138                    for (int i=0; i<M; i++) {
3139                        final PreferredActivity pa = prefs.get(i);
3140                        if (DEBUG_PREFERRED || debug) {
3141                            Slog.v(TAG, "Checking PreferredActivity ds="
3142                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3143                                    + "\n  component=" + pa.mPref.mComponent);
3144                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3145                        }
3146                        if (pa.mPref.mMatch != match) {
3147                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3148                                    + Integer.toHexString(pa.mPref.mMatch));
3149                            continue;
3150                        }
3151                        // If it's not an "always" type preferred activity and that's what we're
3152                        // looking for, skip it.
3153                        if (always && !pa.mPref.mAlways) {
3154                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3155                            continue;
3156                        }
3157                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3158                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3159                        if (DEBUG_PREFERRED || debug) {
3160                            Slog.v(TAG, "Found preferred activity:");
3161                            if (ai != null) {
3162                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3163                            } else {
3164                                Slog.v(TAG, "  null");
3165                            }
3166                        }
3167                        if (ai == null) {
3168                            // This previously registered preferred activity
3169                            // component is no longer known.  Most likely an update
3170                            // to the app was installed and in the new version this
3171                            // component no longer exists.  Clean it up by removing
3172                            // it from the preferred activities list, and skip it.
3173                            Slog.w(TAG, "Removing dangling preferred activity: "
3174                                    + pa.mPref.mComponent);
3175                            pir.removeFilter(pa);
3176                            changed = true;
3177                            continue;
3178                        }
3179                        for (int j=0; j<N; j++) {
3180                            final ResolveInfo ri = query.get(j);
3181                            if (!ri.activityInfo.applicationInfo.packageName
3182                                    .equals(ai.applicationInfo.packageName)) {
3183                                continue;
3184                            }
3185                            if (!ri.activityInfo.name.equals(ai.name)) {
3186                                continue;
3187                            }
3188
3189                            if (removeMatches) {
3190                                pir.removeFilter(pa);
3191                                changed = true;
3192                                if (DEBUG_PREFERRED) {
3193                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3194                                }
3195                                break;
3196                            }
3197
3198                            // Okay we found a previously set preferred or last chosen app.
3199                            // If the result set is different from when this
3200                            // was created, we need to clear it and re-ask the
3201                            // user their preference, if we're looking for an "always" type entry.
3202                            if (always && !pa.mPref.sameSet(query, priority)) {
3203                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3204                                        + intent + " type " + resolvedType);
3205                                if (DEBUG_PREFERRED) {
3206                                    Slog.v(TAG, "Removing preferred activity since set changed "
3207                                            + pa.mPref.mComponent);
3208                                }
3209                                pir.removeFilter(pa);
3210                                // Re-add the filter as a "last chosen" entry (!always)
3211                                PreferredActivity lastChosen = new PreferredActivity(
3212                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3213                                pir.addFilter(lastChosen);
3214                                changed = true;
3215                                return null;
3216                            }
3217
3218                            // Yay! Either the set matched or we're looking for the last chosen
3219                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3220                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3221                            return ri;
3222                        }
3223                    }
3224                } finally {
3225                    if (changed) {
3226                        if (DEBUG_PREFERRED) {
3227                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3228                        }
3229                        mSettings.writePackageRestrictionsLPr(userId);
3230                    }
3231                }
3232            }
3233        }
3234        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3235        return null;
3236    }
3237
3238    /*
3239     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3240     */
3241    @Override
3242    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3243            int targetUserId) {
3244        mContext.enforceCallingOrSelfPermission(
3245                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3246        List<CrossProfileIntentFilter> matches =
3247                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3248        if (matches != null) {
3249            int size = matches.size();
3250            for (int i = 0; i < size; i++) {
3251                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3252            }
3253        }
3254        return false;
3255    }
3256
3257    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3258            String resolvedType, int userId) {
3259        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3260        if (resolver != null) {
3261            return resolver.queryIntent(intent, resolvedType, false, userId);
3262        }
3263        return null;
3264    }
3265
3266    @Override
3267    public List<ResolveInfo> queryIntentActivities(Intent intent,
3268            String resolvedType, int flags, int userId) {
3269        if (!sUserManager.exists(userId)) return Collections.emptyList();
3270        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3271        ComponentName comp = intent.getComponent();
3272        if (comp == null) {
3273            if (intent.getSelector() != null) {
3274                intent = intent.getSelector();
3275                comp = intent.getComponent();
3276            }
3277        }
3278
3279        if (comp != null) {
3280            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3281            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3282            if (ai != null) {
3283                final ResolveInfo ri = new ResolveInfo();
3284                ri.activityInfo = ai;
3285                list.add(ri);
3286            }
3287            return list;
3288        }
3289
3290        // reader
3291        synchronized (mPackages) {
3292            final String pkgName = intent.getPackage();
3293            if (pkgName == null) {
3294                List<CrossProfileIntentFilter> matchingFilters =
3295                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3296                // Check for results that need to skip the current profile.
3297                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3298                        resolvedType, flags, userId);
3299                if (resolveInfo != null) {
3300                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3301                    result.add(resolveInfo);
3302                    return result;
3303                }
3304                // Check for cross profile results.
3305                resolveInfo = queryCrossProfileIntents(
3306                        matchingFilters, intent, resolvedType, flags, userId);
3307
3308                // Check for results in the current profile.
3309                List<ResolveInfo> result = mActivities.queryIntent(
3310                        intent, resolvedType, flags, userId);
3311                if (resolveInfo != null) {
3312                    result.add(resolveInfo);
3313                    Collections.sort(result, mResolvePrioritySorter);
3314                }
3315                return result;
3316            }
3317            final PackageParser.Package pkg = mPackages.get(pkgName);
3318            if (pkg != null) {
3319                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3320                        pkg.activities, userId);
3321            }
3322            return new ArrayList<ResolveInfo>();
3323        }
3324    }
3325
3326    private ResolveInfo querySkipCurrentProfileIntents(
3327            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3328            int flags, int sourceUserId) {
3329        if (matchingFilters != null) {
3330            int size = matchingFilters.size();
3331            for (int i = 0; i < size; i ++) {
3332                CrossProfileIntentFilter filter = matchingFilters.get(i);
3333                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3334                    // Checking if there are activities in the target user that can handle the
3335                    // intent.
3336                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3337                            flags, sourceUserId);
3338                    if (resolveInfo != null) {
3339                        return resolveInfo;
3340                    }
3341                }
3342            }
3343        }
3344        return null;
3345    }
3346
3347    // Return matching ResolveInfo if any for skip current profile intent filters.
3348    private ResolveInfo queryCrossProfileIntents(
3349            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3350            int flags, int sourceUserId) {
3351        if (matchingFilters != null) {
3352            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3353            // match the same intent. For performance reasons, it is better not to
3354            // run queryIntent twice for the same userId
3355            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3356            int size = matchingFilters.size();
3357            for (int i = 0; i < size; i++) {
3358                CrossProfileIntentFilter filter = matchingFilters.get(i);
3359                int targetUserId = filter.getTargetUserId();
3360                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3361                        && !alreadyTriedUserIds.get(targetUserId)) {
3362                    // Checking if there are activities in the target user that can handle the
3363                    // intent.
3364                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3365                            flags, sourceUserId);
3366                    if (resolveInfo != null) return resolveInfo;
3367                    alreadyTriedUserIds.put(targetUserId, true);
3368                }
3369            }
3370        }
3371        return null;
3372    }
3373
3374    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3375            String resolvedType, int flags, int sourceUserId) {
3376        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3377                resolvedType, flags, filter.getTargetUserId());
3378        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3379            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3380        }
3381        return null;
3382    }
3383
3384    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3385            int sourceUserId, int targetUserId) {
3386        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3387        String className;
3388        if (targetUserId == UserHandle.USER_OWNER) {
3389            className = FORWARD_INTENT_TO_USER_OWNER;
3390        } else {
3391            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3392        }
3393        ComponentName forwardingActivityComponentName = new ComponentName(
3394                mAndroidApplication.packageName, className);
3395        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3396                sourceUserId);
3397        if (targetUserId == UserHandle.USER_OWNER) {
3398            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3399            forwardingResolveInfo.noResourceId = true;
3400        }
3401        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3402        forwardingResolveInfo.priority = 0;
3403        forwardingResolveInfo.preferredOrder = 0;
3404        forwardingResolveInfo.match = 0;
3405        forwardingResolveInfo.isDefault = true;
3406        forwardingResolveInfo.filter = filter;
3407        forwardingResolveInfo.targetUserId = targetUserId;
3408        return forwardingResolveInfo;
3409    }
3410
3411    @Override
3412    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3413            Intent[] specifics, String[] specificTypes, Intent intent,
3414            String resolvedType, int flags, int userId) {
3415        if (!sUserManager.exists(userId)) return Collections.emptyList();
3416        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3417                false, "query intent activity options");
3418        final String resultsAction = intent.getAction();
3419
3420        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3421                | PackageManager.GET_RESOLVED_FILTER, userId);
3422
3423        if (DEBUG_INTENT_MATCHING) {
3424            Log.v(TAG, "Query " + intent + ": " + results);
3425        }
3426
3427        int specificsPos = 0;
3428        int N;
3429
3430        // todo: note that the algorithm used here is O(N^2).  This
3431        // isn't a problem in our current environment, but if we start running
3432        // into situations where we have more than 5 or 10 matches then this
3433        // should probably be changed to something smarter...
3434
3435        // First we go through and resolve each of the specific items
3436        // that were supplied, taking care of removing any corresponding
3437        // duplicate items in the generic resolve list.
3438        if (specifics != null) {
3439            for (int i=0; i<specifics.length; i++) {
3440                final Intent sintent = specifics[i];
3441                if (sintent == null) {
3442                    continue;
3443                }
3444
3445                if (DEBUG_INTENT_MATCHING) {
3446                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3447                }
3448
3449                String action = sintent.getAction();
3450                if (resultsAction != null && resultsAction.equals(action)) {
3451                    // If this action was explicitly requested, then don't
3452                    // remove things that have it.
3453                    action = null;
3454                }
3455
3456                ResolveInfo ri = null;
3457                ActivityInfo ai = null;
3458
3459                ComponentName comp = sintent.getComponent();
3460                if (comp == null) {
3461                    ri = resolveIntent(
3462                        sintent,
3463                        specificTypes != null ? specificTypes[i] : null,
3464                            flags, userId);
3465                    if (ri == null) {
3466                        continue;
3467                    }
3468                    if (ri == mResolveInfo) {
3469                        // ACK!  Must do something better with this.
3470                    }
3471                    ai = ri.activityInfo;
3472                    comp = new ComponentName(ai.applicationInfo.packageName,
3473                            ai.name);
3474                } else {
3475                    ai = getActivityInfo(comp, flags, userId);
3476                    if (ai == null) {
3477                        continue;
3478                    }
3479                }
3480
3481                // Look for any generic query activities that are duplicates
3482                // of this specific one, and remove them from the results.
3483                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3484                N = results.size();
3485                int j;
3486                for (j=specificsPos; j<N; j++) {
3487                    ResolveInfo sri = results.get(j);
3488                    if ((sri.activityInfo.name.equals(comp.getClassName())
3489                            && sri.activityInfo.applicationInfo.packageName.equals(
3490                                    comp.getPackageName()))
3491                        || (action != null && sri.filter.matchAction(action))) {
3492                        results.remove(j);
3493                        if (DEBUG_INTENT_MATCHING) Log.v(
3494                            TAG, "Removing duplicate item from " + j
3495                            + " due to specific " + specificsPos);
3496                        if (ri == null) {
3497                            ri = sri;
3498                        }
3499                        j--;
3500                        N--;
3501                    }
3502                }
3503
3504                // Add this specific item to its proper place.
3505                if (ri == null) {
3506                    ri = new ResolveInfo();
3507                    ri.activityInfo = ai;
3508                }
3509                results.add(specificsPos, ri);
3510                ri.specificIndex = i;
3511                specificsPos++;
3512            }
3513        }
3514
3515        // Now we go through the remaining generic results and remove any
3516        // duplicate actions that are found here.
3517        N = results.size();
3518        for (int i=specificsPos; i<N-1; i++) {
3519            final ResolveInfo rii = results.get(i);
3520            if (rii.filter == null) {
3521                continue;
3522            }
3523
3524            // Iterate over all of the actions of this result's intent
3525            // filter...  typically this should be just one.
3526            final Iterator<String> it = rii.filter.actionsIterator();
3527            if (it == null) {
3528                continue;
3529            }
3530            while (it.hasNext()) {
3531                final String action = it.next();
3532                if (resultsAction != null && resultsAction.equals(action)) {
3533                    // If this action was explicitly requested, then don't
3534                    // remove things that have it.
3535                    continue;
3536                }
3537                for (int j=i+1; j<N; j++) {
3538                    final ResolveInfo rij = results.get(j);
3539                    if (rij.filter != null && rij.filter.hasAction(action)) {
3540                        results.remove(j);
3541                        if (DEBUG_INTENT_MATCHING) Log.v(
3542                            TAG, "Removing duplicate item from " + j
3543                            + " due to action " + action + " at " + i);
3544                        j--;
3545                        N--;
3546                    }
3547                }
3548            }
3549
3550            // If the caller didn't request filter information, drop it now
3551            // so we don't have to marshall/unmarshall it.
3552            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3553                rii.filter = null;
3554            }
3555        }
3556
3557        // Filter out the caller activity if so requested.
3558        if (caller != null) {
3559            N = results.size();
3560            for (int i=0; i<N; i++) {
3561                ActivityInfo ainfo = results.get(i).activityInfo;
3562                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3563                        && caller.getClassName().equals(ainfo.name)) {
3564                    results.remove(i);
3565                    break;
3566                }
3567            }
3568        }
3569
3570        // If the caller didn't request filter information,
3571        // drop them now so we don't have to
3572        // marshall/unmarshall it.
3573        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3574            N = results.size();
3575            for (int i=0; i<N; i++) {
3576                results.get(i).filter = null;
3577            }
3578        }
3579
3580        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3581        return results;
3582    }
3583
3584    @Override
3585    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3586            int userId) {
3587        if (!sUserManager.exists(userId)) return Collections.emptyList();
3588        ComponentName comp = intent.getComponent();
3589        if (comp == null) {
3590            if (intent.getSelector() != null) {
3591                intent = intent.getSelector();
3592                comp = intent.getComponent();
3593            }
3594        }
3595        if (comp != null) {
3596            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3597            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3598            if (ai != null) {
3599                ResolveInfo ri = new ResolveInfo();
3600                ri.activityInfo = ai;
3601                list.add(ri);
3602            }
3603            return list;
3604        }
3605
3606        // reader
3607        synchronized (mPackages) {
3608            String pkgName = intent.getPackage();
3609            if (pkgName == null) {
3610                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3611            }
3612            final PackageParser.Package pkg = mPackages.get(pkgName);
3613            if (pkg != null) {
3614                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3615                        userId);
3616            }
3617            return null;
3618        }
3619    }
3620
3621    @Override
3622    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3623        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3624        if (!sUserManager.exists(userId)) return null;
3625        if (query != null) {
3626            if (query.size() >= 1) {
3627                // If there is more than one service with the same priority,
3628                // just arbitrarily pick the first one.
3629                return query.get(0);
3630            }
3631        }
3632        return null;
3633    }
3634
3635    @Override
3636    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3637            int userId) {
3638        if (!sUserManager.exists(userId)) return Collections.emptyList();
3639        ComponentName comp = intent.getComponent();
3640        if (comp == null) {
3641            if (intent.getSelector() != null) {
3642                intent = intent.getSelector();
3643                comp = intent.getComponent();
3644            }
3645        }
3646        if (comp != null) {
3647            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3648            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3649            if (si != null) {
3650                final ResolveInfo ri = new ResolveInfo();
3651                ri.serviceInfo = si;
3652                list.add(ri);
3653            }
3654            return list;
3655        }
3656
3657        // reader
3658        synchronized (mPackages) {
3659            String pkgName = intent.getPackage();
3660            if (pkgName == null) {
3661                return mServices.queryIntent(intent, resolvedType, flags, userId);
3662            }
3663            final PackageParser.Package pkg = mPackages.get(pkgName);
3664            if (pkg != null) {
3665                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3666                        userId);
3667            }
3668            return null;
3669        }
3670    }
3671
3672    @Override
3673    public List<ResolveInfo> queryIntentContentProviders(
3674            Intent intent, String resolvedType, int flags, int userId) {
3675        if (!sUserManager.exists(userId)) return Collections.emptyList();
3676        ComponentName comp = intent.getComponent();
3677        if (comp == null) {
3678            if (intent.getSelector() != null) {
3679                intent = intent.getSelector();
3680                comp = intent.getComponent();
3681            }
3682        }
3683        if (comp != null) {
3684            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3685            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3686            if (pi != null) {
3687                final ResolveInfo ri = new ResolveInfo();
3688                ri.providerInfo = pi;
3689                list.add(ri);
3690            }
3691            return list;
3692        }
3693
3694        // reader
3695        synchronized (mPackages) {
3696            String pkgName = intent.getPackage();
3697            if (pkgName == null) {
3698                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3699            }
3700            final PackageParser.Package pkg = mPackages.get(pkgName);
3701            if (pkg != null) {
3702                return mProviders.queryIntentForPackage(
3703                        intent, resolvedType, flags, pkg.providers, userId);
3704            }
3705            return null;
3706        }
3707    }
3708
3709    @Override
3710    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3711        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3712
3713        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3714
3715        // writer
3716        synchronized (mPackages) {
3717            ArrayList<PackageInfo> list;
3718            if (listUninstalled) {
3719                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3720                for (PackageSetting ps : mSettings.mPackages.values()) {
3721                    PackageInfo pi;
3722                    if (ps.pkg != null) {
3723                        pi = generatePackageInfo(ps.pkg, flags, userId);
3724                    } else {
3725                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3726                    }
3727                    if (pi != null) {
3728                        list.add(pi);
3729                    }
3730                }
3731            } else {
3732                list = new ArrayList<PackageInfo>(mPackages.size());
3733                for (PackageParser.Package p : mPackages.values()) {
3734                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3735                    if (pi != null) {
3736                        list.add(pi);
3737                    }
3738                }
3739            }
3740
3741            return new ParceledListSlice<PackageInfo>(list);
3742        }
3743    }
3744
3745    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3746            String[] permissions, boolean[] tmp, int flags, int userId) {
3747        int numMatch = 0;
3748        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3749        for (int i=0; i<permissions.length; i++) {
3750            if (gp.grantedPermissions.contains(permissions[i])) {
3751                tmp[i] = true;
3752                numMatch++;
3753            } else {
3754                tmp[i] = false;
3755            }
3756        }
3757        if (numMatch == 0) {
3758            return;
3759        }
3760        PackageInfo pi;
3761        if (ps.pkg != null) {
3762            pi = generatePackageInfo(ps.pkg, flags, userId);
3763        } else {
3764            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3765        }
3766        // The above might return null in cases of uninstalled apps or install-state
3767        // skew across users/profiles.
3768        if (pi != null) {
3769            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3770                if (numMatch == permissions.length) {
3771                    pi.requestedPermissions = permissions;
3772                } else {
3773                    pi.requestedPermissions = new String[numMatch];
3774                    numMatch = 0;
3775                    for (int i=0; i<permissions.length; i++) {
3776                        if (tmp[i]) {
3777                            pi.requestedPermissions[numMatch] = permissions[i];
3778                            numMatch++;
3779                        }
3780                    }
3781                }
3782            }
3783            list.add(pi);
3784        }
3785    }
3786
3787    @Override
3788    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3789            String[] permissions, int flags, int userId) {
3790        if (!sUserManager.exists(userId)) return null;
3791        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3792
3793        // writer
3794        synchronized (mPackages) {
3795            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3796            boolean[] tmpBools = new boolean[permissions.length];
3797            if (listUninstalled) {
3798                for (PackageSetting ps : mSettings.mPackages.values()) {
3799                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3800                }
3801            } else {
3802                for (PackageParser.Package pkg : mPackages.values()) {
3803                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3804                    if (ps != null) {
3805                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3806                                userId);
3807                    }
3808                }
3809            }
3810
3811            return new ParceledListSlice<PackageInfo>(list);
3812        }
3813    }
3814
3815    @Override
3816    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3817        if (!sUserManager.exists(userId)) return null;
3818        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3819
3820        // writer
3821        synchronized (mPackages) {
3822            ArrayList<ApplicationInfo> list;
3823            if (listUninstalled) {
3824                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3825                for (PackageSetting ps : mSettings.mPackages.values()) {
3826                    ApplicationInfo ai;
3827                    if (ps.pkg != null) {
3828                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3829                                ps.readUserState(userId), userId);
3830                    } else {
3831                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3832                    }
3833                    if (ai != null) {
3834                        list.add(ai);
3835                    }
3836                }
3837            } else {
3838                list = new ArrayList<ApplicationInfo>(mPackages.size());
3839                for (PackageParser.Package p : mPackages.values()) {
3840                    if (p.mExtras != null) {
3841                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3842                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3843                        if (ai != null) {
3844                            list.add(ai);
3845                        }
3846                    }
3847                }
3848            }
3849
3850            return new ParceledListSlice<ApplicationInfo>(list);
3851        }
3852    }
3853
3854    public List<ApplicationInfo> getPersistentApplications(int flags) {
3855        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3856
3857        // reader
3858        synchronized (mPackages) {
3859            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3860            final int userId = UserHandle.getCallingUserId();
3861            while (i.hasNext()) {
3862                final PackageParser.Package p = i.next();
3863                if (p.applicationInfo != null
3864                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3865                        && (!mSafeMode || isSystemApp(p))) {
3866                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3867                    if (ps != null) {
3868                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3869                                ps.readUserState(userId), userId);
3870                        if (ai != null) {
3871                            finalList.add(ai);
3872                        }
3873                    }
3874                }
3875            }
3876        }
3877
3878        return finalList;
3879    }
3880
3881    @Override
3882    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3883        if (!sUserManager.exists(userId)) return null;
3884        // reader
3885        synchronized (mPackages) {
3886            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3887            PackageSetting ps = provider != null
3888                    ? mSettings.mPackages.get(provider.owner.packageName)
3889                    : null;
3890            return ps != null
3891                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3892                    && (!mSafeMode || (provider.info.applicationInfo.flags
3893                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3894                    ? PackageParser.generateProviderInfo(provider, flags,
3895                            ps.readUserState(userId), userId)
3896                    : null;
3897        }
3898    }
3899
3900    /**
3901     * @deprecated
3902     */
3903    @Deprecated
3904    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3905        // reader
3906        synchronized (mPackages) {
3907            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3908                    .entrySet().iterator();
3909            final int userId = UserHandle.getCallingUserId();
3910            while (i.hasNext()) {
3911                Map.Entry<String, PackageParser.Provider> entry = i.next();
3912                PackageParser.Provider p = entry.getValue();
3913                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3914
3915                if (ps != null && p.syncable
3916                        && (!mSafeMode || (p.info.applicationInfo.flags
3917                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3918                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3919                            ps.readUserState(userId), userId);
3920                    if (info != null) {
3921                        outNames.add(entry.getKey());
3922                        outInfo.add(info);
3923                    }
3924                }
3925            }
3926        }
3927    }
3928
3929    @Override
3930    public List<ProviderInfo> queryContentProviders(String processName,
3931            int uid, int flags) {
3932        ArrayList<ProviderInfo> finalList = null;
3933        // reader
3934        synchronized (mPackages) {
3935            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3936            final int userId = processName != null ?
3937                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3938            while (i.hasNext()) {
3939                final PackageParser.Provider p = i.next();
3940                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3941                if (ps != null && p.info.authority != null
3942                        && (processName == null
3943                                || (p.info.processName.equals(processName)
3944                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3945                        && mSettings.isEnabledLPr(p.info, flags, userId)
3946                        && (!mSafeMode
3947                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3948                    if (finalList == null) {
3949                        finalList = new ArrayList<ProviderInfo>(3);
3950                    }
3951                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3952                            ps.readUserState(userId), userId);
3953                    if (info != null) {
3954                        finalList.add(info);
3955                    }
3956                }
3957            }
3958        }
3959
3960        if (finalList != null) {
3961            Collections.sort(finalList, mProviderInitOrderSorter);
3962        }
3963
3964        return finalList;
3965    }
3966
3967    @Override
3968    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3969            int flags) {
3970        // reader
3971        synchronized (mPackages) {
3972            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3973            return PackageParser.generateInstrumentationInfo(i, flags);
3974        }
3975    }
3976
3977    @Override
3978    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3979            int flags) {
3980        ArrayList<InstrumentationInfo> finalList =
3981            new ArrayList<InstrumentationInfo>();
3982
3983        // reader
3984        synchronized (mPackages) {
3985            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3986            while (i.hasNext()) {
3987                final PackageParser.Instrumentation p = i.next();
3988                if (targetPackage == null
3989                        || targetPackage.equals(p.info.targetPackage)) {
3990                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3991                            flags);
3992                    if (ii != null) {
3993                        finalList.add(ii);
3994                    }
3995                }
3996            }
3997        }
3998
3999        return finalList;
4000    }
4001
4002    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4003        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4004        if (overlays == null) {
4005            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4006            return;
4007        }
4008        for (PackageParser.Package opkg : overlays.values()) {
4009            // Not much to do if idmap fails: we already logged the error
4010            // and we certainly don't want to abort installation of pkg simply
4011            // because an overlay didn't fit properly. For these reasons,
4012            // ignore the return value of createIdmapForPackagePairLI.
4013            createIdmapForPackagePairLI(pkg, opkg);
4014        }
4015    }
4016
4017    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4018            PackageParser.Package opkg) {
4019        if (!opkg.mTrustedOverlay) {
4020            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4021                    opkg.baseCodePath + ": overlay not trusted");
4022            return false;
4023        }
4024        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4025        if (overlaySet == null) {
4026            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4027                    opkg.baseCodePath + " but target package has no known overlays");
4028            return false;
4029        }
4030        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4031        // TODO: generate idmap for split APKs
4032        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4033            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4034                    + opkg.baseCodePath);
4035            return false;
4036        }
4037        PackageParser.Package[] overlayArray =
4038            overlaySet.values().toArray(new PackageParser.Package[0]);
4039        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4040            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4041                return p1.mOverlayPriority - p2.mOverlayPriority;
4042            }
4043        };
4044        Arrays.sort(overlayArray, cmp);
4045
4046        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4047        int i = 0;
4048        for (PackageParser.Package p : overlayArray) {
4049            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4050        }
4051        return true;
4052    }
4053
4054    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4055        final File[] files = dir.listFiles();
4056        if (ArrayUtils.isEmpty(files)) {
4057            Log.d(TAG, "No files in app dir " + dir);
4058            return;
4059        }
4060
4061        if (DEBUG_PACKAGE_SCANNING) {
4062            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4063                    + " flags=0x" + Integer.toHexString(parseFlags));
4064        }
4065
4066        for (File file : files) {
4067            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4068                    && !PackageInstallerService.isStageName(file.getName());
4069            if (!isPackage) {
4070                // Ignore entries which are not packages
4071                continue;
4072            }
4073            try {
4074                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4075                        scanFlags, currentTime, null);
4076            } catch (PackageManagerException e) {
4077                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4078
4079                // Delete invalid userdata apps
4080                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4081                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4082                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4083                    if (file.isDirectory()) {
4084                        FileUtils.deleteContents(file);
4085                    }
4086                    file.delete();
4087                }
4088            }
4089        }
4090    }
4091
4092    private static File getSettingsProblemFile() {
4093        File dataDir = Environment.getDataDirectory();
4094        File systemDir = new File(dataDir, "system");
4095        File fname = new File(systemDir, "uiderrors.txt");
4096        return fname;
4097    }
4098
4099    static void reportSettingsProblem(int priority, String msg) {
4100        logCriticalInfo(priority, msg);
4101    }
4102
4103    static void logCriticalInfo(int priority, String msg) {
4104        Slog.println(priority, TAG, msg);
4105        EventLogTags.writePmCriticalInfo(msg);
4106        try {
4107            File fname = getSettingsProblemFile();
4108            FileOutputStream out = new FileOutputStream(fname, true);
4109            PrintWriter pw = new FastPrintWriter(out);
4110            SimpleDateFormat formatter = new SimpleDateFormat();
4111            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4112            pw.println(dateString + ": " + msg);
4113            pw.close();
4114            FileUtils.setPermissions(
4115                    fname.toString(),
4116                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4117                    -1, -1);
4118        } catch (java.io.IOException e) {
4119        }
4120    }
4121
4122    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4123            PackageParser.Package pkg, File srcFile, int parseFlags)
4124            throws PackageManagerException {
4125        if (ps != null
4126                && ps.codePath.equals(srcFile)
4127                && ps.timeStamp == srcFile.lastModified()
4128                && !isCompatSignatureUpdateNeeded(pkg)) {
4129            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4130            if (ps.signatures.mSignatures != null
4131                    && ps.signatures.mSignatures.length != 0
4132                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4133                // Optimization: reuse the existing cached certificates
4134                // if the package appears to be unchanged.
4135                pkg.mSignatures = ps.signatures.mSignatures;
4136                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4137                synchronized (mPackages) {
4138                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4139                }
4140                return;
4141            }
4142
4143            Slog.w(TAG, "PackageSetting for " + ps.name
4144                    + " is missing signatures.  Collecting certs again to recover them.");
4145        } else {
4146            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4147        }
4148
4149        try {
4150            pp.collectCertificates(pkg, parseFlags);
4151            pp.collectManifestDigest(pkg);
4152        } catch (PackageParserException e) {
4153            throw PackageManagerException.from(e);
4154        }
4155    }
4156
4157    /*
4158     *  Scan a package and return the newly parsed package.
4159     *  Returns null in case of errors and the error code is stored in mLastScanError
4160     */
4161    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4162            long currentTime, UserHandle user) throws PackageManagerException {
4163        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4164        parseFlags |= mDefParseFlags;
4165        PackageParser pp = new PackageParser();
4166        pp.setSeparateProcesses(mSeparateProcesses);
4167        pp.setOnlyCoreApps(mOnlyCore);
4168        pp.setDisplayMetrics(mMetrics);
4169
4170        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4171            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4172        }
4173
4174        final PackageParser.Package pkg;
4175        try {
4176            pkg = pp.parsePackage(scanFile, parseFlags);
4177        } catch (PackageParserException e) {
4178            throw PackageManagerException.from(e);
4179        }
4180
4181        PackageSetting ps = null;
4182        PackageSetting updatedPkg;
4183        // reader
4184        synchronized (mPackages) {
4185            // Look to see if we already know about this package.
4186            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4187            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4188                // This package has been renamed to its original name.  Let's
4189                // use that.
4190                ps = mSettings.peekPackageLPr(oldName);
4191            }
4192            // If there was no original package, see one for the real package name.
4193            if (ps == null) {
4194                ps = mSettings.peekPackageLPr(pkg.packageName);
4195            }
4196            // Check to see if this package could be hiding/updating a system
4197            // package.  Must look for it either under the original or real
4198            // package name depending on our state.
4199            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4200            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4201        }
4202        boolean updatedPkgBetter = false;
4203        // First check if this is a system package that may involve an update
4204        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4205            if (ps != null && !ps.codePath.equals(scanFile)) {
4206                // The path has changed from what was last scanned...  check the
4207                // version of the new path against what we have stored to determine
4208                // what to do.
4209                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4210                if (pkg.mVersionCode < ps.versionCode) {
4211                    // The system package has been updated and the code path does not match
4212                    // Ignore entry. Skip it.
4213                    logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
4214                            + " ignored: updated version " + ps.versionCode
4215                            + " better than this " + pkg.mVersionCode);
4216                    if (!updatedPkg.codePath.equals(scanFile)) {
4217                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4218                                + ps.name + " changing from " + updatedPkg.codePathString
4219                                + " to " + scanFile);
4220                        updatedPkg.codePath = scanFile;
4221                        updatedPkg.codePathString = scanFile.toString();
4222                        // This is the point at which we know that the system-disk APK
4223                        // for this package has moved during a reboot (e.g. due to an OTA),
4224                        // so we need to reevaluate it for privilege policy.
4225                        if (locationIsPrivileged(scanFile)) {
4226                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4227                        }
4228                    }
4229                    updatedPkg.pkg = pkg;
4230                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4231                } else {
4232                    // The current app on the system partition is better than
4233                    // what we have updated to on the data partition; switch
4234                    // back to the system partition version.
4235                    // At this point, its safely assumed that package installation for
4236                    // apps in system partition will go through. If not there won't be a working
4237                    // version of the app
4238                    // writer
4239                    synchronized (mPackages) {
4240                        // Just remove the loaded entries from package lists.
4241                        mPackages.remove(ps.name);
4242                    }
4243
4244                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4245                            + " reverting from " + ps.codePathString
4246                            + ": new version " + pkg.mVersionCode
4247                            + " better than installed " + ps.versionCode);
4248
4249                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4250                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4251                            getAppDexInstructionSets(ps));
4252                    synchronized (mInstallLock) {
4253                        args.cleanUpResourcesLI();
4254                    }
4255                    synchronized (mPackages) {
4256                        mSettings.enableSystemPackageLPw(ps.name);
4257                    }
4258                    updatedPkgBetter = true;
4259                }
4260            }
4261        }
4262
4263        if (updatedPkg != null) {
4264            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4265            // initially
4266            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4267
4268            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4269            // flag set initially
4270            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4271                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4272            }
4273        }
4274
4275        // Verify certificates against what was last scanned
4276        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4277
4278        /*
4279         * A new system app appeared, but we already had a non-system one of the
4280         * same name installed earlier.
4281         */
4282        boolean shouldHideSystemApp = false;
4283        if (updatedPkg == null && ps != null
4284                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4285            /*
4286             * Check to make sure the signatures match first. If they don't,
4287             * wipe the installed application and its data.
4288             */
4289            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4290                    != PackageManager.SIGNATURE_MATCH) {
4291                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4292                        + " signatures don't match existing userdata copy; removing");
4293                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4294                ps = null;
4295            } else {
4296                /*
4297                 * If the newly-added system app is an older version than the
4298                 * already installed version, hide it. It will be scanned later
4299                 * and re-added like an update.
4300                 */
4301                if (pkg.mVersionCode < ps.versionCode) {
4302                    shouldHideSystemApp = true;
4303                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4304                            + " but new version " + pkg.mVersionCode + " better than installed "
4305                            + ps.versionCode + "; hiding system");
4306                } else {
4307                    /*
4308                     * The newly found system app is a newer version that the
4309                     * one previously installed. Simply remove the
4310                     * already-installed application and replace it with our own
4311                     * while keeping the application data.
4312                     */
4313                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4314                            + " reverting from " + ps.codePathString + ": new version "
4315                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4316                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4317                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4318                            getAppDexInstructionSets(ps));
4319                    synchronized (mInstallLock) {
4320                        args.cleanUpResourcesLI();
4321                    }
4322                }
4323            }
4324        }
4325
4326        // The apk is forward locked (not public) if its code and resources
4327        // are kept in different files. (except for app in either system or
4328        // vendor path).
4329        // TODO grab this value from PackageSettings
4330        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4331            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4332                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4333            }
4334        }
4335
4336        // TODO: extend to support forward-locked splits
4337        String resourcePath = null;
4338        String baseResourcePath = null;
4339        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4340            if (ps != null && ps.resourcePathString != null) {
4341                resourcePath = ps.resourcePathString;
4342                baseResourcePath = ps.resourcePathString;
4343            } else {
4344                // Should not happen at all. Just log an error.
4345                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4346            }
4347        } else {
4348            resourcePath = pkg.codePath;
4349            baseResourcePath = pkg.baseCodePath;
4350        }
4351
4352        // Set application objects path explicitly.
4353        pkg.applicationInfo.setCodePath(pkg.codePath);
4354        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4355        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4356        pkg.applicationInfo.setResourcePath(resourcePath);
4357        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4358        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4359
4360        // Note that we invoke the following method only if we are about to unpack an application
4361        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4362                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4363
4364        /*
4365         * If the system app should be overridden by a previously installed
4366         * data, hide the system app now and let the /data/app scan pick it up
4367         * again.
4368         */
4369        if (shouldHideSystemApp) {
4370            synchronized (mPackages) {
4371                /*
4372                 * We have to grant systems permissions before we hide, because
4373                 * grantPermissions will assume the package update is trying to
4374                 * expand its permissions.
4375                 */
4376                grantPermissionsLPw(pkg, true, pkg.packageName);
4377                mSettings.disableSystemPackageLPw(pkg.packageName);
4378            }
4379        }
4380
4381        return scannedPkg;
4382    }
4383
4384    private static String fixProcessName(String defProcessName,
4385            String processName, int uid) {
4386        if (processName == null) {
4387            return defProcessName;
4388        }
4389        return processName;
4390    }
4391
4392    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4393            throws PackageManagerException {
4394        if (pkgSetting.signatures.mSignatures != null) {
4395            // Already existing package. Make sure signatures match
4396            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4397                    == PackageManager.SIGNATURE_MATCH;
4398            if (!match) {
4399                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4400                        == PackageManager.SIGNATURE_MATCH;
4401            }
4402            if (!match) {
4403                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4404                        + pkg.packageName + " signatures do not match the "
4405                        + "previously installed version; ignoring!");
4406            }
4407        }
4408
4409        // Check for shared user signatures
4410        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4411            // Already existing package. Make sure signatures match
4412            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4413                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4414            if (!match) {
4415                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4416                        == PackageManager.SIGNATURE_MATCH;
4417            }
4418            if (!match) {
4419                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4420                        "Package " + pkg.packageName
4421                        + " has no signatures that match those in shared user "
4422                        + pkgSetting.sharedUser.name + "; ignoring!");
4423            }
4424        }
4425    }
4426
4427    /**
4428     * Enforces that only the system UID or root's UID can call a method exposed
4429     * via Binder.
4430     *
4431     * @param message used as message if SecurityException is thrown
4432     * @throws SecurityException if the caller is not system or root
4433     */
4434    private static final void enforceSystemOrRoot(String message) {
4435        final int uid = Binder.getCallingUid();
4436        if (uid != Process.SYSTEM_UID && uid != 0) {
4437            throw new SecurityException(message);
4438        }
4439    }
4440
4441    @Override
4442    public void performBootDexOpt() {
4443        enforceSystemOrRoot("Only the system can request dexopt be performed");
4444
4445        final HashSet<PackageParser.Package> pkgs;
4446        synchronized (mPackages) {
4447            pkgs = mDeferredDexOpt;
4448            mDeferredDexOpt = null;
4449        }
4450
4451        if (pkgs != null) {
4452            // Filter out packages that aren't recently used.
4453            //
4454            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4455            // should do a full dexopt.
4456            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4457                // TODO: add a property to control this?
4458                long dexOptLRUThresholdInMinutes;
4459                if (mLazyDexOpt) {
4460                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4461                } else {
4462                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4463                }
4464                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4465
4466                int total = pkgs.size();
4467                int skipped = 0;
4468                long now = System.currentTimeMillis();
4469                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4470                    PackageParser.Package pkg = i.next();
4471                    long then = pkg.mLastPackageUsageTimeInMills;
4472                    if (then + dexOptLRUThresholdInMills < now) {
4473                        if (DEBUG_DEXOPT) {
4474                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4475                                  ((then == 0) ? "never" : new Date(then)));
4476                        }
4477                        i.remove();
4478                        skipped++;
4479                    }
4480                }
4481                if (DEBUG_DEXOPT) {
4482                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4483                }
4484            }
4485
4486            int i = 0;
4487            for (PackageParser.Package pkg : pkgs) {
4488                i++;
4489                if (DEBUG_DEXOPT) {
4490                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4491                          + ": " + pkg.packageName);
4492                }
4493                if (!isFirstBoot()) {
4494                    try {
4495                        ActivityManagerNative.getDefault().showBootMessage(
4496                                mContext.getResources().getString(
4497                                        R.string.android_upgrading_apk,
4498                                        i, pkgs.size()), true);
4499                    } catch (RemoteException e) {
4500                    }
4501                }
4502                PackageParser.Package p = pkg;
4503                synchronized (mInstallLock) {
4504                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4505                            true /* include dependencies */);
4506                }
4507            }
4508        }
4509    }
4510
4511    @Override
4512    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4513        return performDexOpt(packageName, instructionSet, false);
4514    }
4515
4516    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4517        if (info.primaryCpuAbi == null) {
4518            return getPreferredInstructionSet();
4519        }
4520
4521        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4522    }
4523
4524    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4525        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4526        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4527        if (!dexopt && !updateUsage) {
4528            // We aren't going to dexopt or update usage, so bail early.
4529            return false;
4530        }
4531        PackageParser.Package p;
4532        final String targetInstructionSet;
4533        synchronized (mPackages) {
4534            p = mPackages.get(packageName);
4535            if (p == null) {
4536                return false;
4537            }
4538            if (updateUsage) {
4539                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4540            }
4541            mPackageUsage.write(false);
4542            if (!dexopt) {
4543                // We aren't going to dexopt, so bail early.
4544                return false;
4545            }
4546
4547            targetInstructionSet = instructionSet != null ? instructionSet :
4548                    getPrimaryInstructionSet(p.applicationInfo);
4549            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4550                return false;
4551            }
4552        }
4553
4554        synchronized (mInstallLock) {
4555            final String[] instructionSets = new String[] { targetInstructionSet };
4556            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4557                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4558        }
4559    }
4560
4561    public HashSet<String> getPackagesThatNeedDexOpt() {
4562        HashSet<String> pkgs = null;
4563        synchronized (mPackages) {
4564            for (PackageParser.Package p : mPackages.values()) {
4565                if (DEBUG_DEXOPT) {
4566                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4567                }
4568                if (!p.mDexOptPerformed.isEmpty()) {
4569                    continue;
4570                }
4571                if (pkgs == null) {
4572                    pkgs = new HashSet<String>();
4573                }
4574                pkgs.add(p.packageName);
4575            }
4576        }
4577        return pkgs;
4578    }
4579
4580    public void shutdown() {
4581        mPackageUsage.write(true);
4582    }
4583
4584    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4585             boolean forceDex, boolean defer, HashSet<String> done) {
4586        for (int i=0; i<libs.size(); i++) {
4587            PackageParser.Package libPkg;
4588            String libName;
4589            synchronized (mPackages) {
4590                libName = libs.get(i);
4591                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4592                if (lib != null && lib.apk != null) {
4593                    libPkg = mPackages.get(lib.apk);
4594                } else {
4595                    libPkg = null;
4596                }
4597            }
4598            if (libPkg != null && !done.contains(libName)) {
4599                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4600            }
4601        }
4602    }
4603
4604    static final int DEX_OPT_SKIPPED = 0;
4605    static final int DEX_OPT_PERFORMED = 1;
4606    static final int DEX_OPT_DEFERRED = 2;
4607    static final int DEX_OPT_FAILED = -1;
4608
4609    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4610            boolean forceDex, boolean defer, HashSet<String> done) {
4611        final String[] instructionSets = targetInstructionSets != null ?
4612                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4613
4614        if (done != null) {
4615            done.add(pkg.packageName);
4616            if (pkg.usesLibraries != null) {
4617                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4618            }
4619            if (pkg.usesOptionalLibraries != null) {
4620                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4621            }
4622        }
4623
4624        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4625            return DEX_OPT_SKIPPED;
4626        }
4627
4628        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4629
4630        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4631        boolean performedDexOpt = false;
4632        // There are three basic cases here:
4633        // 1.) we need to dexopt, either because we are forced or it is needed
4634        // 2.) we are defering a needed dexopt
4635        // 3.) we are skipping an unneeded dexopt
4636        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4637        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4638            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4639                continue;
4640            }
4641
4642            for (String path : paths) {
4643                try {
4644                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4645                    // patckage or the one we find does not match the image checksum (i.e. it was
4646                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4647                    // odex file and it matches the checksum of the image but not its base address,
4648                    // meaning we need to move it.
4649                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4650                            pkg.packageName, dexCodeInstructionSet, defer);
4651                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4652                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4653                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4654                                + " vmSafeMode=" + vmSafeMode);
4655                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4656                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4657                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4658
4659                        if (ret < 0) {
4660                            // Don't bother running dexopt again if we failed, it will probably
4661                            // just result in an error again. Also, don't bother dexopting for other
4662                            // paths & ISAs.
4663                            return DEX_OPT_FAILED;
4664                        }
4665
4666                        performedDexOpt = true;
4667                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4668                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4669                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4670                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4671                                pkg.packageName, dexCodeInstructionSet);
4672
4673                        if (ret < 0) {
4674                            // Don't bother running patchoat again if we failed, it will probably
4675                            // just result in an error again. Also, don't bother dexopting for other
4676                            // paths & ISAs.
4677                            return DEX_OPT_FAILED;
4678                        }
4679
4680                        performedDexOpt = true;
4681                    }
4682
4683                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4684                    // paths and instruction sets. We'll deal with them all together when we process
4685                    // our list of deferred dexopts.
4686                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4687                        if (mDeferredDexOpt == null) {
4688                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4689                        }
4690                        mDeferredDexOpt.add(pkg);
4691                        return DEX_OPT_DEFERRED;
4692                    }
4693                } catch (FileNotFoundException e) {
4694                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4695                    return DEX_OPT_FAILED;
4696                } catch (IOException e) {
4697                    Slog.w(TAG, "IOException reading apk: " + path, e);
4698                    return DEX_OPT_FAILED;
4699                } catch (StaleDexCacheError e) {
4700                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4701                    return DEX_OPT_FAILED;
4702                } catch (Exception e) {
4703                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4704                    return DEX_OPT_FAILED;
4705                }
4706            }
4707
4708            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4709            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4710            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4711            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4712            // it.
4713            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4714        }
4715
4716        // If we've gotten here, we're sure that no error occurred and that we haven't
4717        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4718        // we've skipped all of them because they are up to date. In both cases this
4719        // package doesn't need dexopt any longer.
4720        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4721    }
4722
4723    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4724        if (info.primaryCpuAbi != null) {
4725            if (info.secondaryCpuAbi != null) {
4726                return new String[] {
4727                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4728                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4729            } else {
4730                return new String[] {
4731                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4732            }
4733        }
4734
4735        return new String[] { getPreferredInstructionSet() };
4736    }
4737
4738    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4739        if (ps.primaryCpuAbiString != null) {
4740            if (ps.secondaryCpuAbiString != null) {
4741                return new String[] {
4742                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4743                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4744            } else {
4745                return new String[] {
4746                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4747            }
4748        }
4749
4750        return new String[] { getPreferredInstructionSet() };
4751    }
4752
4753    private static String getPreferredInstructionSet() {
4754        if (sPreferredInstructionSet == null) {
4755            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4756        }
4757
4758        return sPreferredInstructionSet;
4759    }
4760
4761    private static List<String> getAllInstructionSets() {
4762        final String[] allAbis = Build.SUPPORTED_ABIS;
4763        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4764
4765        for (String abi : allAbis) {
4766            final String instructionSet = VMRuntime.getInstructionSet(abi);
4767            if (!allInstructionSets.contains(instructionSet)) {
4768                allInstructionSets.add(instructionSet);
4769            }
4770        }
4771
4772        return allInstructionSets;
4773    }
4774
4775    /**
4776     * Returns the instruction set that should be used to compile dex code. In the presence of
4777     * a native bridge this might be different than the one shared libraries use.
4778     */
4779    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4780        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4781        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4782    }
4783
4784    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4785        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4786        for (String instructionSet : instructionSets) {
4787            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4788        }
4789        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4790    }
4791
4792    /**
4793     * Returns deduplicated list of supported instructions for dex code.
4794     */
4795    public static String[] getAllDexCodeInstructionSets() {
4796        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4797        for (int i = 0; i < supportedInstructionSets.length; i++) {
4798            String abi = Build.SUPPORTED_ABIS[i];
4799            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4800        }
4801        return getDexCodeInstructionSets(supportedInstructionSets);
4802    }
4803
4804    @Override
4805    public void forceDexOpt(String packageName) {
4806        enforceSystemOrRoot("forceDexOpt");
4807
4808        PackageParser.Package pkg;
4809        synchronized (mPackages) {
4810            pkg = mPackages.get(packageName);
4811            if (pkg == null) {
4812                throw new IllegalArgumentException("Missing package: " + packageName);
4813            }
4814        }
4815
4816        synchronized (mInstallLock) {
4817            final String[] instructionSets = new String[] {
4818                    getPrimaryInstructionSet(pkg.applicationInfo) };
4819            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4820            if (res != DEX_OPT_PERFORMED) {
4821                throw new IllegalStateException("Failed to dexopt: " + res);
4822            }
4823        }
4824    }
4825
4826    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4827                                boolean forceDex, boolean defer, boolean inclDependencies) {
4828        HashSet<String> done;
4829        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4830            done = new HashSet<String>();
4831            done.add(pkg.packageName);
4832        } else {
4833            done = null;
4834        }
4835        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4836    }
4837
4838    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4839        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4840            Slog.w(TAG, "Unable to update from " + oldPkg.name
4841                    + " to " + newPkg.packageName
4842                    + ": old package not in system partition");
4843            return false;
4844        } else if (mPackages.get(oldPkg.name) != null) {
4845            Slog.w(TAG, "Unable to update from " + oldPkg.name
4846                    + " to " + newPkg.packageName
4847                    + ": old package still exists");
4848            return false;
4849        }
4850        return true;
4851    }
4852
4853    File getDataPathForUser(int userId) {
4854        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4855    }
4856
4857    private File getDataPathForPackage(String packageName, int userId) {
4858        /*
4859         * Until we fully support multiple users, return the directory we
4860         * previously would have. The PackageManagerTests will need to be
4861         * revised when this is changed back..
4862         */
4863        if (userId == 0) {
4864            return new File(mAppDataDir, packageName);
4865        } else {
4866            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4867                + File.separator + packageName);
4868        }
4869    }
4870
4871    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4872        int[] users = sUserManager.getUserIds();
4873        int res = mInstaller.install(packageName, uid, uid, seinfo);
4874        if (res < 0) {
4875            return res;
4876        }
4877        for (int user : users) {
4878            if (user != 0) {
4879                res = mInstaller.createUserData(packageName,
4880                        UserHandle.getUid(user, uid), user, seinfo);
4881                if (res < 0) {
4882                    return res;
4883                }
4884            }
4885        }
4886        return res;
4887    }
4888
4889    private int removeDataDirsLI(String packageName) {
4890        int[] users = sUserManager.getUserIds();
4891        int res = 0;
4892        for (int user : users) {
4893            int resInner = mInstaller.remove(packageName, user);
4894            if (resInner < 0) {
4895                res = resInner;
4896            }
4897        }
4898
4899        return res;
4900    }
4901
4902    private int deleteCodeCacheDirsLI(String packageName) {
4903        int[] users = sUserManager.getUserIds();
4904        int res = 0;
4905        for (int user : users) {
4906            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4907            if (resInner < 0) {
4908                res = resInner;
4909            }
4910        }
4911        return res;
4912    }
4913
4914    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4915            PackageParser.Package changingLib) {
4916        if (file.path != null) {
4917            usesLibraryFiles.add(file.path);
4918            return;
4919        }
4920        PackageParser.Package p = mPackages.get(file.apk);
4921        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4922            // If we are doing this while in the middle of updating a library apk,
4923            // then we need to make sure to use that new apk for determining the
4924            // dependencies here.  (We haven't yet finished committing the new apk
4925            // to the package manager state.)
4926            if (p == null || p.packageName.equals(changingLib.packageName)) {
4927                p = changingLib;
4928            }
4929        }
4930        if (p != null) {
4931            usesLibraryFiles.addAll(p.getAllCodePaths());
4932        }
4933    }
4934
4935    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4936            PackageParser.Package changingLib) throws PackageManagerException {
4937        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4938            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4939            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4940            for (int i=0; i<N; i++) {
4941                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4942                if (file == null) {
4943                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4944                            "Package " + pkg.packageName + " requires unavailable shared library "
4945                            + pkg.usesLibraries.get(i) + "; failing!");
4946                }
4947                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4948            }
4949            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4950            for (int i=0; i<N; i++) {
4951                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4952                if (file == null) {
4953                    Slog.w(TAG, "Package " + pkg.packageName
4954                            + " desires unavailable shared library "
4955                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4956                } else {
4957                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4958                }
4959            }
4960            N = usesLibraryFiles.size();
4961            if (N > 0) {
4962                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4963            } else {
4964                pkg.usesLibraryFiles = null;
4965            }
4966        }
4967    }
4968
4969    private static boolean hasString(List<String> list, List<String> which) {
4970        if (list == null) {
4971            return false;
4972        }
4973        for (int i=list.size()-1; i>=0; i--) {
4974            for (int j=which.size()-1; j>=0; j--) {
4975                if (which.get(j).equals(list.get(i))) {
4976                    return true;
4977                }
4978            }
4979        }
4980        return false;
4981    }
4982
4983    private void updateAllSharedLibrariesLPw() {
4984        for (PackageParser.Package pkg : mPackages.values()) {
4985            try {
4986                updateSharedLibrariesLPw(pkg, null);
4987            } catch (PackageManagerException e) {
4988                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4989            }
4990        }
4991    }
4992
4993    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4994            PackageParser.Package changingPkg) {
4995        ArrayList<PackageParser.Package> res = null;
4996        for (PackageParser.Package pkg : mPackages.values()) {
4997            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4998                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4999                if (res == null) {
5000                    res = new ArrayList<PackageParser.Package>();
5001                }
5002                res.add(pkg);
5003                try {
5004                    updateSharedLibrariesLPw(pkg, changingPkg);
5005                } catch (PackageManagerException e) {
5006                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5007                }
5008            }
5009        }
5010        return res;
5011    }
5012
5013    /**
5014     * Derive the value of the {@code cpuAbiOverride} based on the provided
5015     * value and an optional stored value from the package settings.
5016     */
5017    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5018        String cpuAbiOverride = null;
5019
5020        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5021            cpuAbiOverride = null;
5022        } else if (abiOverride != null) {
5023            cpuAbiOverride = abiOverride;
5024        } else if (settings != null) {
5025            cpuAbiOverride = settings.cpuAbiOverrideString;
5026        }
5027
5028        return cpuAbiOverride;
5029    }
5030
5031    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5032            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5033        boolean success = false;
5034        try {
5035            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5036                    currentTime, user);
5037            success = true;
5038            return res;
5039        } finally {
5040            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5041                removeDataDirsLI(pkg.packageName);
5042            }
5043        }
5044    }
5045
5046    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5047            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5048        final File scanFile = new File(pkg.codePath);
5049        if (pkg.applicationInfo.getCodePath() == null ||
5050                pkg.applicationInfo.getResourcePath() == null) {
5051            // Bail out. The resource and code paths haven't been set.
5052            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5053                    "Code and resource paths haven't been set correctly");
5054        }
5055
5056        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5057            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5058        }
5059
5060        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5061            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5062        }
5063
5064        if (mCustomResolverComponentName != null &&
5065                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5066            setUpCustomResolverActivity(pkg);
5067        }
5068
5069        if (pkg.packageName.equals("android")) {
5070            synchronized (mPackages) {
5071                if (mAndroidApplication != null) {
5072                    Slog.w(TAG, "*************************************************");
5073                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5074                    Slog.w(TAG, " file=" + scanFile);
5075                    Slog.w(TAG, "*************************************************");
5076                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5077                            "Core android package being redefined.  Skipping.");
5078                }
5079
5080                // Set up information for our fall-back user intent resolution activity.
5081                mPlatformPackage = pkg;
5082                pkg.mVersionCode = mSdkVersion;
5083                mAndroidApplication = pkg.applicationInfo;
5084
5085                if (!mResolverReplaced) {
5086                    mResolveActivity.applicationInfo = mAndroidApplication;
5087                    mResolveActivity.name = ResolverActivity.class.getName();
5088                    mResolveActivity.packageName = mAndroidApplication.packageName;
5089                    mResolveActivity.processName = "system:ui";
5090                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5091                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5092                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5093                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5094                    mResolveActivity.exported = true;
5095                    mResolveActivity.enabled = true;
5096                    mResolveInfo.activityInfo = mResolveActivity;
5097                    mResolveInfo.priority = 0;
5098                    mResolveInfo.preferredOrder = 0;
5099                    mResolveInfo.match = 0;
5100                    mResolveComponentName = new ComponentName(
5101                            mAndroidApplication.packageName, mResolveActivity.name);
5102                }
5103            }
5104        }
5105
5106        if (DEBUG_PACKAGE_SCANNING) {
5107            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5108                Log.d(TAG, "Scanning package " + pkg.packageName);
5109        }
5110
5111        if (mPackages.containsKey(pkg.packageName)
5112                || mSharedLibraries.containsKey(pkg.packageName)) {
5113            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5114                    "Application package " + pkg.packageName
5115                    + " already installed.  Skipping duplicate.");
5116        }
5117
5118        // Initialize package source and resource directories
5119        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5120        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5121
5122        SharedUserSetting suid = null;
5123        PackageSetting pkgSetting = null;
5124
5125        if (!isSystemApp(pkg)) {
5126            // Only system apps can use these features.
5127            pkg.mOriginalPackages = null;
5128            pkg.mRealPackage = null;
5129            pkg.mAdoptPermissions = null;
5130        }
5131
5132        // writer
5133        synchronized (mPackages) {
5134            if (pkg.mSharedUserId != null) {
5135                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5136                if (suid == null) {
5137                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5138                            "Creating application package " + pkg.packageName
5139                            + " for shared user failed");
5140                }
5141                if (DEBUG_PACKAGE_SCANNING) {
5142                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5143                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5144                                + "): packages=" + suid.packages);
5145                }
5146            }
5147
5148            // Check if we are renaming from an original package name.
5149            PackageSetting origPackage = null;
5150            String realName = null;
5151            if (pkg.mOriginalPackages != null) {
5152                // This package may need to be renamed to a previously
5153                // installed name.  Let's check on that...
5154                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5155                if (pkg.mOriginalPackages.contains(renamed)) {
5156                    // This package had originally been installed as the
5157                    // original name, and we have already taken care of
5158                    // transitioning to the new one.  Just update the new
5159                    // one to continue using the old name.
5160                    realName = pkg.mRealPackage;
5161                    if (!pkg.packageName.equals(renamed)) {
5162                        // Callers into this function may have already taken
5163                        // care of renaming the package; only do it here if
5164                        // it is not already done.
5165                        pkg.setPackageName(renamed);
5166                    }
5167
5168                } else {
5169                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5170                        if ((origPackage = mSettings.peekPackageLPr(
5171                                pkg.mOriginalPackages.get(i))) != null) {
5172                            // We do have the package already installed under its
5173                            // original name...  should we use it?
5174                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5175                                // New package is not compatible with original.
5176                                origPackage = null;
5177                                continue;
5178                            } else if (origPackage.sharedUser != null) {
5179                                // Make sure uid is compatible between packages.
5180                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5181                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5182                                            + " to " + pkg.packageName + ": old uid "
5183                                            + origPackage.sharedUser.name
5184                                            + " differs from " + pkg.mSharedUserId);
5185                                    origPackage = null;
5186                                    continue;
5187                                }
5188                            } else {
5189                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5190                                        + pkg.packageName + " to old name " + origPackage.name);
5191                            }
5192                            break;
5193                        }
5194                    }
5195                }
5196            }
5197
5198            if (mTransferedPackages.contains(pkg.packageName)) {
5199                Slog.w(TAG, "Package " + pkg.packageName
5200                        + " was transferred to another, but its .apk remains");
5201            }
5202
5203            // Just create the setting, don't add it yet. For already existing packages
5204            // the PkgSetting exists already and doesn't have to be created.
5205            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5206                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5207                    pkg.applicationInfo.primaryCpuAbi,
5208                    pkg.applicationInfo.secondaryCpuAbi,
5209                    pkg.applicationInfo.flags, user, false);
5210            if (pkgSetting == null) {
5211                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5212                        "Creating application package " + pkg.packageName + " failed");
5213            }
5214
5215            if (pkgSetting.origPackage != null) {
5216                // If we are first transitioning from an original package,
5217                // fix up the new package's name now.  We need to do this after
5218                // looking up the package under its new name, so getPackageLP
5219                // can take care of fiddling things correctly.
5220                pkg.setPackageName(origPackage.name);
5221
5222                // File a report about this.
5223                String msg = "New package " + pkgSetting.realName
5224                        + " renamed to replace old package " + pkgSetting.name;
5225                reportSettingsProblem(Log.WARN, msg);
5226
5227                // Make a note of it.
5228                mTransferedPackages.add(origPackage.name);
5229
5230                // No longer need to retain this.
5231                pkgSetting.origPackage = null;
5232            }
5233
5234            if (realName != null) {
5235                // Make a note of it.
5236                mTransferedPackages.add(pkg.packageName);
5237            }
5238
5239            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5240                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5241            }
5242
5243            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5244                // Check all shared libraries and map to their actual file path.
5245                // We only do this here for apps not on a system dir, because those
5246                // are the only ones that can fail an install due to this.  We
5247                // will take care of the system apps by updating all of their
5248                // library paths after the scan is done.
5249                updateSharedLibrariesLPw(pkg, null);
5250            }
5251
5252            if (mFoundPolicyFile) {
5253                SELinuxMMAC.assignSeinfoValue(pkg);
5254            }
5255
5256            pkg.applicationInfo.uid = pkgSetting.appId;
5257            pkg.mExtras = pkgSetting;
5258            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5259                try {
5260                    verifySignaturesLP(pkgSetting, pkg);
5261                } catch (PackageManagerException e) {
5262                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5263                        throw e;
5264                    }
5265                    // The signature has changed, but this package is in the system
5266                    // image...  let's recover!
5267                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5268                    // However...  if this package is part of a shared user, but it
5269                    // doesn't match the signature of the shared user, let's fail.
5270                    // What this means is that you can't change the signatures
5271                    // associated with an overall shared user, which doesn't seem all
5272                    // that unreasonable.
5273                    if (pkgSetting.sharedUser != null) {
5274                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5275                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5276                            throw new PackageManagerException(
5277                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5278                                            "Signature mismatch for shared user : "
5279                                            + pkgSetting.sharedUser);
5280                        }
5281                    }
5282                    // File a report about this.
5283                    String msg = "System package " + pkg.packageName
5284                        + " signature changed; retaining data.";
5285                    reportSettingsProblem(Log.WARN, msg);
5286                }
5287            } else {
5288                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5289                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5290                            + pkg.packageName + " upgrade keys do not match the "
5291                            + "previously installed version");
5292                } else {
5293                    // signatures may have changed as result of upgrade
5294                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5295                }
5296            }
5297            // Verify that this new package doesn't have any content providers
5298            // that conflict with existing packages.  Only do this if the
5299            // package isn't already installed, since we don't want to break
5300            // things that are installed.
5301            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5302                final int N = pkg.providers.size();
5303                int i;
5304                for (i=0; i<N; i++) {
5305                    PackageParser.Provider p = pkg.providers.get(i);
5306                    if (p.info.authority != null) {
5307                        String names[] = p.info.authority.split(";");
5308                        for (int j = 0; j < names.length; j++) {
5309                            if (mProvidersByAuthority.containsKey(names[j])) {
5310                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5311                                final String otherPackageName =
5312                                        ((other != null && other.getComponentName() != null) ?
5313                                                other.getComponentName().getPackageName() : "?");
5314                                throw new PackageManagerException(
5315                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5316                                                "Can't install because provider name " + names[j]
5317                                                + " (in package " + pkg.applicationInfo.packageName
5318                                                + ") is already used by " + otherPackageName);
5319                            }
5320                        }
5321                    }
5322                }
5323            }
5324
5325            if (pkg.mAdoptPermissions != null) {
5326                // This package wants to adopt ownership of permissions from
5327                // another package.
5328                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5329                    final String origName = pkg.mAdoptPermissions.get(i);
5330                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5331                    if (orig != null) {
5332                        if (verifyPackageUpdateLPr(orig, pkg)) {
5333                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5334                                    + pkg.packageName);
5335                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5336                        }
5337                    }
5338                }
5339            }
5340        }
5341
5342        final String pkgName = pkg.packageName;
5343
5344        final long scanFileTime = scanFile.lastModified();
5345        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5346        pkg.applicationInfo.processName = fixProcessName(
5347                pkg.applicationInfo.packageName,
5348                pkg.applicationInfo.processName,
5349                pkg.applicationInfo.uid);
5350
5351        File dataPath;
5352        if (mPlatformPackage == pkg) {
5353            // The system package is special.
5354            dataPath = new File(Environment.getDataDirectory(), "system");
5355
5356            pkg.applicationInfo.dataDir = dataPath.getPath();
5357
5358        } else {
5359            // This is a normal package, need to make its data directory.
5360            dataPath = getDataPathForPackage(pkg.packageName, 0);
5361
5362            boolean uidError = false;
5363            if (dataPath.exists()) {
5364                int currentUid = 0;
5365                try {
5366                    StructStat stat = Os.stat(dataPath.getPath());
5367                    currentUid = stat.st_uid;
5368                } catch (ErrnoException e) {
5369                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5370                }
5371
5372                // If we have mismatched owners for the data path, we have a problem.
5373                if (currentUid != pkg.applicationInfo.uid) {
5374                    boolean recovered = false;
5375                    if (currentUid == 0) {
5376                        // The directory somehow became owned by root.  Wow.
5377                        // This is probably because the system was stopped while
5378                        // installd was in the middle of messing with its libs
5379                        // directory.  Ask installd to fix that.
5380                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5381                                pkg.applicationInfo.uid);
5382                        if (ret >= 0) {
5383                            recovered = true;
5384                            String msg = "Package " + pkg.packageName
5385                                    + " unexpectedly changed to uid 0; recovered to " +
5386                                    + pkg.applicationInfo.uid;
5387                            reportSettingsProblem(Log.WARN, msg);
5388                        }
5389                    }
5390                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5391                            || (scanFlags&SCAN_BOOTING) != 0)) {
5392                        // If this is a system app, we can at least delete its
5393                        // current data so the application will still work.
5394                        int ret = removeDataDirsLI(pkgName);
5395                        if (ret >= 0) {
5396                            // TODO: Kill the processes first
5397                            // Old data gone!
5398                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5399                                    ? "System package " : "Third party package ";
5400                            String msg = prefix + pkg.packageName
5401                                    + " has changed from uid: "
5402                                    + currentUid + " to "
5403                                    + pkg.applicationInfo.uid + "; old data erased";
5404                            reportSettingsProblem(Log.WARN, msg);
5405                            recovered = true;
5406
5407                            // And now re-install the app.
5408                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5409                                                   pkg.applicationInfo.seinfo);
5410                            if (ret == -1) {
5411                                // Ack should not happen!
5412                                msg = prefix + pkg.packageName
5413                                        + " could not have data directory re-created after delete.";
5414                                reportSettingsProblem(Log.WARN, msg);
5415                                throw new PackageManagerException(
5416                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5417                            }
5418                        }
5419                        if (!recovered) {
5420                            mHasSystemUidErrors = true;
5421                        }
5422                    } else if (!recovered) {
5423                        // If we allow this install to proceed, we will be broken.
5424                        // Abort, abort!
5425                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5426                                "scanPackageLI");
5427                    }
5428                    if (!recovered) {
5429                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5430                            + pkg.applicationInfo.uid + "/fs_"
5431                            + currentUid;
5432                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5433                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5434                        String msg = "Package " + pkg.packageName
5435                                + " has mismatched uid: "
5436                                + currentUid + " on disk, "
5437                                + pkg.applicationInfo.uid + " in settings";
5438                        // writer
5439                        synchronized (mPackages) {
5440                            mSettings.mReadMessages.append(msg);
5441                            mSettings.mReadMessages.append('\n');
5442                            uidError = true;
5443                            if (!pkgSetting.uidError) {
5444                                reportSettingsProblem(Log.ERROR, msg);
5445                            }
5446                        }
5447                    }
5448                }
5449                pkg.applicationInfo.dataDir = dataPath.getPath();
5450                if (mShouldRestoreconData) {
5451                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5452                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5453                                pkg.applicationInfo.uid);
5454                }
5455            } else {
5456                if (DEBUG_PACKAGE_SCANNING) {
5457                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5458                        Log.v(TAG, "Want this data dir: " + dataPath);
5459                }
5460                //invoke installer to do the actual installation
5461                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5462                                           pkg.applicationInfo.seinfo);
5463                if (ret < 0) {
5464                    // Error from installer
5465                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5466                            "Unable to create data dirs [errorCode=" + ret + "]");
5467                }
5468
5469                if (dataPath.exists()) {
5470                    pkg.applicationInfo.dataDir = dataPath.getPath();
5471                } else {
5472                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5473                    pkg.applicationInfo.dataDir = null;
5474                }
5475            }
5476
5477            pkgSetting.uidError = uidError;
5478        }
5479
5480        final String path = scanFile.getPath();
5481        final String codePath = pkg.applicationInfo.getCodePath();
5482        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5483        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5484            setBundledAppAbisAndRoots(pkg, pkgSetting);
5485
5486            // If we haven't found any native libraries for the app, check if it has
5487            // renderscript code. We'll need to force the app to 32 bit if it has
5488            // renderscript bitcode.
5489            if (pkg.applicationInfo.primaryCpuAbi == null
5490                    && pkg.applicationInfo.secondaryCpuAbi == null
5491                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5492                NativeLibraryHelper.Handle handle = null;
5493                try {
5494                    handle = NativeLibraryHelper.Handle.create(scanFile);
5495                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5496                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5497                    }
5498                } catch (IOException ioe) {
5499                    Slog.w(TAG, "Error scanning system app : " + ioe);
5500                } finally {
5501                    IoUtils.closeQuietly(handle);
5502                }
5503            }
5504
5505            setNativeLibraryPaths(pkg);
5506        } else {
5507            // TODO: We can probably be smarter about this stuff. For installed apps,
5508            // we can calculate this information at install time once and for all. For
5509            // system apps, we can probably assume that this information doesn't change
5510            // after the first boot scan. As things stand, we do lots of unnecessary work.
5511
5512            // Give ourselves some initial paths; we'll come back for another
5513            // pass once we've determined ABI below.
5514            setNativeLibraryPaths(pkg);
5515
5516            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5517            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5518            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5519
5520            NativeLibraryHelper.Handle handle = null;
5521            try {
5522                handle = NativeLibraryHelper.Handle.create(scanFile);
5523                // TODO(multiArch): This can be null for apps that didn't go through the
5524                // usual installation process. We can calculate it again, like we
5525                // do during install time.
5526                //
5527                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5528                // unnecessary.
5529                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5530
5531                // Null out the abis so that they can be recalculated.
5532                pkg.applicationInfo.primaryCpuAbi = null;
5533                pkg.applicationInfo.secondaryCpuAbi = null;
5534                if (isMultiArch(pkg.applicationInfo)) {
5535                    // Warn if we've set an abiOverride for multi-lib packages..
5536                    // By definition, we need to copy both 32 and 64 bit libraries for
5537                    // such packages.
5538                    if (pkg.cpuAbiOverride != null
5539                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5540                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5541                    }
5542
5543                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5544                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5545                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5546                        if (isAsec) {
5547                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5548                        } else {
5549                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5550                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5551                                    useIsaSpecificSubdirs);
5552                        }
5553                    }
5554
5555                    maybeThrowExceptionForMultiArchCopy(
5556                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5557
5558                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5559                        if (isAsec) {
5560                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5561                        } else {
5562                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5563                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5564                                    useIsaSpecificSubdirs);
5565                        }
5566                    }
5567
5568                    maybeThrowExceptionForMultiArchCopy(
5569                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5570
5571                    if (abi64 >= 0) {
5572                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5573                    }
5574
5575                    if (abi32 >= 0) {
5576                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5577                        if (abi64 >= 0) {
5578                            pkg.applicationInfo.secondaryCpuAbi = abi;
5579                        } else {
5580                            pkg.applicationInfo.primaryCpuAbi = abi;
5581                        }
5582                    }
5583                } else {
5584                    String[] abiList = (cpuAbiOverride != null) ?
5585                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5586
5587                    // Enable gross and lame hacks for apps that are built with old
5588                    // SDK tools. We must scan their APKs for renderscript bitcode and
5589                    // not launch them if it's present. Don't bother checking on devices
5590                    // that don't have 64 bit support.
5591                    boolean needsRenderScriptOverride = false;
5592                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5593                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5594                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5595                        needsRenderScriptOverride = true;
5596                    }
5597
5598                    final int copyRet;
5599                    if (isAsec) {
5600                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5601                    } else {
5602                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5603                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5604                    }
5605
5606                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5607                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5608                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5609                    }
5610
5611                    if (copyRet >= 0) {
5612                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5613                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5614                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5615                    } else if (needsRenderScriptOverride) {
5616                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5617                    }
5618                }
5619            } catch (IOException ioe) {
5620                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5621            } finally {
5622                IoUtils.closeQuietly(handle);
5623            }
5624
5625            // Now that we've calculated the ABIs and determined if it's an internal app,
5626            // we will go ahead and populate the nativeLibraryPath.
5627            setNativeLibraryPaths(pkg);
5628
5629            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5630            final int[] userIds = sUserManager.getUserIds();
5631            synchronized (mInstallLock) {
5632                // Create a native library symlink only if we have native libraries
5633                // and if the native libraries are 32 bit libraries. We do not provide
5634                // this symlink for 64 bit libraries.
5635                if (pkg.applicationInfo.primaryCpuAbi != null &&
5636                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5637                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5638                    for (int userId : userIds) {
5639                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5640                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5641                                    "Failed linking native library dir (user=" + userId + ")");
5642                        }
5643                    }
5644                }
5645            }
5646        }
5647
5648        // This is a special case for the "system" package, where the ABI is
5649        // dictated by the zygote configuration (and init.rc). We should keep track
5650        // of this ABI so that we can deal with "normal" applications that run under
5651        // the same UID correctly.
5652        if (mPlatformPackage == pkg) {
5653            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5654                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5655        }
5656
5657        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5658        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5659        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5660        // Copy the derived override back to the parsed package, so that we can
5661        // update the package settings accordingly.
5662        pkg.cpuAbiOverride = cpuAbiOverride;
5663
5664        if (DEBUG_ABI_SELECTION) {
5665            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5666                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5667                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5668        }
5669
5670        // Push the derived path down into PackageSettings so we know what to
5671        // clean up at uninstall time.
5672        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5673
5674        if (DEBUG_ABI_SELECTION) {
5675            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5676                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5677                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5678        }
5679
5680        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5681            // We don't do this here during boot because we can do it all
5682            // at once after scanning all existing packages.
5683            //
5684            // We also do this *before* we perform dexopt on this package, so that
5685            // we can avoid redundant dexopts, and also to make sure we've got the
5686            // code and package path correct.
5687            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5688                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5689        }
5690
5691        if ((scanFlags & SCAN_NO_DEX) == 0) {
5692            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5693                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5694                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5695            }
5696        }
5697
5698        if (mFactoryTest && pkg.requestedPermissions.contains(
5699                android.Manifest.permission.FACTORY_TEST)) {
5700            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5701        }
5702
5703        ArrayList<PackageParser.Package> clientLibPkgs = null;
5704
5705        // writer
5706        synchronized (mPackages) {
5707            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5708                // Only system apps can add new shared libraries.
5709                if (pkg.libraryNames != null) {
5710                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5711                        String name = pkg.libraryNames.get(i);
5712                        boolean allowed = false;
5713                        if (isUpdatedSystemApp(pkg)) {
5714                            // New library entries can only be added through the
5715                            // system image.  This is important to get rid of a lot
5716                            // of nasty edge cases: for example if we allowed a non-
5717                            // system update of the app to add a library, then uninstalling
5718                            // the update would make the library go away, and assumptions
5719                            // we made such as through app install filtering would now
5720                            // have allowed apps on the device which aren't compatible
5721                            // with it.  Better to just have the restriction here, be
5722                            // conservative, and create many fewer cases that can negatively
5723                            // impact the user experience.
5724                            final PackageSetting sysPs = mSettings
5725                                    .getDisabledSystemPkgLPr(pkg.packageName);
5726                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5727                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5728                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5729                                        allowed = true;
5730                                        allowed = true;
5731                                        break;
5732                                    }
5733                                }
5734                            }
5735                        } else {
5736                            allowed = true;
5737                        }
5738                        if (allowed) {
5739                            if (!mSharedLibraries.containsKey(name)) {
5740                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5741                            } else if (!name.equals(pkg.packageName)) {
5742                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5743                                        + name + " already exists; skipping");
5744                            }
5745                        } else {
5746                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5747                                    + name + " that is not declared on system image; skipping");
5748                        }
5749                    }
5750                    if ((scanFlags&SCAN_BOOTING) == 0) {
5751                        // If we are not booting, we need to update any applications
5752                        // that are clients of our shared library.  If we are booting,
5753                        // this will all be done once the scan is complete.
5754                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5755                    }
5756                }
5757            }
5758        }
5759
5760        // We also need to dexopt any apps that are dependent on this library.  Note that
5761        // if these fail, we should abort the install since installing the library will
5762        // result in some apps being broken.
5763        if (clientLibPkgs != null) {
5764            if ((scanFlags & SCAN_NO_DEX) == 0) {
5765                for (int i = 0; i < clientLibPkgs.size(); i++) {
5766                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5767                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5768                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5769                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5770                                "scanPackageLI failed to dexopt clientLibPkgs");
5771                    }
5772                }
5773            }
5774        }
5775
5776        // Request the ActivityManager to kill the process(only for existing packages)
5777        // so that we do not end up in a confused state while the user is still using the older
5778        // version of the application while the new one gets installed.
5779        if ((scanFlags & SCAN_REPLACING) != 0) {
5780            killApplication(pkg.applicationInfo.packageName,
5781                        pkg.applicationInfo.uid, "update pkg");
5782        }
5783
5784        // Also need to kill any apps that are dependent on the library.
5785        if (clientLibPkgs != null) {
5786            for (int i=0; i<clientLibPkgs.size(); i++) {
5787                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5788                killApplication(clientPkg.applicationInfo.packageName,
5789                        clientPkg.applicationInfo.uid, "update lib");
5790            }
5791        }
5792
5793        // writer
5794        synchronized (mPackages) {
5795            // We don't expect installation to fail beyond this point
5796
5797            // Add the new setting to mSettings
5798            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5799            // Add the new setting to mPackages
5800            mPackages.put(pkg.applicationInfo.packageName, pkg);
5801            // Make sure we don't accidentally delete its data.
5802            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5803            while (iter.hasNext()) {
5804                PackageCleanItem item = iter.next();
5805                if (pkgName.equals(item.packageName)) {
5806                    iter.remove();
5807                }
5808            }
5809
5810            // Take care of first install / last update times.
5811            if (currentTime != 0) {
5812                if (pkgSetting.firstInstallTime == 0) {
5813                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5814                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5815                    pkgSetting.lastUpdateTime = currentTime;
5816                }
5817            } else if (pkgSetting.firstInstallTime == 0) {
5818                // We need *something*.  Take time time stamp of the file.
5819                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5820            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5821                if (scanFileTime != pkgSetting.timeStamp) {
5822                    // A package on the system image has changed; consider this
5823                    // to be an update.
5824                    pkgSetting.lastUpdateTime = scanFileTime;
5825                }
5826            }
5827
5828            // Add the package's KeySets to the global KeySetManagerService
5829            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5830            try {
5831                // Old KeySetData no longer valid.
5832                ksms.removeAppKeySetDataLPw(pkg.packageName);
5833                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5834                if (pkg.mKeySetMapping != null) {
5835                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5836                            pkg.mKeySetMapping.entrySet()) {
5837                        if (entry.getValue() != null) {
5838                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5839                                                          entry.getValue(), entry.getKey());
5840                        }
5841                    }
5842                    if (pkg.mUpgradeKeySets != null) {
5843                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5844                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5845                        }
5846                    }
5847                }
5848            } catch (NullPointerException e) {
5849                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5850            } catch (IllegalArgumentException e) {
5851                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5852            }
5853
5854            int N = pkg.providers.size();
5855            StringBuilder r = null;
5856            int i;
5857            for (i=0; i<N; i++) {
5858                PackageParser.Provider p = pkg.providers.get(i);
5859                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5860                        p.info.processName, pkg.applicationInfo.uid);
5861                mProviders.addProvider(p);
5862                p.syncable = p.info.isSyncable;
5863                if (p.info.authority != null) {
5864                    String names[] = p.info.authority.split(";");
5865                    p.info.authority = null;
5866                    for (int j = 0; j < names.length; j++) {
5867                        if (j == 1 && p.syncable) {
5868                            // We only want the first authority for a provider to possibly be
5869                            // syncable, so if we already added this provider using a different
5870                            // authority clear the syncable flag. We copy the provider before
5871                            // changing it because the mProviders object contains a reference
5872                            // to a provider that we don't want to change.
5873                            // Only do this for the second authority since the resulting provider
5874                            // object can be the same for all future authorities for this provider.
5875                            p = new PackageParser.Provider(p);
5876                            p.syncable = false;
5877                        }
5878                        if (!mProvidersByAuthority.containsKey(names[j])) {
5879                            mProvidersByAuthority.put(names[j], p);
5880                            if (p.info.authority == null) {
5881                                p.info.authority = names[j];
5882                            } else {
5883                                p.info.authority = p.info.authority + ";" + names[j];
5884                            }
5885                            if (DEBUG_PACKAGE_SCANNING) {
5886                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5887                                    Log.d(TAG, "Registered content provider: " + names[j]
5888                                            + ", className = " + p.info.name + ", isSyncable = "
5889                                            + p.info.isSyncable);
5890                            }
5891                        } else {
5892                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5893                            Slog.w(TAG, "Skipping provider name " + names[j] +
5894                                    " (in package " + pkg.applicationInfo.packageName +
5895                                    "): name already used by "
5896                                    + ((other != null && other.getComponentName() != null)
5897                                            ? other.getComponentName().getPackageName() : "?"));
5898                        }
5899                    }
5900                }
5901                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5902                    if (r == null) {
5903                        r = new StringBuilder(256);
5904                    } else {
5905                        r.append(' ');
5906                    }
5907                    r.append(p.info.name);
5908                }
5909            }
5910            if (r != null) {
5911                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5912            }
5913
5914            N = pkg.services.size();
5915            r = null;
5916            for (i=0; i<N; i++) {
5917                PackageParser.Service s = pkg.services.get(i);
5918                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5919                        s.info.processName, pkg.applicationInfo.uid);
5920                mServices.addService(s);
5921                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5922                    if (r == null) {
5923                        r = new StringBuilder(256);
5924                    } else {
5925                        r.append(' ');
5926                    }
5927                    r.append(s.info.name);
5928                }
5929            }
5930            if (r != null) {
5931                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5932            }
5933
5934            N = pkg.receivers.size();
5935            r = null;
5936            for (i=0; i<N; i++) {
5937                PackageParser.Activity a = pkg.receivers.get(i);
5938                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5939                        a.info.processName, pkg.applicationInfo.uid);
5940                mReceivers.addActivity(a, "receiver");
5941                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5942                    if (r == null) {
5943                        r = new StringBuilder(256);
5944                    } else {
5945                        r.append(' ');
5946                    }
5947                    r.append(a.info.name);
5948                }
5949            }
5950            if (r != null) {
5951                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5952            }
5953
5954            N = pkg.activities.size();
5955            r = null;
5956            for (i=0; i<N; i++) {
5957                PackageParser.Activity a = pkg.activities.get(i);
5958                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5959                        a.info.processName, pkg.applicationInfo.uid);
5960                mActivities.addActivity(a, "activity");
5961                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5962                    if (r == null) {
5963                        r = new StringBuilder(256);
5964                    } else {
5965                        r.append(' ');
5966                    }
5967                    r.append(a.info.name);
5968                }
5969            }
5970            if (r != null) {
5971                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5972            }
5973
5974            N = pkg.permissionGroups.size();
5975            r = null;
5976            for (i=0; i<N; i++) {
5977                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5978                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5979                if (cur == null) {
5980                    mPermissionGroups.put(pg.info.name, pg);
5981                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5982                        if (r == null) {
5983                            r = new StringBuilder(256);
5984                        } else {
5985                            r.append(' ');
5986                        }
5987                        r.append(pg.info.name);
5988                    }
5989                } else {
5990                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5991                            + pg.info.packageName + " ignored: original from "
5992                            + cur.info.packageName);
5993                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5994                        if (r == null) {
5995                            r = new StringBuilder(256);
5996                        } else {
5997                            r.append(' ');
5998                        }
5999                        r.append("DUP:");
6000                        r.append(pg.info.name);
6001                    }
6002                }
6003            }
6004            if (r != null) {
6005                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6006            }
6007
6008            N = pkg.permissions.size();
6009            r = null;
6010            for (i=0; i<N; i++) {
6011                PackageParser.Permission p = pkg.permissions.get(i);
6012                HashMap<String, BasePermission> permissionMap =
6013                        p.tree ? mSettings.mPermissionTrees
6014                        : mSettings.mPermissions;
6015                p.group = mPermissionGroups.get(p.info.group);
6016                if (p.info.group == null || p.group != null) {
6017                    BasePermission bp = permissionMap.get(p.info.name);
6018
6019                    // Allow system apps to redefine non-system permissions
6020                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6021                        final boolean currentOwnerIsSystem = (bp.perm != null
6022                                && isSystemApp(bp.perm.owner));
6023                        if (isSystemApp(p.owner)) {
6024                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6025                                // It's a built-in permission and no owner, take ownership now
6026                                bp.packageSetting = pkgSetting;
6027                                bp.perm = p;
6028                                bp.uid = pkg.applicationInfo.uid;
6029                                bp.sourcePackage = p.info.packageName;
6030                            } else if (!currentOwnerIsSystem) {
6031                                String msg = "New decl " + p.owner + " of permission  "
6032                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6033                                reportSettingsProblem(Log.WARN, msg);
6034                                bp = null;
6035                            }
6036                        }
6037                    }
6038
6039                    if (bp == null) {
6040                        bp = new BasePermission(p.info.name, p.info.packageName,
6041                                BasePermission.TYPE_NORMAL);
6042                        permissionMap.put(p.info.name, bp);
6043                    }
6044
6045                    if (bp.perm == null) {
6046                        if (bp.sourcePackage == null
6047                                || bp.sourcePackage.equals(p.info.packageName)) {
6048                            BasePermission tree = findPermissionTreeLP(p.info.name);
6049                            if (tree == null
6050                                    || tree.sourcePackage.equals(p.info.packageName)) {
6051                                bp.packageSetting = pkgSetting;
6052                                bp.perm = p;
6053                                bp.uid = pkg.applicationInfo.uid;
6054                                bp.sourcePackage = p.info.packageName;
6055                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6056                                    if (r == null) {
6057                                        r = new StringBuilder(256);
6058                                    } else {
6059                                        r.append(' ');
6060                                    }
6061                                    r.append(p.info.name);
6062                                }
6063                            } else {
6064                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6065                                        + p.info.packageName + " ignored: base tree "
6066                                        + tree.name + " is from package "
6067                                        + tree.sourcePackage);
6068                            }
6069                        } else {
6070                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6071                                    + p.info.packageName + " ignored: original from "
6072                                    + bp.sourcePackage);
6073                        }
6074                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6075                        if (r == null) {
6076                            r = new StringBuilder(256);
6077                        } else {
6078                            r.append(' ');
6079                        }
6080                        r.append("DUP:");
6081                        r.append(p.info.name);
6082                    }
6083                    if (bp.perm == p) {
6084                        bp.protectionLevel = p.info.protectionLevel;
6085                    }
6086                } else {
6087                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6088                            + p.info.packageName + " ignored: no group "
6089                            + p.group);
6090                }
6091            }
6092            if (r != null) {
6093                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6094            }
6095
6096            N = pkg.instrumentation.size();
6097            r = null;
6098            for (i=0; i<N; i++) {
6099                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6100                a.info.packageName = pkg.applicationInfo.packageName;
6101                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6102                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6103                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6104                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6105                a.info.dataDir = pkg.applicationInfo.dataDir;
6106
6107                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6108                // need other information about the application, like the ABI and what not ?
6109                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6110                mInstrumentation.put(a.getComponentName(), a);
6111                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6112                    if (r == null) {
6113                        r = new StringBuilder(256);
6114                    } else {
6115                        r.append(' ');
6116                    }
6117                    r.append(a.info.name);
6118                }
6119            }
6120            if (r != null) {
6121                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6122            }
6123
6124            if (pkg.protectedBroadcasts != null) {
6125                N = pkg.protectedBroadcasts.size();
6126                for (i=0; i<N; i++) {
6127                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6128                }
6129            }
6130
6131            pkgSetting.setTimeStamp(scanFileTime);
6132
6133            // Create idmap files for pairs of (packages, overlay packages).
6134            // Note: "android", ie framework-res.apk, is handled by native layers.
6135            if (pkg.mOverlayTarget != null) {
6136                // This is an overlay package.
6137                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6138                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6139                        mOverlays.put(pkg.mOverlayTarget,
6140                                new HashMap<String, PackageParser.Package>());
6141                    }
6142                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6143                    map.put(pkg.packageName, pkg);
6144                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6145                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6146                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6147                                "scanPackageLI failed to createIdmap");
6148                    }
6149                }
6150            } else if (mOverlays.containsKey(pkg.packageName) &&
6151                    !pkg.packageName.equals("android")) {
6152                // This is a regular package, with one or more known overlay packages.
6153                createIdmapsForPackageLI(pkg);
6154            }
6155        }
6156
6157        return pkg;
6158    }
6159
6160    /**
6161     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6162     * i.e, so that all packages can be run inside a single process if required.
6163     *
6164     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6165     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6166     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6167     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6168     * updating a package that belongs to a shared user.
6169     *
6170     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6171     * adds unnecessary complexity.
6172     */
6173    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6174            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6175        String requiredInstructionSet = null;
6176        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6177            requiredInstructionSet = VMRuntime.getInstructionSet(
6178                     scannedPackage.applicationInfo.primaryCpuAbi);
6179        }
6180
6181        PackageSetting requirer = null;
6182        for (PackageSetting ps : packagesForUser) {
6183            // If packagesForUser contains scannedPackage, we skip it. This will happen
6184            // when scannedPackage is an update of an existing package. Without this check,
6185            // we will never be able to change the ABI of any package belonging to a shared
6186            // user, even if it's compatible with other packages.
6187            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6188                if (ps.primaryCpuAbiString == null) {
6189                    continue;
6190                }
6191
6192                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6193                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6194                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6195                    // this but there's not much we can do.
6196                    String errorMessage = "Instruction set mismatch, "
6197                            + ((requirer == null) ? "[caller]" : requirer)
6198                            + " requires " + requiredInstructionSet + " whereas " + ps
6199                            + " requires " + instructionSet;
6200                    Slog.w(TAG, errorMessage);
6201                }
6202
6203                if (requiredInstructionSet == null) {
6204                    requiredInstructionSet = instructionSet;
6205                    requirer = ps;
6206                }
6207            }
6208        }
6209
6210        if (requiredInstructionSet != null) {
6211            String adjustedAbi;
6212            if (requirer != null) {
6213                // requirer != null implies that either scannedPackage was null or that scannedPackage
6214                // did not require an ABI, in which case we have to adjust scannedPackage to match
6215                // the ABI of the set (which is the same as requirer's ABI)
6216                adjustedAbi = requirer.primaryCpuAbiString;
6217                if (scannedPackage != null) {
6218                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6219                }
6220            } else {
6221                // requirer == null implies that we're updating all ABIs in the set to
6222                // match scannedPackage.
6223                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6224            }
6225
6226            for (PackageSetting ps : packagesForUser) {
6227                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6228                    if (ps.primaryCpuAbiString != null) {
6229                        continue;
6230                    }
6231
6232                    ps.primaryCpuAbiString = adjustedAbi;
6233                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6234                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6235                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6236
6237                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6238                                deferDexOpt, true) == DEX_OPT_FAILED) {
6239                            ps.primaryCpuAbiString = null;
6240                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6241                            return;
6242                        } else {
6243                            mInstaller.rmdex(ps.codePathString,
6244                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6245                        }
6246                    }
6247                }
6248            }
6249        }
6250    }
6251
6252    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6253        synchronized (mPackages) {
6254            mResolverReplaced = true;
6255            // Set up information for custom user intent resolution activity.
6256            mResolveActivity.applicationInfo = pkg.applicationInfo;
6257            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6258            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6259            mResolveActivity.processName = null;
6260            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6261            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6262                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6263            mResolveActivity.theme = 0;
6264            mResolveActivity.exported = true;
6265            mResolveActivity.enabled = true;
6266            mResolveInfo.activityInfo = mResolveActivity;
6267            mResolveInfo.priority = 0;
6268            mResolveInfo.preferredOrder = 0;
6269            mResolveInfo.match = 0;
6270            mResolveComponentName = mCustomResolverComponentName;
6271            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6272                    mResolveComponentName);
6273        }
6274    }
6275
6276    private static String calculateBundledApkRoot(final String codePathString) {
6277        final File codePath = new File(codePathString);
6278        final File codeRoot;
6279        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6280            codeRoot = Environment.getRootDirectory();
6281        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6282            codeRoot = Environment.getOemDirectory();
6283        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6284            codeRoot = Environment.getVendorDirectory();
6285        } else {
6286            // Unrecognized code path; take its top real segment as the apk root:
6287            // e.g. /something/app/blah.apk => /something
6288            try {
6289                File f = codePath.getCanonicalFile();
6290                File parent = f.getParentFile();    // non-null because codePath is a file
6291                File tmp;
6292                while ((tmp = parent.getParentFile()) != null) {
6293                    f = parent;
6294                    parent = tmp;
6295                }
6296                codeRoot = f;
6297                Slog.w(TAG, "Unrecognized code path "
6298                        + codePath + " - using " + codeRoot);
6299            } catch (IOException e) {
6300                // Can't canonicalize the code path -- shenanigans?
6301                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6302                return Environment.getRootDirectory().getPath();
6303            }
6304        }
6305        return codeRoot.getPath();
6306    }
6307
6308    /**
6309     * Derive and set the location of native libraries for the given package,
6310     * which varies depending on where and how the package was installed.
6311     */
6312    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6313        final ApplicationInfo info = pkg.applicationInfo;
6314        final String codePath = pkg.codePath;
6315        final File codeFile = new File(codePath);
6316        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6317        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6318
6319        info.nativeLibraryRootDir = null;
6320        info.nativeLibraryRootRequiresIsa = false;
6321        info.nativeLibraryDir = null;
6322        info.secondaryNativeLibraryDir = null;
6323
6324        if (isApkFile(codeFile)) {
6325            // Monolithic install
6326            if (bundledApp) {
6327                // If "/system/lib64/apkname" exists, assume that is the per-package
6328                // native library directory to use; otherwise use "/system/lib/apkname".
6329                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6330                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6331                        getPrimaryInstructionSet(info));
6332
6333                // This is a bundled system app so choose the path based on the ABI.
6334                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6335                // is just the default path.
6336                final String apkName = deriveCodePathName(codePath);
6337                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6338                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6339                        apkName).getAbsolutePath();
6340
6341                if (info.secondaryCpuAbi != null) {
6342                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6343                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6344                            secondaryLibDir, apkName).getAbsolutePath();
6345                }
6346            } else if (asecApp) {
6347                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6348                        .getAbsolutePath();
6349            } else {
6350                final String apkName = deriveCodePathName(codePath);
6351                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6352                        .getAbsolutePath();
6353            }
6354
6355            info.nativeLibraryRootRequiresIsa = false;
6356            info.nativeLibraryDir = info.nativeLibraryRootDir;
6357        } else {
6358            // Cluster install
6359            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6360            info.nativeLibraryRootRequiresIsa = true;
6361
6362            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6363                    getPrimaryInstructionSet(info)).getAbsolutePath();
6364
6365            if (info.secondaryCpuAbi != null) {
6366                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6367                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6368            }
6369        }
6370    }
6371
6372    /**
6373     * Calculate the abis and roots for a bundled app. These can uniquely
6374     * be determined from the contents of the system partition, i.e whether
6375     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6376     * of this information, and instead assume that the system was built
6377     * sensibly.
6378     */
6379    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6380                                           PackageSetting pkgSetting) {
6381        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6382
6383        // If "/system/lib64/apkname" exists, assume that is the per-package
6384        // native library directory to use; otherwise use "/system/lib/apkname".
6385        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6386        setBundledAppAbi(pkg, apkRoot, apkName);
6387        // pkgSetting might be null during rescan following uninstall of updates
6388        // to a bundled app, so accommodate that possibility.  The settings in
6389        // that case will be established later from the parsed package.
6390        //
6391        // If the settings aren't null, sync them up with what we've just derived.
6392        // note that apkRoot isn't stored in the package settings.
6393        if (pkgSetting != null) {
6394            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6395            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6396        }
6397    }
6398
6399    /**
6400     * Deduces the ABI of a bundled app and sets the relevant fields on the
6401     * parsed pkg object.
6402     *
6403     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6404     *        under which system libraries are installed.
6405     * @param apkName the name of the installed package.
6406     */
6407    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6408        final File codeFile = new File(pkg.codePath);
6409
6410        final boolean has64BitLibs;
6411        final boolean has32BitLibs;
6412        if (isApkFile(codeFile)) {
6413            // Monolithic install
6414            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6415            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6416        } else {
6417            // Cluster install
6418            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6419            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6420                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6421                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6422                has64BitLibs = (new File(rootDir, isa)).exists();
6423            } else {
6424                has64BitLibs = false;
6425            }
6426            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6427                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6428                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6429                has32BitLibs = (new File(rootDir, isa)).exists();
6430            } else {
6431                has32BitLibs = false;
6432            }
6433        }
6434
6435        if (has64BitLibs && !has32BitLibs) {
6436            // The package has 64 bit libs, but not 32 bit libs. Its primary
6437            // ABI should be 64 bit. We can safely assume here that the bundled
6438            // native libraries correspond to the most preferred ABI in the list.
6439
6440            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6441            pkg.applicationInfo.secondaryCpuAbi = null;
6442        } else if (has32BitLibs && !has64BitLibs) {
6443            // The package has 32 bit libs but not 64 bit libs. Its primary
6444            // ABI should be 32 bit.
6445
6446            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6447            pkg.applicationInfo.secondaryCpuAbi = null;
6448        } else if (has32BitLibs && has64BitLibs) {
6449            // The application has both 64 and 32 bit bundled libraries. We check
6450            // here that the app declares multiArch support, and warn if it doesn't.
6451            //
6452            // We will be lenient here and record both ABIs. The primary will be the
6453            // ABI that's higher on the list, i.e, a device that's configured to prefer
6454            // 64 bit apps will see a 64 bit primary ABI,
6455
6456            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6457                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6458            }
6459
6460            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6461                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6462                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6463            } else {
6464                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6465                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6466            }
6467        } else {
6468            pkg.applicationInfo.primaryCpuAbi = null;
6469            pkg.applicationInfo.secondaryCpuAbi = null;
6470        }
6471    }
6472
6473    private void killApplication(String pkgName, int appId, String reason) {
6474        // Request the ActivityManager to kill the process(only for existing packages)
6475        // so that we do not end up in a confused state while the user is still using the older
6476        // version of the application while the new one gets installed.
6477        IActivityManager am = ActivityManagerNative.getDefault();
6478        if (am != null) {
6479            try {
6480                am.killApplicationWithAppId(pkgName, appId, reason);
6481            } catch (RemoteException e) {
6482            }
6483        }
6484    }
6485
6486    void removePackageLI(PackageSetting ps, boolean chatty) {
6487        if (DEBUG_INSTALL) {
6488            if (chatty)
6489                Log.d(TAG, "Removing package " + ps.name);
6490        }
6491
6492        // writer
6493        synchronized (mPackages) {
6494            mPackages.remove(ps.name);
6495            final PackageParser.Package pkg = ps.pkg;
6496            if (pkg != null) {
6497                cleanPackageDataStructuresLILPw(pkg, chatty);
6498            }
6499        }
6500    }
6501
6502    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6503        if (DEBUG_INSTALL) {
6504            if (chatty)
6505                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6506        }
6507
6508        // writer
6509        synchronized (mPackages) {
6510            mPackages.remove(pkg.applicationInfo.packageName);
6511            cleanPackageDataStructuresLILPw(pkg, chatty);
6512        }
6513    }
6514
6515    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6516        int N = pkg.providers.size();
6517        StringBuilder r = null;
6518        int i;
6519        for (i=0; i<N; i++) {
6520            PackageParser.Provider p = pkg.providers.get(i);
6521            mProviders.removeProvider(p);
6522            if (p.info.authority == null) {
6523
6524                /* There was another ContentProvider with this authority when
6525                 * this app was installed so this authority is null,
6526                 * Ignore it as we don't have to unregister the provider.
6527                 */
6528                continue;
6529            }
6530            String names[] = p.info.authority.split(";");
6531            for (int j = 0; j < names.length; j++) {
6532                if (mProvidersByAuthority.get(names[j]) == p) {
6533                    mProvidersByAuthority.remove(names[j]);
6534                    if (DEBUG_REMOVE) {
6535                        if (chatty)
6536                            Log.d(TAG, "Unregistered content provider: " + names[j]
6537                                    + ", className = " + p.info.name + ", isSyncable = "
6538                                    + p.info.isSyncable);
6539                    }
6540                }
6541            }
6542            if (DEBUG_REMOVE && chatty) {
6543                if (r == null) {
6544                    r = new StringBuilder(256);
6545                } else {
6546                    r.append(' ');
6547                }
6548                r.append(p.info.name);
6549            }
6550        }
6551        if (r != null) {
6552            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6553        }
6554
6555        N = pkg.services.size();
6556        r = null;
6557        for (i=0; i<N; i++) {
6558            PackageParser.Service s = pkg.services.get(i);
6559            mServices.removeService(s);
6560            if (chatty) {
6561                if (r == null) {
6562                    r = new StringBuilder(256);
6563                } else {
6564                    r.append(' ');
6565                }
6566                r.append(s.info.name);
6567            }
6568        }
6569        if (r != null) {
6570            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6571        }
6572
6573        N = pkg.receivers.size();
6574        r = null;
6575        for (i=0; i<N; i++) {
6576            PackageParser.Activity a = pkg.receivers.get(i);
6577            mReceivers.removeActivity(a, "receiver");
6578            if (DEBUG_REMOVE && chatty) {
6579                if (r == null) {
6580                    r = new StringBuilder(256);
6581                } else {
6582                    r.append(' ');
6583                }
6584                r.append(a.info.name);
6585            }
6586        }
6587        if (r != null) {
6588            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6589        }
6590
6591        N = pkg.activities.size();
6592        r = null;
6593        for (i=0; i<N; i++) {
6594            PackageParser.Activity a = pkg.activities.get(i);
6595            mActivities.removeActivity(a, "activity");
6596            if (DEBUG_REMOVE && chatty) {
6597                if (r == null) {
6598                    r = new StringBuilder(256);
6599                } else {
6600                    r.append(' ');
6601                }
6602                r.append(a.info.name);
6603            }
6604        }
6605        if (r != null) {
6606            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6607        }
6608
6609        N = pkg.permissions.size();
6610        r = null;
6611        for (i=0; i<N; i++) {
6612            PackageParser.Permission p = pkg.permissions.get(i);
6613            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6614            if (bp == null) {
6615                bp = mSettings.mPermissionTrees.get(p.info.name);
6616            }
6617            if (bp != null && bp.perm == p) {
6618                bp.perm = null;
6619                if (DEBUG_REMOVE && chatty) {
6620                    if (r == null) {
6621                        r = new StringBuilder(256);
6622                    } else {
6623                        r.append(' ');
6624                    }
6625                    r.append(p.info.name);
6626                }
6627            }
6628            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6629                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6630                if (appOpPerms != null) {
6631                    appOpPerms.remove(pkg.packageName);
6632                }
6633            }
6634        }
6635        if (r != null) {
6636            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6637        }
6638
6639        N = pkg.requestedPermissions.size();
6640        r = null;
6641        for (i=0; i<N; i++) {
6642            String perm = pkg.requestedPermissions.get(i);
6643            BasePermission bp = mSettings.mPermissions.get(perm);
6644            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6645                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6646                if (appOpPerms != null) {
6647                    appOpPerms.remove(pkg.packageName);
6648                    if (appOpPerms.isEmpty()) {
6649                        mAppOpPermissionPackages.remove(perm);
6650                    }
6651                }
6652            }
6653        }
6654        if (r != null) {
6655            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6656        }
6657
6658        N = pkg.instrumentation.size();
6659        r = null;
6660        for (i=0; i<N; i++) {
6661            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6662            mInstrumentation.remove(a.getComponentName());
6663            if (DEBUG_REMOVE && chatty) {
6664                if (r == null) {
6665                    r = new StringBuilder(256);
6666                } else {
6667                    r.append(' ');
6668                }
6669                r.append(a.info.name);
6670            }
6671        }
6672        if (r != null) {
6673            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6674        }
6675
6676        r = null;
6677        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6678            // Only system apps can hold shared libraries.
6679            if (pkg.libraryNames != null) {
6680                for (i=0; i<pkg.libraryNames.size(); i++) {
6681                    String name = pkg.libraryNames.get(i);
6682                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6683                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6684                        mSharedLibraries.remove(name);
6685                        if (DEBUG_REMOVE && chatty) {
6686                            if (r == null) {
6687                                r = new StringBuilder(256);
6688                            } else {
6689                                r.append(' ');
6690                            }
6691                            r.append(name);
6692                        }
6693                    }
6694                }
6695            }
6696        }
6697        if (r != null) {
6698            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6699        }
6700    }
6701
6702    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6703        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6704            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6705                return true;
6706            }
6707        }
6708        return false;
6709    }
6710
6711    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6712    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6713    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6714
6715    private void updatePermissionsLPw(String changingPkg,
6716            PackageParser.Package pkgInfo, int flags) {
6717        // Make sure there are no dangling permission trees.
6718        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6719        while (it.hasNext()) {
6720            final BasePermission bp = it.next();
6721            if (bp.packageSetting == null) {
6722                // We may not yet have parsed the package, so just see if
6723                // we still know about its settings.
6724                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6725            }
6726            if (bp.packageSetting == null) {
6727                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6728                        + " from package " + bp.sourcePackage);
6729                it.remove();
6730            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6731                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6732                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6733                            + " from package " + bp.sourcePackage);
6734                    flags |= UPDATE_PERMISSIONS_ALL;
6735                    it.remove();
6736                }
6737            }
6738        }
6739
6740        // Make sure all dynamic permissions have been assigned to a package,
6741        // and make sure there are no dangling permissions.
6742        it = mSettings.mPermissions.values().iterator();
6743        while (it.hasNext()) {
6744            final BasePermission bp = it.next();
6745            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6746                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6747                        + bp.name + " pkg=" + bp.sourcePackage
6748                        + " info=" + bp.pendingInfo);
6749                if (bp.packageSetting == null && bp.pendingInfo != null) {
6750                    final BasePermission tree = findPermissionTreeLP(bp.name);
6751                    if (tree != null && tree.perm != null) {
6752                        bp.packageSetting = tree.packageSetting;
6753                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6754                                new PermissionInfo(bp.pendingInfo));
6755                        bp.perm.info.packageName = tree.perm.info.packageName;
6756                        bp.perm.info.name = bp.name;
6757                        bp.uid = tree.uid;
6758                    }
6759                }
6760            }
6761            if (bp.packageSetting == null) {
6762                // We may not yet have parsed the package, so just see if
6763                // we still know about its settings.
6764                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6765            }
6766            if (bp.packageSetting == null) {
6767                Slog.w(TAG, "Removing dangling permission: " + bp.name
6768                        + " from package " + bp.sourcePackage);
6769                it.remove();
6770            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6771                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6772                    Slog.i(TAG, "Removing old permission: " + bp.name
6773                            + " from package " + bp.sourcePackage);
6774                    flags |= UPDATE_PERMISSIONS_ALL;
6775                    it.remove();
6776                }
6777            }
6778        }
6779
6780        // Now update the permissions for all packages, in particular
6781        // replace the granted permissions of the system packages.
6782        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6783            for (PackageParser.Package pkg : mPackages.values()) {
6784                if (pkg != pkgInfo) {
6785                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6786                            changingPkg);
6787                }
6788            }
6789        }
6790
6791        if (pkgInfo != null) {
6792            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6793        }
6794    }
6795
6796    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6797            String packageOfInterest) {
6798        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6799        if (ps == null) {
6800            return;
6801        }
6802        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6803        HashSet<String> origPermissions = gp.grantedPermissions;
6804        boolean changedPermission = false;
6805
6806        if (replace) {
6807            ps.permissionsFixed = false;
6808            if (gp == ps) {
6809                origPermissions = new HashSet<String>(gp.grantedPermissions);
6810                gp.grantedPermissions.clear();
6811                gp.gids = mGlobalGids;
6812            }
6813        }
6814
6815        if (gp.gids == null) {
6816            gp.gids = mGlobalGids;
6817        }
6818
6819        final int N = pkg.requestedPermissions.size();
6820        for (int i=0; i<N; i++) {
6821            final String name = pkg.requestedPermissions.get(i);
6822            final boolean required = pkg.requestedPermissionsRequired.get(i);
6823            final BasePermission bp = mSettings.mPermissions.get(name);
6824            if (DEBUG_INSTALL) {
6825                if (gp != ps) {
6826                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6827                }
6828            }
6829
6830            if (bp == null || bp.packageSetting == null) {
6831                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6832                    Slog.w(TAG, "Unknown permission " + name
6833                            + " in package " + pkg.packageName);
6834                }
6835                continue;
6836            }
6837
6838            final String perm = bp.name;
6839            boolean allowed;
6840            boolean allowedSig = false;
6841            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6842                // Keep track of app op permissions.
6843                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6844                if (pkgs == null) {
6845                    pkgs = new ArraySet<>();
6846                    mAppOpPermissionPackages.put(bp.name, pkgs);
6847                }
6848                pkgs.add(pkg.packageName);
6849            }
6850            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6851            if (level == PermissionInfo.PROTECTION_NORMAL
6852                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6853                // We grant a normal or dangerous permission if any of the following
6854                // are true:
6855                // 1) The permission is required
6856                // 2) The permission is optional, but was granted in the past
6857                // 3) The permission is optional, but was requested by an
6858                //    app in /system (not /data)
6859                //
6860                // Otherwise, reject the permission.
6861                allowed = (required || origPermissions.contains(perm)
6862                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6863            } else if (bp.packageSetting == null) {
6864                // This permission is invalid; skip it.
6865                allowed = false;
6866            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6867                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6868                if (allowed) {
6869                    allowedSig = true;
6870                }
6871            } else {
6872                allowed = false;
6873            }
6874            if (DEBUG_INSTALL) {
6875                if (gp != ps) {
6876                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6877                }
6878            }
6879            if (allowed) {
6880                if (!isSystemApp(ps) && ps.permissionsFixed) {
6881                    // If this is an existing, non-system package, then
6882                    // we can't add any new permissions to it.
6883                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6884                        // Except...  if this is a permission that was added
6885                        // to the platform (note: need to only do this when
6886                        // updating the platform).
6887                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6888                    }
6889                }
6890                if (allowed) {
6891                    if (!gp.grantedPermissions.contains(perm)) {
6892                        changedPermission = true;
6893                        gp.grantedPermissions.add(perm);
6894                        gp.gids = appendInts(gp.gids, bp.gids);
6895                    } else if (!ps.haveGids) {
6896                        gp.gids = appendInts(gp.gids, bp.gids);
6897                    }
6898                } else {
6899                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6900                        Slog.w(TAG, "Not granting permission " + perm
6901                                + " to package " + pkg.packageName
6902                                + " because it was previously installed without");
6903                    }
6904                }
6905            } else {
6906                if (gp.grantedPermissions.remove(perm)) {
6907                    changedPermission = true;
6908                    gp.gids = removeInts(gp.gids, bp.gids);
6909                    Slog.i(TAG, "Un-granting permission " + perm
6910                            + " from package " + pkg.packageName
6911                            + " (protectionLevel=" + bp.protectionLevel
6912                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6913                            + ")");
6914                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6915                    // Don't print warning for app op permissions, since it is fine for them
6916                    // not to be granted, there is a UI for the user to decide.
6917                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6918                        Slog.w(TAG, "Not granting permission " + perm
6919                                + " to package " + pkg.packageName
6920                                + " (protectionLevel=" + bp.protectionLevel
6921                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6922                                + ")");
6923                    }
6924                }
6925            }
6926        }
6927
6928        if ((changedPermission || replace) && !ps.permissionsFixed &&
6929                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6930            // This is the first that we have heard about this package, so the
6931            // permissions we have now selected are fixed until explicitly
6932            // changed.
6933            ps.permissionsFixed = true;
6934        }
6935        ps.haveGids = true;
6936    }
6937
6938    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6939        boolean allowed = false;
6940        final int NP = PackageParser.NEW_PERMISSIONS.length;
6941        for (int ip=0; ip<NP; ip++) {
6942            final PackageParser.NewPermissionInfo npi
6943                    = PackageParser.NEW_PERMISSIONS[ip];
6944            if (npi.name.equals(perm)
6945                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6946                allowed = true;
6947                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6948                        + pkg.packageName);
6949                break;
6950            }
6951        }
6952        return allowed;
6953    }
6954
6955    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6956                                          BasePermission bp, HashSet<String> origPermissions) {
6957        boolean allowed;
6958        allowed = (compareSignatures(
6959                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6960                        == PackageManager.SIGNATURE_MATCH)
6961                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6962                        == PackageManager.SIGNATURE_MATCH);
6963        if (!allowed && (bp.protectionLevel
6964                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6965            if (isSystemApp(pkg)) {
6966                // For updated system applications, a system permission
6967                // is granted only if it had been defined by the original application.
6968                if (isUpdatedSystemApp(pkg)) {
6969                    final PackageSetting sysPs = mSettings
6970                            .getDisabledSystemPkgLPr(pkg.packageName);
6971                    final GrantedPermissions origGp = sysPs.sharedUser != null
6972                            ? sysPs.sharedUser : sysPs;
6973
6974                    if (origGp.grantedPermissions.contains(perm)) {
6975                        // If the original was granted this permission, we take
6976                        // that grant decision as read and propagate it to the
6977                        // update.
6978                        allowed = true;
6979                    } else {
6980                        // The system apk may have been updated with an older
6981                        // version of the one on the data partition, but which
6982                        // granted a new system permission that it didn't have
6983                        // before.  In this case we do want to allow the app to
6984                        // now get the new permission if the ancestral apk is
6985                        // privileged to get it.
6986                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6987                            for (int j=0;
6988                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6989                                if (perm.equals(
6990                                        sysPs.pkg.requestedPermissions.get(j))) {
6991                                    allowed = true;
6992                                    break;
6993                                }
6994                            }
6995                        }
6996                    }
6997                } else {
6998                    allowed = isPrivilegedApp(pkg);
6999                }
7000            }
7001        }
7002        if (!allowed && (bp.protectionLevel
7003                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7004            // For development permissions, a development permission
7005            // is granted only if it was already granted.
7006            allowed = origPermissions.contains(perm);
7007        }
7008        return allowed;
7009    }
7010
7011    final class ActivityIntentResolver
7012            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7013        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7014                boolean defaultOnly, int userId) {
7015            if (!sUserManager.exists(userId)) return null;
7016            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7017            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7018        }
7019
7020        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7021                int userId) {
7022            if (!sUserManager.exists(userId)) return null;
7023            mFlags = flags;
7024            return super.queryIntent(intent, resolvedType,
7025                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7026        }
7027
7028        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7029                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7030            if (!sUserManager.exists(userId)) return null;
7031            if (packageActivities == null) {
7032                return null;
7033            }
7034            mFlags = flags;
7035            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7036            final int N = packageActivities.size();
7037            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7038                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7039
7040            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7041            for (int i = 0; i < N; ++i) {
7042                intentFilters = packageActivities.get(i).intents;
7043                if (intentFilters != null && intentFilters.size() > 0) {
7044                    PackageParser.ActivityIntentInfo[] array =
7045                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7046                    intentFilters.toArray(array);
7047                    listCut.add(array);
7048                }
7049            }
7050            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7051        }
7052
7053        public final void addActivity(PackageParser.Activity a, String type) {
7054            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7055            mActivities.put(a.getComponentName(), a);
7056            if (DEBUG_SHOW_INFO)
7057                Log.v(
7058                TAG, "  " + type + " " +
7059                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7060            if (DEBUG_SHOW_INFO)
7061                Log.v(TAG, "    Class=" + a.info.name);
7062            final int NI = a.intents.size();
7063            for (int j=0; j<NI; j++) {
7064                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7065                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7066                    intent.setPriority(0);
7067                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7068                            + a.className + " with priority > 0, forcing to 0");
7069                }
7070                if (DEBUG_SHOW_INFO) {
7071                    Log.v(TAG, "    IntentFilter:");
7072                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7073                }
7074                if (!intent.debugCheck()) {
7075                    Log.w(TAG, "==> For Activity " + a.info.name);
7076                }
7077                addFilter(intent);
7078            }
7079        }
7080
7081        public final void removeActivity(PackageParser.Activity a, String type) {
7082            mActivities.remove(a.getComponentName());
7083            if (DEBUG_SHOW_INFO) {
7084                Log.v(TAG, "  " + type + " "
7085                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7086                                : a.info.name) + ":");
7087                Log.v(TAG, "    Class=" + a.info.name);
7088            }
7089            final int NI = a.intents.size();
7090            for (int j=0; j<NI; j++) {
7091                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7092                if (DEBUG_SHOW_INFO) {
7093                    Log.v(TAG, "    IntentFilter:");
7094                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7095                }
7096                removeFilter(intent);
7097            }
7098        }
7099
7100        @Override
7101        protected boolean allowFilterResult(
7102                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7103            ActivityInfo filterAi = filter.activity.info;
7104            for (int i=dest.size()-1; i>=0; i--) {
7105                ActivityInfo destAi = dest.get(i).activityInfo;
7106                if (destAi.name == filterAi.name
7107                        && destAi.packageName == filterAi.packageName) {
7108                    return false;
7109                }
7110            }
7111            return true;
7112        }
7113
7114        @Override
7115        protected ActivityIntentInfo[] newArray(int size) {
7116            return new ActivityIntentInfo[size];
7117        }
7118
7119        @Override
7120        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7121            if (!sUserManager.exists(userId)) return true;
7122            PackageParser.Package p = filter.activity.owner;
7123            if (p != null) {
7124                PackageSetting ps = (PackageSetting)p.mExtras;
7125                if (ps != null) {
7126                    // System apps are never considered stopped for purposes of
7127                    // filtering, because there may be no way for the user to
7128                    // actually re-launch them.
7129                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7130                            && ps.getStopped(userId);
7131                }
7132            }
7133            return false;
7134        }
7135
7136        @Override
7137        protected boolean isPackageForFilter(String packageName,
7138                PackageParser.ActivityIntentInfo info) {
7139            return packageName.equals(info.activity.owner.packageName);
7140        }
7141
7142        @Override
7143        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7144                int match, int userId) {
7145            if (!sUserManager.exists(userId)) return null;
7146            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7147                return null;
7148            }
7149            final PackageParser.Activity activity = info.activity;
7150            if (mSafeMode && (activity.info.applicationInfo.flags
7151                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7152                return null;
7153            }
7154            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7155            if (ps == null) {
7156                return null;
7157            }
7158            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7159                    ps.readUserState(userId), userId);
7160            if (ai == null) {
7161                return null;
7162            }
7163            final ResolveInfo res = new ResolveInfo();
7164            res.activityInfo = ai;
7165            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7166                res.filter = info;
7167            }
7168            res.priority = info.getPriority();
7169            res.preferredOrder = activity.owner.mPreferredOrder;
7170            //System.out.println("Result: " + res.activityInfo.className +
7171            //                   " = " + res.priority);
7172            res.match = match;
7173            res.isDefault = info.hasDefault;
7174            res.labelRes = info.labelRes;
7175            res.nonLocalizedLabel = info.nonLocalizedLabel;
7176            if (userNeedsBadging(userId)) {
7177                res.noResourceId = true;
7178            } else {
7179                res.icon = info.icon;
7180            }
7181            res.system = isSystemApp(res.activityInfo.applicationInfo);
7182            return res;
7183        }
7184
7185        @Override
7186        protected void sortResults(List<ResolveInfo> results) {
7187            Collections.sort(results, mResolvePrioritySorter);
7188        }
7189
7190        @Override
7191        protected void dumpFilter(PrintWriter out, String prefix,
7192                PackageParser.ActivityIntentInfo filter) {
7193            out.print(prefix); out.print(
7194                    Integer.toHexString(System.identityHashCode(filter.activity)));
7195                    out.print(' ');
7196                    filter.activity.printComponentShortName(out);
7197                    out.print(" filter ");
7198                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7199        }
7200
7201//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7202//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7203//            final List<ResolveInfo> retList = Lists.newArrayList();
7204//            while (i.hasNext()) {
7205//                final ResolveInfo resolveInfo = i.next();
7206//                if (isEnabledLP(resolveInfo.activityInfo)) {
7207//                    retList.add(resolveInfo);
7208//                }
7209//            }
7210//            return retList;
7211//        }
7212
7213        // Keys are String (activity class name), values are Activity.
7214        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7215                = new HashMap<ComponentName, PackageParser.Activity>();
7216        private int mFlags;
7217    }
7218
7219    private final class ServiceIntentResolver
7220            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7221        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7222                boolean defaultOnly, int userId) {
7223            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7224            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7225        }
7226
7227        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7228                int userId) {
7229            if (!sUserManager.exists(userId)) return null;
7230            mFlags = flags;
7231            return super.queryIntent(intent, resolvedType,
7232                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7233        }
7234
7235        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7236                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7237            if (!sUserManager.exists(userId)) return null;
7238            if (packageServices == null) {
7239                return null;
7240            }
7241            mFlags = flags;
7242            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7243            final int N = packageServices.size();
7244            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7245                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7246
7247            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7248            for (int i = 0; i < N; ++i) {
7249                intentFilters = packageServices.get(i).intents;
7250                if (intentFilters != null && intentFilters.size() > 0) {
7251                    PackageParser.ServiceIntentInfo[] array =
7252                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7253                    intentFilters.toArray(array);
7254                    listCut.add(array);
7255                }
7256            }
7257            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7258        }
7259
7260        public final void addService(PackageParser.Service s) {
7261            mServices.put(s.getComponentName(), s);
7262            if (DEBUG_SHOW_INFO) {
7263                Log.v(TAG, "  "
7264                        + (s.info.nonLocalizedLabel != null
7265                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7266                Log.v(TAG, "    Class=" + s.info.name);
7267            }
7268            final int NI = s.intents.size();
7269            int j;
7270            for (j=0; j<NI; j++) {
7271                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7272                if (DEBUG_SHOW_INFO) {
7273                    Log.v(TAG, "    IntentFilter:");
7274                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7275                }
7276                if (!intent.debugCheck()) {
7277                    Log.w(TAG, "==> For Service " + s.info.name);
7278                }
7279                addFilter(intent);
7280            }
7281        }
7282
7283        public final void removeService(PackageParser.Service s) {
7284            mServices.remove(s.getComponentName());
7285            if (DEBUG_SHOW_INFO) {
7286                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7287                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7288                Log.v(TAG, "    Class=" + s.info.name);
7289            }
7290            final int NI = s.intents.size();
7291            int j;
7292            for (j=0; j<NI; j++) {
7293                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7294                if (DEBUG_SHOW_INFO) {
7295                    Log.v(TAG, "    IntentFilter:");
7296                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7297                }
7298                removeFilter(intent);
7299            }
7300        }
7301
7302        @Override
7303        protected boolean allowFilterResult(
7304                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7305            ServiceInfo filterSi = filter.service.info;
7306            for (int i=dest.size()-1; i>=0; i--) {
7307                ServiceInfo destAi = dest.get(i).serviceInfo;
7308                if (destAi.name == filterSi.name
7309                        && destAi.packageName == filterSi.packageName) {
7310                    return false;
7311                }
7312            }
7313            return true;
7314        }
7315
7316        @Override
7317        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7318            return new PackageParser.ServiceIntentInfo[size];
7319        }
7320
7321        @Override
7322        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7323            if (!sUserManager.exists(userId)) return true;
7324            PackageParser.Package p = filter.service.owner;
7325            if (p != null) {
7326                PackageSetting ps = (PackageSetting)p.mExtras;
7327                if (ps != null) {
7328                    // System apps are never considered stopped for purposes of
7329                    // filtering, because there may be no way for the user to
7330                    // actually re-launch them.
7331                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7332                            && ps.getStopped(userId);
7333                }
7334            }
7335            return false;
7336        }
7337
7338        @Override
7339        protected boolean isPackageForFilter(String packageName,
7340                PackageParser.ServiceIntentInfo info) {
7341            return packageName.equals(info.service.owner.packageName);
7342        }
7343
7344        @Override
7345        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7346                int match, int userId) {
7347            if (!sUserManager.exists(userId)) return null;
7348            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7349            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7350                return null;
7351            }
7352            final PackageParser.Service service = info.service;
7353            if (mSafeMode && (service.info.applicationInfo.flags
7354                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7355                return null;
7356            }
7357            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7358            if (ps == null) {
7359                return null;
7360            }
7361            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7362                    ps.readUserState(userId), userId);
7363            if (si == null) {
7364                return null;
7365            }
7366            final ResolveInfo res = new ResolveInfo();
7367            res.serviceInfo = si;
7368            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7369                res.filter = filter;
7370            }
7371            res.priority = info.getPriority();
7372            res.preferredOrder = service.owner.mPreferredOrder;
7373            //System.out.println("Result: " + res.activityInfo.className +
7374            //                   " = " + res.priority);
7375            res.match = match;
7376            res.isDefault = info.hasDefault;
7377            res.labelRes = info.labelRes;
7378            res.nonLocalizedLabel = info.nonLocalizedLabel;
7379            res.icon = info.icon;
7380            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7381            return res;
7382        }
7383
7384        @Override
7385        protected void sortResults(List<ResolveInfo> results) {
7386            Collections.sort(results, mResolvePrioritySorter);
7387        }
7388
7389        @Override
7390        protected void dumpFilter(PrintWriter out, String prefix,
7391                PackageParser.ServiceIntentInfo filter) {
7392            out.print(prefix); out.print(
7393                    Integer.toHexString(System.identityHashCode(filter.service)));
7394                    out.print(' ');
7395                    filter.service.printComponentShortName(out);
7396                    out.print(" filter ");
7397                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7398        }
7399
7400//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7401//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7402//            final List<ResolveInfo> retList = Lists.newArrayList();
7403//            while (i.hasNext()) {
7404//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7405//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7406//                    retList.add(resolveInfo);
7407//                }
7408//            }
7409//            return retList;
7410//        }
7411
7412        // Keys are String (activity class name), values are Activity.
7413        private final HashMap<ComponentName, PackageParser.Service> mServices
7414                = new HashMap<ComponentName, PackageParser.Service>();
7415        private int mFlags;
7416    };
7417
7418    private final class ProviderIntentResolver
7419            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7420        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7421                boolean defaultOnly, int userId) {
7422            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7423            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7424        }
7425
7426        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7427                int userId) {
7428            if (!sUserManager.exists(userId))
7429                return null;
7430            mFlags = flags;
7431            return super.queryIntent(intent, resolvedType,
7432                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7433        }
7434
7435        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7436                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7437            if (!sUserManager.exists(userId))
7438                return null;
7439            if (packageProviders == null) {
7440                return null;
7441            }
7442            mFlags = flags;
7443            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7444            final int N = packageProviders.size();
7445            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7446                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7447
7448            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7449            for (int i = 0; i < N; ++i) {
7450                intentFilters = packageProviders.get(i).intents;
7451                if (intentFilters != null && intentFilters.size() > 0) {
7452                    PackageParser.ProviderIntentInfo[] array =
7453                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7454                    intentFilters.toArray(array);
7455                    listCut.add(array);
7456                }
7457            }
7458            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7459        }
7460
7461        public final void addProvider(PackageParser.Provider p) {
7462            if (mProviders.containsKey(p.getComponentName())) {
7463                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7464                return;
7465            }
7466
7467            mProviders.put(p.getComponentName(), p);
7468            if (DEBUG_SHOW_INFO) {
7469                Log.v(TAG, "  "
7470                        + (p.info.nonLocalizedLabel != null
7471                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7472                Log.v(TAG, "    Class=" + p.info.name);
7473            }
7474            final int NI = p.intents.size();
7475            int j;
7476            for (j = 0; j < NI; j++) {
7477                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7478                if (DEBUG_SHOW_INFO) {
7479                    Log.v(TAG, "    IntentFilter:");
7480                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7481                }
7482                if (!intent.debugCheck()) {
7483                    Log.w(TAG, "==> For Provider " + p.info.name);
7484                }
7485                addFilter(intent);
7486            }
7487        }
7488
7489        public final void removeProvider(PackageParser.Provider p) {
7490            mProviders.remove(p.getComponentName());
7491            if (DEBUG_SHOW_INFO) {
7492                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7493                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7494                Log.v(TAG, "    Class=" + p.info.name);
7495            }
7496            final int NI = p.intents.size();
7497            int j;
7498            for (j = 0; j < NI; j++) {
7499                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7500                if (DEBUG_SHOW_INFO) {
7501                    Log.v(TAG, "    IntentFilter:");
7502                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7503                }
7504                removeFilter(intent);
7505            }
7506        }
7507
7508        @Override
7509        protected boolean allowFilterResult(
7510                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7511            ProviderInfo filterPi = filter.provider.info;
7512            for (int i = dest.size() - 1; i >= 0; i--) {
7513                ProviderInfo destPi = dest.get(i).providerInfo;
7514                if (destPi.name == filterPi.name
7515                        && destPi.packageName == filterPi.packageName) {
7516                    return false;
7517                }
7518            }
7519            return true;
7520        }
7521
7522        @Override
7523        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7524            return new PackageParser.ProviderIntentInfo[size];
7525        }
7526
7527        @Override
7528        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7529            if (!sUserManager.exists(userId))
7530                return true;
7531            PackageParser.Package p = filter.provider.owner;
7532            if (p != null) {
7533                PackageSetting ps = (PackageSetting) p.mExtras;
7534                if (ps != null) {
7535                    // System apps are never considered stopped for purposes of
7536                    // filtering, because there may be no way for the user to
7537                    // actually re-launch them.
7538                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7539                            && ps.getStopped(userId);
7540                }
7541            }
7542            return false;
7543        }
7544
7545        @Override
7546        protected boolean isPackageForFilter(String packageName,
7547                PackageParser.ProviderIntentInfo info) {
7548            return packageName.equals(info.provider.owner.packageName);
7549        }
7550
7551        @Override
7552        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7553                int match, int userId) {
7554            if (!sUserManager.exists(userId))
7555                return null;
7556            final PackageParser.ProviderIntentInfo info = filter;
7557            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7558                return null;
7559            }
7560            final PackageParser.Provider provider = info.provider;
7561            if (mSafeMode && (provider.info.applicationInfo.flags
7562                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7563                return null;
7564            }
7565            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7566            if (ps == null) {
7567                return null;
7568            }
7569            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7570                    ps.readUserState(userId), userId);
7571            if (pi == null) {
7572                return null;
7573            }
7574            final ResolveInfo res = new ResolveInfo();
7575            res.providerInfo = pi;
7576            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7577                res.filter = filter;
7578            }
7579            res.priority = info.getPriority();
7580            res.preferredOrder = provider.owner.mPreferredOrder;
7581            res.match = match;
7582            res.isDefault = info.hasDefault;
7583            res.labelRes = info.labelRes;
7584            res.nonLocalizedLabel = info.nonLocalizedLabel;
7585            res.icon = info.icon;
7586            res.system = isSystemApp(res.providerInfo.applicationInfo);
7587            return res;
7588        }
7589
7590        @Override
7591        protected void sortResults(List<ResolveInfo> results) {
7592            Collections.sort(results, mResolvePrioritySorter);
7593        }
7594
7595        @Override
7596        protected void dumpFilter(PrintWriter out, String prefix,
7597                PackageParser.ProviderIntentInfo filter) {
7598            out.print(prefix);
7599            out.print(
7600                    Integer.toHexString(System.identityHashCode(filter.provider)));
7601            out.print(' ');
7602            filter.provider.printComponentShortName(out);
7603            out.print(" filter ");
7604            out.println(Integer.toHexString(System.identityHashCode(filter)));
7605        }
7606
7607        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7608                = new HashMap<ComponentName, PackageParser.Provider>();
7609        private int mFlags;
7610    };
7611
7612    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7613            new Comparator<ResolveInfo>() {
7614        public int compare(ResolveInfo r1, ResolveInfo r2) {
7615            int v1 = r1.priority;
7616            int v2 = r2.priority;
7617            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7618            if (v1 != v2) {
7619                return (v1 > v2) ? -1 : 1;
7620            }
7621            v1 = r1.preferredOrder;
7622            v2 = r2.preferredOrder;
7623            if (v1 != v2) {
7624                return (v1 > v2) ? -1 : 1;
7625            }
7626            if (r1.isDefault != r2.isDefault) {
7627                return r1.isDefault ? -1 : 1;
7628            }
7629            v1 = r1.match;
7630            v2 = r2.match;
7631            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7632            if (v1 != v2) {
7633                return (v1 > v2) ? -1 : 1;
7634            }
7635            if (r1.system != r2.system) {
7636                return r1.system ? -1 : 1;
7637            }
7638            return 0;
7639        }
7640    };
7641
7642    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7643            new Comparator<ProviderInfo>() {
7644        public int compare(ProviderInfo p1, ProviderInfo p2) {
7645            final int v1 = p1.initOrder;
7646            final int v2 = p2.initOrder;
7647            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7648        }
7649    };
7650
7651    static final void sendPackageBroadcast(String action, String pkg,
7652            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7653            int[] userIds) {
7654        IActivityManager am = ActivityManagerNative.getDefault();
7655        if (am != null) {
7656            try {
7657                if (userIds == null) {
7658                    userIds = am.getRunningUserIds();
7659                }
7660                for (int id : userIds) {
7661                    final Intent intent = new Intent(action,
7662                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7663                    if (extras != null) {
7664                        intent.putExtras(extras);
7665                    }
7666                    if (targetPkg != null) {
7667                        intent.setPackage(targetPkg);
7668                    }
7669                    // Modify the UID when posting to other users
7670                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7671                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7672                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7673                        intent.putExtra(Intent.EXTRA_UID, uid);
7674                    }
7675                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7676                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7677                    if (DEBUG_BROADCASTS) {
7678                        RuntimeException here = new RuntimeException("here");
7679                        here.fillInStackTrace();
7680                        Slog.d(TAG, "Sending to user " + id + ": "
7681                                + intent.toShortString(false, true, false, false)
7682                                + " " + intent.getExtras(), here);
7683                    }
7684                    am.broadcastIntent(null, intent, null, finishedReceiver,
7685                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7686                            finishedReceiver != null, false, id);
7687                }
7688            } catch (RemoteException ex) {
7689            }
7690        }
7691    }
7692
7693    /**
7694     * Check if the external storage media is available. This is true if there
7695     * is a mounted external storage medium or if the external storage is
7696     * emulated.
7697     */
7698    private boolean isExternalMediaAvailable() {
7699        return mMediaMounted || Environment.isExternalStorageEmulated();
7700    }
7701
7702    @Override
7703    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7704        // writer
7705        synchronized (mPackages) {
7706            if (!isExternalMediaAvailable()) {
7707                // If the external storage is no longer mounted at this point,
7708                // the caller may not have been able to delete all of this
7709                // packages files and can not delete any more.  Bail.
7710                return null;
7711            }
7712            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7713            if (lastPackage != null) {
7714                pkgs.remove(lastPackage);
7715            }
7716            if (pkgs.size() > 0) {
7717                return pkgs.get(0);
7718            }
7719        }
7720        return null;
7721    }
7722
7723    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7724        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7725                userId, andCode ? 1 : 0, packageName);
7726        if (mSystemReady) {
7727            msg.sendToTarget();
7728        } else {
7729            if (mPostSystemReadyMessages == null) {
7730                mPostSystemReadyMessages = new ArrayList<>();
7731            }
7732            mPostSystemReadyMessages.add(msg);
7733        }
7734    }
7735
7736    void startCleaningPackages() {
7737        // reader
7738        synchronized (mPackages) {
7739            if (!isExternalMediaAvailable()) {
7740                return;
7741            }
7742            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7743                return;
7744            }
7745        }
7746        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7747        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7748        IActivityManager am = ActivityManagerNative.getDefault();
7749        if (am != null) {
7750            try {
7751                am.startService(null, intent, null, UserHandle.USER_OWNER);
7752            } catch (RemoteException e) {
7753            }
7754        }
7755    }
7756
7757    @Override
7758    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7759            int installFlags, String installerPackageName, VerificationParams verificationParams,
7760            String packageAbiOverride) {
7761        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7762                packageAbiOverride, UserHandle.getCallingUserId());
7763    }
7764
7765    @Override
7766    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7767            int installFlags, String installerPackageName, VerificationParams verificationParams,
7768            String packageAbiOverride, int userId) {
7769        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7770
7771        final int callingUid = Binder.getCallingUid();
7772        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7773
7774        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7775            try {
7776                if (observer != null) {
7777                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7778                }
7779            } catch (RemoteException re) {
7780            }
7781            return;
7782        }
7783
7784        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7785            installFlags |= PackageManager.INSTALL_FROM_ADB;
7786
7787        } else {
7788            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7789            // about installerPackageName.
7790
7791            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7792            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7793        }
7794
7795        UserHandle user;
7796        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7797            user = UserHandle.ALL;
7798        } else {
7799            user = new UserHandle(userId);
7800        }
7801
7802        verificationParams.setInstallerUid(callingUid);
7803
7804        final File originFile = new File(originPath);
7805        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7806
7807        final Message msg = mHandler.obtainMessage(INIT_COPY);
7808        msg.obj = new InstallParams(origin, observer, installFlags,
7809                installerPackageName, verificationParams, user, packageAbiOverride);
7810        mHandler.sendMessage(msg);
7811    }
7812
7813    void installStage(String packageName, File stagedDir, String stagedCid,
7814            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7815            String installerPackageName, int installerUid, UserHandle user) {
7816        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7817                params.referrerUri, installerUid, null);
7818
7819        final OriginInfo origin;
7820        if (stagedDir != null) {
7821            origin = OriginInfo.fromStagedFile(stagedDir);
7822        } else {
7823            origin = OriginInfo.fromStagedContainer(stagedCid);
7824        }
7825
7826        final Message msg = mHandler.obtainMessage(INIT_COPY);
7827        msg.obj = new InstallParams(origin, observer, params.installFlags,
7828                installerPackageName, verifParams, user, params.abiOverride);
7829        mHandler.sendMessage(msg);
7830    }
7831
7832    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7833        Bundle extras = new Bundle(1);
7834        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7835
7836        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7837                packageName, extras, null, null, new int[] {userId});
7838        try {
7839            IActivityManager am = ActivityManagerNative.getDefault();
7840            final boolean isSystem =
7841                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7842            if (isSystem && am.isUserRunning(userId, false)) {
7843                // The just-installed/enabled app is bundled on the system, so presumed
7844                // to be able to run automatically without needing an explicit launch.
7845                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7846                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7847                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7848                        .setPackage(packageName);
7849                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7850                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7851            }
7852        } catch (RemoteException e) {
7853            // shouldn't happen
7854            Slog.w(TAG, "Unable to bootstrap installed package", e);
7855        }
7856    }
7857
7858    @Override
7859    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7860            int userId) {
7861        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7862        PackageSetting pkgSetting;
7863        final int uid = Binder.getCallingUid();
7864        enforceCrossUserPermission(uid, userId, true, true,
7865                "setApplicationHiddenSetting for user " + userId);
7866
7867        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7868            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7869            return false;
7870        }
7871
7872        long callingId = Binder.clearCallingIdentity();
7873        try {
7874            boolean sendAdded = false;
7875            boolean sendRemoved = false;
7876            // writer
7877            synchronized (mPackages) {
7878                pkgSetting = mSettings.mPackages.get(packageName);
7879                if (pkgSetting == null) {
7880                    return false;
7881                }
7882                if (pkgSetting.getHidden(userId) != hidden) {
7883                    pkgSetting.setHidden(hidden, userId);
7884                    mSettings.writePackageRestrictionsLPr(userId);
7885                    if (hidden) {
7886                        sendRemoved = true;
7887                    } else {
7888                        sendAdded = true;
7889                    }
7890                }
7891            }
7892            if (sendAdded) {
7893                sendPackageAddedForUser(packageName, pkgSetting, userId);
7894                return true;
7895            }
7896            if (sendRemoved) {
7897                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7898                        "hiding pkg");
7899                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7900            }
7901        } finally {
7902            Binder.restoreCallingIdentity(callingId);
7903        }
7904        return false;
7905    }
7906
7907    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7908            int userId) {
7909        final PackageRemovedInfo info = new PackageRemovedInfo();
7910        info.removedPackage = packageName;
7911        info.removedUsers = new int[] {userId};
7912        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7913        info.sendBroadcast(false, false, false);
7914    }
7915
7916    /**
7917     * Returns true if application is not found or there was an error. Otherwise it returns
7918     * the hidden state of the package for the given user.
7919     */
7920    @Override
7921    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7922        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7923        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7924                false, "getApplicationHidden for user " + userId);
7925        PackageSetting pkgSetting;
7926        long callingId = Binder.clearCallingIdentity();
7927        try {
7928            // writer
7929            synchronized (mPackages) {
7930                pkgSetting = mSettings.mPackages.get(packageName);
7931                if (pkgSetting == null) {
7932                    return true;
7933                }
7934                return pkgSetting.getHidden(userId);
7935            }
7936        } finally {
7937            Binder.restoreCallingIdentity(callingId);
7938        }
7939    }
7940
7941    /**
7942     * @hide
7943     */
7944    @Override
7945    public int installExistingPackageAsUser(String packageName, int userId) {
7946        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7947                null);
7948        PackageSetting pkgSetting;
7949        final int uid = Binder.getCallingUid();
7950        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7951                + userId);
7952        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7953            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7954        }
7955
7956        long callingId = Binder.clearCallingIdentity();
7957        try {
7958            boolean sendAdded = false;
7959            Bundle extras = new Bundle(1);
7960
7961            // writer
7962            synchronized (mPackages) {
7963                pkgSetting = mSettings.mPackages.get(packageName);
7964                if (pkgSetting == null) {
7965                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7966                }
7967                if (!pkgSetting.getInstalled(userId)) {
7968                    pkgSetting.setInstalled(true, userId);
7969                    pkgSetting.setHidden(false, userId);
7970                    mSettings.writePackageRestrictionsLPr(userId);
7971                    sendAdded = true;
7972                }
7973            }
7974
7975            if (sendAdded) {
7976                sendPackageAddedForUser(packageName, pkgSetting, userId);
7977            }
7978        } finally {
7979            Binder.restoreCallingIdentity(callingId);
7980        }
7981
7982        return PackageManager.INSTALL_SUCCEEDED;
7983    }
7984
7985    boolean isUserRestricted(int userId, String restrictionKey) {
7986        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7987        if (restrictions.getBoolean(restrictionKey, false)) {
7988            Log.w(TAG, "User is restricted: " + restrictionKey);
7989            return true;
7990        }
7991        return false;
7992    }
7993
7994    @Override
7995    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7996        mContext.enforceCallingOrSelfPermission(
7997                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7998                "Only package verification agents can verify applications");
7999
8000        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8001        final PackageVerificationResponse response = new PackageVerificationResponse(
8002                verificationCode, Binder.getCallingUid());
8003        msg.arg1 = id;
8004        msg.obj = response;
8005        mHandler.sendMessage(msg);
8006    }
8007
8008    @Override
8009    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8010            long millisecondsToDelay) {
8011        mContext.enforceCallingOrSelfPermission(
8012                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8013                "Only package verification agents can extend verification timeouts");
8014
8015        final PackageVerificationState state = mPendingVerification.get(id);
8016        final PackageVerificationResponse response = new PackageVerificationResponse(
8017                verificationCodeAtTimeout, Binder.getCallingUid());
8018
8019        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8020            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8021        }
8022        if (millisecondsToDelay < 0) {
8023            millisecondsToDelay = 0;
8024        }
8025        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8026                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8027            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8028        }
8029
8030        if ((state != null) && !state.timeoutExtended()) {
8031            state.extendTimeout();
8032
8033            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8034            msg.arg1 = id;
8035            msg.obj = response;
8036            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8037        }
8038    }
8039
8040    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8041            int verificationCode, UserHandle user) {
8042        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8043        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8044        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8045        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8046        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8047
8048        mContext.sendBroadcastAsUser(intent, user,
8049                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8050    }
8051
8052    private ComponentName matchComponentForVerifier(String packageName,
8053            List<ResolveInfo> receivers) {
8054        ActivityInfo targetReceiver = null;
8055
8056        final int NR = receivers.size();
8057        for (int i = 0; i < NR; i++) {
8058            final ResolveInfo info = receivers.get(i);
8059            if (info.activityInfo == null) {
8060                continue;
8061            }
8062
8063            if (packageName.equals(info.activityInfo.packageName)) {
8064                targetReceiver = info.activityInfo;
8065                break;
8066            }
8067        }
8068
8069        if (targetReceiver == null) {
8070            return null;
8071        }
8072
8073        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8074    }
8075
8076    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8077            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8078        if (pkgInfo.verifiers.length == 0) {
8079            return null;
8080        }
8081
8082        final int N = pkgInfo.verifiers.length;
8083        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8084        for (int i = 0; i < N; i++) {
8085            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8086
8087            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8088                    receivers);
8089            if (comp == null) {
8090                continue;
8091            }
8092
8093            final int verifierUid = getUidForVerifier(verifierInfo);
8094            if (verifierUid == -1) {
8095                continue;
8096            }
8097
8098            if (DEBUG_VERIFY) {
8099                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8100                        + " with the correct signature");
8101            }
8102            sufficientVerifiers.add(comp);
8103            verificationState.addSufficientVerifier(verifierUid);
8104        }
8105
8106        return sufficientVerifiers;
8107    }
8108
8109    private int getUidForVerifier(VerifierInfo verifierInfo) {
8110        synchronized (mPackages) {
8111            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8112            if (pkg == null) {
8113                return -1;
8114            } else if (pkg.mSignatures.length != 1) {
8115                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8116                        + " has more than one signature; ignoring");
8117                return -1;
8118            }
8119
8120            /*
8121             * If the public key of the package's signature does not match
8122             * our expected public key, then this is a different package and
8123             * we should skip.
8124             */
8125
8126            final byte[] expectedPublicKey;
8127            try {
8128                final Signature verifierSig = pkg.mSignatures[0];
8129                final PublicKey publicKey = verifierSig.getPublicKey();
8130                expectedPublicKey = publicKey.getEncoded();
8131            } catch (CertificateException e) {
8132                return -1;
8133            }
8134
8135            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8136
8137            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8138                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8139                        + " does not have the expected public key; ignoring");
8140                return -1;
8141            }
8142
8143            return pkg.applicationInfo.uid;
8144        }
8145    }
8146
8147    @Override
8148    public void finishPackageInstall(int token) {
8149        enforceSystemOrRoot("Only the system is allowed to finish installs");
8150
8151        if (DEBUG_INSTALL) {
8152            Slog.v(TAG, "BM finishing package install for " + token);
8153        }
8154
8155        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8156        mHandler.sendMessage(msg);
8157    }
8158
8159    /**
8160     * Get the verification agent timeout.
8161     *
8162     * @return verification timeout in milliseconds
8163     */
8164    private long getVerificationTimeout() {
8165        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8166                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8167                DEFAULT_VERIFICATION_TIMEOUT);
8168    }
8169
8170    /**
8171     * Get the default verification agent response code.
8172     *
8173     * @return default verification response code
8174     */
8175    private int getDefaultVerificationResponse() {
8176        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8177                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8178                DEFAULT_VERIFICATION_RESPONSE);
8179    }
8180
8181    /**
8182     * Check whether or not package verification has been enabled.
8183     *
8184     * @return true if verification should be performed
8185     */
8186    private boolean isVerificationEnabled(int userId, int installFlags) {
8187        if (!DEFAULT_VERIFY_ENABLE) {
8188            return false;
8189        }
8190
8191        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8192
8193        // Check if installing from ADB
8194        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8195            // Do not run verification in a test harness environment
8196            if (ActivityManager.isRunningInTestHarness()) {
8197                return false;
8198            }
8199            if (ensureVerifyAppsEnabled) {
8200                return true;
8201            }
8202            // Check if the developer does not want package verification for ADB installs
8203            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8204                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8205                return false;
8206            }
8207        }
8208
8209        if (ensureVerifyAppsEnabled) {
8210            return true;
8211        }
8212
8213        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8214                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8215    }
8216
8217    /**
8218     * Get the "allow unknown sources" setting.
8219     *
8220     * @return the current "allow unknown sources" setting
8221     */
8222    private int getUnknownSourcesSettings() {
8223        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8224                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8225                -1);
8226    }
8227
8228    @Override
8229    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8230        final int uid = Binder.getCallingUid();
8231        // writer
8232        synchronized (mPackages) {
8233            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8234            if (targetPackageSetting == null) {
8235                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8236            }
8237
8238            PackageSetting installerPackageSetting;
8239            if (installerPackageName != null) {
8240                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8241                if (installerPackageSetting == null) {
8242                    throw new IllegalArgumentException("Unknown installer package: "
8243                            + installerPackageName);
8244                }
8245            } else {
8246                installerPackageSetting = null;
8247            }
8248
8249            Signature[] callerSignature;
8250            Object obj = mSettings.getUserIdLPr(uid);
8251            if (obj != null) {
8252                if (obj instanceof SharedUserSetting) {
8253                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8254                } else if (obj instanceof PackageSetting) {
8255                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8256                } else {
8257                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8258                }
8259            } else {
8260                throw new SecurityException("Unknown calling uid " + uid);
8261            }
8262
8263            // Verify: can't set installerPackageName to a package that is
8264            // not signed with the same cert as the caller.
8265            if (installerPackageSetting != null) {
8266                if (compareSignatures(callerSignature,
8267                        installerPackageSetting.signatures.mSignatures)
8268                        != PackageManager.SIGNATURE_MATCH) {
8269                    throw new SecurityException(
8270                            "Caller does not have same cert as new installer package "
8271                            + installerPackageName);
8272                }
8273            }
8274
8275            // Verify: if target already has an installer package, it must
8276            // be signed with the same cert as the caller.
8277            if (targetPackageSetting.installerPackageName != null) {
8278                PackageSetting setting = mSettings.mPackages.get(
8279                        targetPackageSetting.installerPackageName);
8280                // If the currently set package isn't valid, then it's always
8281                // okay to change it.
8282                if (setting != null) {
8283                    if (compareSignatures(callerSignature,
8284                            setting.signatures.mSignatures)
8285                            != PackageManager.SIGNATURE_MATCH) {
8286                        throw new SecurityException(
8287                                "Caller does not have same cert as old installer package "
8288                                + targetPackageSetting.installerPackageName);
8289                    }
8290                }
8291            }
8292
8293            // Okay!
8294            targetPackageSetting.installerPackageName = installerPackageName;
8295            scheduleWriteSettingsLocked();
8296        }
8297    }
8298
8299    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8300        // Queue up an async operation since the package installation may take a little while.
8301        mHandler.post(new Runnable() {
8302            public void run() {
8303                mHandler.removeCallbacks(this);
8304                 // Result object to be returned
8305                PackageInstalledInfo res = new PackageInstalledInfo();
8306                res.returnCode = currentStatus;
8307                res.uid = -1;
8308                res.pkg = null;
8309                res.removedInfo = new PackageRemovedInfo();
8310                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8311                    args.doPreInstall(res.returnCode);
8312                    synchronized (mInstallLock) {
8313                        installPackageLI(args, res);
8314                    }
8315                    args.doPostInstall(res.returnCode, res.uid);
8316                }
8317
8318                // A restore should be performed at this point if (a) the install
8319                // succeeded, (b) the operation is not an update, and (c) the new
8320                // package has not opted out of backup participation.
8321                final boolean update = res.removedInfo.removedPackage != null;
8322                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8323                boolean doRestore = !update
8324                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8325
8326                // Set up the post-install work request bookkeeping.  This will be used
8327                // and cleaned up by the post-install event handling regardless of whether
8328                // there's a restore pass performed.  Token values are >= 1.
8329                int token;
8330                if (mNextInstallToken < 0) mNextInstallToken = 1;
8331                token = mNextInstallToken++;
8332
8333                PostInstallData data = new PostInstallData(args, res);
8334                mRunningInstalls.put(token, data);
8335                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8336
8337                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8338                    // Pass responsibility to the Backup Manager.  It will perform a
8339                    // restore if appropriate, then pass responsibility back to the
8340                    // Package Manager to run the post-install observer callbacks
8341                    // and broadcasts.
8342                    IBackupManager bm = IBackupManager.Stub.asInterface(
8343                            ServiceManager.getService(Context.BACKUP_SERVICE));
8344                    if (bm != null) {
8345                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8346                                + " to BM for possible restore");
8347                        try {
8348                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8349                        } catch (RemoteException e) {
8350                            // can't happen; the backup manager is local
8351                        } catch (Exception e) {
8352                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8353                            doRestore = false;
8354                        }
8355                    } else {
8356                        Slog.e(TAG, "Backup Manager not found!");
8357                        doRestore = false;
8358                    }
8359                }
8360
8361                if (!doRestore) {
8362                    // No restore possible, or the Backup Manager was mysteriously not
8363                    // available -- just fire the post-install work request directly.
8364                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8365                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8366                    mHandler.sendMessage(msg);
8367                }
8368            }
8369        });
8370    }
8371
8372    private abstract class HandlerParams {
8373        private static final int MAX_RETRIES = 4;
8374
8375        /**
8376         * Number of times startCopy() has been attempted and had a non-fatal
8377         * error.
8378         */
8379        private int mRetries = 0;
8380
8381        /** User handle for the user requesting the information or installation. */
8382        private final UserHandle mUser;
8383
8384        HandlerParams(UserHandle user) {
8385            mUser = user;
8386        }
8387
8388        UserHandle getUser() {
8389            return mUser;
8390        }
8391
8392        final boolean startCopy() {
8393            boolean res;
8394            try {
8395                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8396
8397                if (++mRetries > MAX_RETRIES) {
8398                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8399                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8400                    handleServiceError();
8401                    return false;
8402                } else {
8403                    handleStartCopy();
8404                    res = true;
8405                }
8406            } catch (RemoteException e) {
8407                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8408                mHandler.sendEmptyMessage(MCS_RECONNECT);
8409                res = false;
8410            }
8411            handleReturnCode();
8412            return res;
8413        }
8414
8415        final void serviceError() {
8416            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8417            handleServiceError();
8418            handleReturnCode();
8419        }
8420
8421        abstract void handleStartCopy() throws RemoteException;
8422        abstract void handleServiceError();
8423        abstract void handleReturnCode();
8424    }
8425
8426    class MeasureParams extends HandlerParams {
8427        private final PackageStats mStats;
8428        private boolean mSuccess;
8429
8430        private final IPackageStatsObserver mObserver;
8431
8432        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8433            super(new UserHandle(stats.userHandle));
8434            mObserver = observer;
8435            mStats = stats;
8436        }
8437
8438        @Override
8439        public String toString() {
8440            return "MeasureParams{"
8441                + Integer.toHexString(System.identityHashCode(this))
8442                + " " + mStats.packageName + "}";
8443        }
8444
8445        @Override
8446        void handleStartCopy() throws RemoteException {
8447            synchronized (mInstallLock) {
8448                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8449            }
8450
8451            if (mSuccess) {
8452                final boolean mounted;
8453                if (Environment.isExternalStorageEmulated()) {
8454                    mounted = true;
8455                } else {
8456                    final String status = Environment.getExternalStorageState();
8457                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8458                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8459                }
8460
8461                if (mounted) {
8462                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8463
8464                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8465                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8466
8467                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8468                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8469
8470                    // Always subtract cache size, since it's a subdirectory
8471                    mStats.externalDataSize -= mStats.externalCacheSize;
8472
8473                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8474                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8475
8476                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8477                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8478                }
8479            }
8480        }
8481
8482        @Override
8483        void handleReturnCode() {
8484            if (mObserver != null) {
8485                try {
8486                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8487                } catch (RemoteException e) {
8488                    Slog.i(TAG, "Observer no longer exists.");
8489                }
8490            }
8491        }
8492
8493        @Override
8494        void handleServiceError() {
8495            Slog.e(TAG, "Could not measure application " + mStats.packageName
8496                            + " external storage");
8497        }
8498    }
8499
8500    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8501            throws RemoteException {
8502        long result = 0;
8503        for (File path : paths) {
8504            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8505        }
8506        return result;
8507    }
8508
8509    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8510        for (File path : paths) {
8511            try {
8512                mcs.clearDirectory(path.getAbsolutePath());
8513            } catch (RemoteException e) {
8514            }
8515        }
8516    }
8517
8518    static class OriginInfo {
8519        /**
8520         * Location where install is coming from, before it has been
8521         * copied/renamed into place. This could be a single monolithic APK
8522         * file, or a cluster directory. This location may be untrusted.
8523         */
8524        final File file;
8525        final String cid;
8526
8527        /**
8528         * Flag indicating that {@link #file} or {@link #cid} has already been
8529         * staged, meaning downstream users don't need to defensively copy the
8530         * contents.
8531         */
8532        final boolean staged;
8533
8534        /**
8535         * Flag indicating that {@link #file} or {@link #cid} is an already
8536         * installed app that is being moved.
8537         */
8538        final boolean existing;
8539
8540        final String resolvedPath;
8541        final File resolvedFile;
8542
8543        static OriginInfo fromNothing() {
8544            return new OriginInfo(null, null, false, false);
8545        }
8546
8547        static OriginInfo fromUntrustedFile(File file) {
8548            return new OriginInfo(file, null, false, false);
8549        }
8550
8551        static OriginInfo fromExistingFile(File file) {
8552            return new OriginInfo(file, null, false, true);
8553        }
8554
8555        static OriginInfo fromStagedFile(File file) {
8556            return new OriginInfo(file, null, true, false);
8557        }
8558
8559        static OriginInfo fromStagedContainer(String cid) {
8560            return new OriginInfo(null, cid, true, false);
8561        }
8562
8563        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8564            this.file = file;
8565            this.cid = cid;
8566            this.staged = staged;
8567            this.existing = existing;
8568
8569            if (cid != null) {
8570                resolvedPath = PackageHelper.getSdDir(cid);
8571                resolvedFile = new File(resolvedPath);
8572            } else if (file != null) {
8573                resolvedPath = file.getAbsolutePath();
8574                resolvedFile = file;
8575            } else {
8576                resolvedPath = null;
8577                resolvedFile = null;
8578            }
8579        }
8580    }
8581
8582    class InstallParams extends HandlerParams {
8583        final OriginInfo origin;
8584        final IPackageInstallObserver2 observer;
8585        int installFlags;
8586        final String installerPackageName;
8587        final VerificationParams verificationParams;
8588        private InstallArgs mArgs;
8589        private int mRet;
8590        final String packageAbiOverride;
8591
8592        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8593                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8594                String packageAbiOverride) {
8595            super(user);
8596            this.origin = origin;
8597            this.observer = observer;
8598            this.installFlags = installFlags;
8599            this.installerPackageName = installerPackageName;
8600            this.verificationParams = verificationParams;
8601            this.packageAbiOverride = packageAbiOverride;
8602        }
8603
8604        @Override
8605        public String toString() {
8606            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8607                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8608        }
8609
8610        public ManifestDigest getManifestDigest() {
8611            if (verificationParams == null) {
8612                return null;
8613            }
8614            return verificationParams.getManifestDigest();
8615        }
8616
8617        private int installLocationPolicy(PackageInfoLite pkgLite) {
8618            String packageName = pkgLite.packageName;
8619            int installLocation = pkgLite.installLocation;
8620            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8621            // reader
8622            synchronized (mPackages) {
8623                PackageParser.Package pkg = mPackages.get(packageName);
8624                if (pkg != null) {
8625                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8626                        // Check for downgrading.
8627                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8628                            if (pkgLite.versionCode < pkg.mVersionCode) {
8629                                Slog.w(TAG, "Can't install update of " + packageName
8630                                        + " update version " + pkgLite.versionCode
8631                                        + " is older than installed version "
8632                                        + pkg.mVersionCode);
8633                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8634                            }
8635                        }
8636                        // Check for updated system application.
8637                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8638                            if (onSd) {
8639                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8640                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8641                            }
8642                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8643                        } else {
8644                            if (onSd) {
8645                                // Install flag overrides everything.
8646                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8647                            }
8648                            // If current upgrade specifies particular preference
8649                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8650                                // Application explicitly specified internal.
8651                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8652                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8653                                // App explictly prefers external. Let policy decide
8654                            } else {
8655                                // Prefer previous location
8656                                if (isExternal(pkg)) {
8657                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8658                                }
8659                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8660                            }
8661                        }
8662                    } else {
8663                        // Invalid install. Return error code
8664                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8665                    }
8666                }
8667            }
8668            // All the special cases have been taken care of.
8669            // Return result based on recommended install location.
8670            if (onSd) {
8671                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8672            }
8673            return pkgLite.recommendedInstallLocation;
8674        }
8675
8676        /*
8677         * Invoke remote method to get package information and install
8678         * location values. Override install location based on default
8679         * policy if needed and then create install arguments based
8680         * on the install location.
8681         */
8682        public void handleStartCopy() throws RemoteException {
8683            int ret = PackageManager.INSTALL_SUCCEEDED;
8684
8685            // If we're already staged, we've firmly committed to an install location
8686            if (origin.staged) {
8687                if (origin.file != null) {
8688                    installFlags |= PackageManager.INSTALL_INTERNAL;
8689                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8690                } else if (origin.cid != null) {
8691                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8692                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8693                } else {
8694                    throw new IllegalStateException("Invalid stage location");
8695                }
8696            }
8697
8698            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8699            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8700
8701            PackageInfoLite pkgLite = null;
8702
8703            if (onInt && onSd) {
8704                // Check if both bits are set.
8705                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8706                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8707            } else {
8708                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8709                        packageAbiOverride);
8710
8711                /*
8712                 * If we have too little free space, try to free cache
8713                 * before giving up.
8714                 */
8715                if (!origin.staged && pkgLite.recommendedInstallLocation
8716                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8717                    // TODO: focus freeing disk space on the target device
8718                    final StorageManager storage = StorageManager.from(mContext);
8719                    final long lowThreshold = storage.getStorageLowBytes(
8720                            Environment.getDataDirectory());
8721
8722                    final long sizeBytes = mContainerService.calculateInstalledSize(
8723                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8724
8725                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8726                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8727                                installFlags, packageAbiOverride);
8728                    }
8729
8730                    /*
8731                     * The cache free must have deleted the file we
8732                     * downloaded to install.
8733                     *
8734                     * TODO: fix the "freeCache" call to not delete
8735                     *       the file we care about.
8736                     */
8737                    if (pkgLite.recommendedInstallLocation
8738                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8739                        pkgLite.recommendedInstallLocation
8740                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8741                    }
8742                }
8743            }
8744
8745            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8746                int loc = pkgLite.recommendedInstallLocation;
8747                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8748                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8749                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8750                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8751                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8752                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8753                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8754                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8755                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8756                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8757                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8758                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8759                } else {
8760                    // Override with defaults if needed.
8761                    loc = installLocationPolicy(pkgLite);
8762                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8763                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8764                    } else if (!onSd && !onInt) {
8765                        // Override install location with flags
8766                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8767                            // Set the flag to install on external media.
8768                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8769                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8770                        } else {
8771                            // Make sure the flag for installing on external
8772                            // media is unset
8773                            installFlags |= PackageManager.INSTALL_INTERNAL;
8774                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8775                        }
8776                    }
8777                }
8778            }
8779
8780            final InstallArgs args = createInstallArgs(this);
8781            mArgs = args;
8782
8783            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8784                 /*
8785                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8786                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8787                 */
8788                int userIdentifier = getUser().getIdentifier();
8789                if (userIdentifier == UserHandle.USER_ALL
8790                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8791                    userIdentifier = UserHandle.USER_OWNER;
8792                }
8793
8794                /*
8795                 * Determine if we have any installed package verifiers. If we
8796                 * do, then we'll defer to them to verify the packages.
8797                 */
8798                final int requiredUid = mRequiredVerifierPackage == null ? -1
8799                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8800                if (!origin.existing && requiredUid != -1
8801                        && isVerificationEnabled(userIdentifier, installFlags)) {
8802                    final Intent verification = new Intent(
8803                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8804                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8805                            PACKAGE_MIME_TYPE);
8806                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8807
8808                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8809                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8810                            0 /* TODO: Which userId? */);
8811
8812                    if (DEBUG_VERIFY) {
8813                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8814                                + verification.toString() + " with " + pkgLite.verifiers.length
8815                                + " optional verifiers");
8816                    }
8817
8818                    final int verificationId = mPendingVerificationToken++;
8819
8820                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8821
8822                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8823                            installerPackageName);
8824
8825                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8826                            installFlags);
8827
8828                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8829                            pkgLite.packageName);
8830
8831                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8832                            pkgLite.versionCode);
8833
8834                    if (verificationParams != null) {
8835                        if (verificationParams.getVerificationURI() != null) {
8836                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8837                                 verificationParams.getVerificationURI());
8838                        }
8839                        if (verificationParams.getOriginatingURI() != null) {
8840                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8841                                  verificationParams.getOriginatingURI());
8842                        }
8843                        if (verificationParams.getReferrer() != null) {
8844                            verification.putExtra(Intent.EXTRA_REFERRER,
8845                                  verificationParams.getReferrer());
8846                        }
8847                        if (verificationParams.getOriginatingUid() >= 0) {
8848                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8849                                  verificationParams.getOriginatingUid());
8850                        }
8851                        if (verificationParams.getInstallerUid() >= 0) {
8852                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8853                                  verificationParams.getInstallerUid());
8854                        }
8855                    }
8856
8857                    final PackageVerificationState verificationState = new PackageVerificationState(
8858                            requiredUid, args);
8859
8860                    mPendingVerification.append(verificationId, verificationState);
8861
8862                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8863                            receivers, verificationState);
8864
8865                    /*
8866                     * If any sufficient verifiers were listed in the package
8867                     * manifest, attempt to ask them.
8868                     */
8869                    if (sufficientVerifiers != null) {
8870                        final int N = sufficientVerifiers.size();
8871                        if (N == 0) {
8872                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8873                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8874                        } else {
8875                            for (int i = 0; i < N; i++) {
8876                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8877
8878                                final Intent sufficientIntent = new Intent(verification);
8879                                sufficientIntent.setComponent(verifierComponent);
8880
8881                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8882                            }
8883                        }
8884                    }
8885
8886                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8887                            mRequiredVerifierPackage, receivers);
8888                    if (ret == PackageManager.INSTALL_SUCCEEDED
8889                            && mRequiredVerifierPackage != null) {
8890                        /*
8891                         * Send the intent to the required verification agent,
8892                         * but only start the verification timeout after the
8893                         * target BroadcastReceivers have run.
8894                         */
8895                        verification.setComponent(requiredVerifierComponent);
8896                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8897                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8898                                new BroadcastReceiver() {
8899                                    @Override
8900                                    public void onReceive(Context context, Intent intent) {
8901                                        final Message msg = mHandler
8902                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8903                                        msg.arg1 = verificationId;
8904                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8905                                    }
8906                                }, null, 0, null, null);
8907
8908                        /*
8909                         * We don't want the copy to proceed until verification
8910                         * succeeds, so null out this field.
8911                         */
8912                        mArgs = null;
8913                    }
8914                } else {
8915                    /*
8916                     * No package verification is enabled, so immediately start
8917                     * the remote call to initiate copy using temporary file.
8918                     */
8919                    ret = args.copyApk(mContainerService, true);
8920                }
8921            }
8922
8923            mRet = ret;
8924        }
8925
8926        @Override
8927        void handleReturnCode() {
8928            // If mArgs is null, then MCS couldn't be reached. When it
8929            // reconnects, it will try again to install. At that point, this
8930            // will succeed.
8931            if (mArgs != null) {
8932                processPendingInstall(mArgs, mRet);
8933            }
8934        }
8935
8936        @Override
8937        void handleServiceError() {
8938            mArgs = createInstallArgs(this);
8939            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8940        }
8941
8942        public boolean isForwardLocked() {
8943            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8944        }
8945    }
8946
8947    /**
8948     * Used during creation of InstallArgs
8949     *
8950     * @param installFlags package installation flags
8951     * @return true if should be installed on external storage
8952     */
8953    private static boolean installOnSd(int installFlags) {
8954        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8955            return false;
8956        }
8957        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8958            return true;
8959        }
8960        return false;
8961    }
8962
8963    /**
8964     * Used during creation of InstallArgs
8965     *
8966     * @param installFlags package installation flags
8967     * @return true if should be installed as forward locked
8968     */
8969    private static boolean installForwardLocked(int installFlags) {
8970        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8971    }
8972
8973    private InstallArgs createInstallArgs(InstallParams params) {
8974        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8975            return new AsecInstallArgs(params);
8976        } else {
8977            return new FileInstallArgs(params);
8978        }
8979    }
8980
8981    /**
8982     * Create args that describe an existing installed package. Typically used
8983     * when cleaning up old installs, or used as a move source.
8984     */
8985    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8986            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8987        final boolean isInAsec;
8988        if (installOnSd(installFlags)) {
8989            /* Apps on SD card are always in ASEC containers. */
8990            isInAsec = true;
8991        } else if (installForwardLocked(installFlags)
8992                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8993            /*
8994             * Forward-locked apps are only in ASEC containers if they're the
8995             * new style
8996             */
8997            isInAsec = true;
8998        } else {
8999            isInAsec = false;
9000        }
9001
9002        if (isInAsec) {
9003            return new AsecInstallArgs(codePath, instructionSets,
9004                    installOnSd(installFlags), installForwardLocked(installFlags));
9005        } else {
9006            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9007                    instructionSets);
9008        }
9009    }
9010
9011    static abstract class InstallArgs {
9012        /** @see InstallParams#origin */
9013        final OriginInfo origin;
9014
9015        final IPackageInstallObserver2 observer;
9016        // Always refers to PackageManager flags only
9017        final int installFlags;
9018        final String installerPackageName;
9019        final ManifestDigest manifestDigest;
9020        final UserHandle user;
9021        final String abiOverride;
9022
9023        // The list of instruction sets supported by this app. This is currently
9024        // only used during the rmdex() phase to clean up resources. We can get rid of this
9025        // if we move dex files under the common app path.
9026        /* nullable */ String[] instructionSets;
9027
9028        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9029                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9030                String[] instructionSets, String abiOverride) {
9031            this.origin = origin;
9032            this.installFlags = installFlags;
9033            this.observer = observer;
9034            this.installerPackageName = installerPackageName;
9035            this.manifestDigest = manifestDigest;
9036            this.user = user;
9037            this.instructionSets = instructionSets;
9038            this.abiOverride = abiOverride;
9039        }
9040
9041        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9042        abstract int doPreInstall(int status);
9043
9044        /**
9045         * Rename package into final resting place. All paths on the given
9046         * scanned package should be updated to reflect the rename.
9047         */
9048        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9049        abstract int doPostInstall(int status, int uid);
9050
9051        /** @see PackageSettingBase#codePathString */
9052        abstract String getCodePath();
9053        /** @see PackageSettingBase#resourcePathString */
9054        abstract String getResourcePath();
9055        abstract String getLegacyNativeLibraryPath();
9056
9057        // Need installer lock especially for dex file removal.
9058        abstract void cleanUpResourcesLI();
9059        abstract boolean doPostDeleteLI(boolean delete);
9060        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9061
9062        /**
9063         * Called before the source arguments are copied. This is used mostly
9064         * for MoveParams when it needs to read the source file to put it in the
9065         * destination.
9066         */
9067        int doPreCopy() {
9068            return PackageManager.INSTALL_SUCCEEDED;
9069        }
9070
9071        /**
9072         * Called after the source arguments are copied. This is used mostly for
9073         * MoveParams when it needs to read the source file to put it in the
9074         * destination.
9075         *
9076         * @return
9077         */
9078        int doPostCopy(int uid) {
9079            return PackageManager.INSTALL_SUCCEEDED;
9080        }
9081
9082        protected boolean isFwdLocked() {
9083            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9084        }
9085
9086        protected boolean isExternal() {
9087            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9088        }
9089
9090        UserHandle getUser() {
9091            return user;
9092        }
9093    }
9094
9095    /**
9096     * Logic to handle installation of non-ASEC applications, including copying
9097     * and renaming logic.
9098     */
9099    class FileInstallArgs extends InstallArgs {
9100        private File codeFile;
9101        private File resourceFile;
9102        private File legacyNativeLibraryPath;
9103
9104        // Example topology:
9105        // /data/app/com.example/base.apk
9106        // /data/app/com.example/split_foo.apk
9107        // /data/app/com.example/lib/arm/libfoo.so
9108        // /data/app/com.example/lib/arm64/libfoo.so
9109        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9110
9111        /** New install */
9112        FileInstallArgs(InstallParams params) {
9113            super(params.origin, params.observer, params.installFlags,
9114                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9115                    null /* instruction sets */, params.packageAbiOverride);
9116            if (isFwdLocked()) {
9117                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9118            }
9119        }
9120
9121        /** Existing install */
9122        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9123                String[] instructionSets) {
9124            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9125            this.codeFile = (codePath != null) ? new File(codePath) : null;
9126            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9127            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9128                    new File(legacyNativeLibraryPath) : null;
9129        }
9130
9131        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9132            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9133                    isFwdLocked(), abiOverride);
9134
9135            final StorageManager storage = StorageManager.from(mContext);
9136            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9137        }
9138
9139        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9140            if (origin.staged) {
9141                Slog.d(TAG, origin.file + " already staged; skipping copy");
9142                codeFile = origin.file;
9143                resourceFile = origin.file;
9144                return PackageManager.INSTALL_SUCCEEDED;
9145            }
9146
9147            try {
9148                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9149                codeFile = tempDir;
9150                resourceFile = tempDir;
9151            } catch (IOException e) {
9152                Slog.w(TAG, "Failed to create copy file: " + e);
9153                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9154            }
9155
9156            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9157                @Override
9158                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9159                    if (!FileUtils.isValidExtFilename(name)) {
9160                        throw new IllegalArgumentException("Invalid filename: " + name);
9161                    }
9162                    try {
9163                        final File file = new File(codeFile, name);
9164                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9165                                O_RDWR | O_CREAT, 0644);
9166                        Os.chmod(file.getAbsolutePath(), 0644);
9167                        return new ParcelFileDescriptor(fd);
9168                    } catch (ErrnoException e) {
9169                        throw new RemoteException("Failed to open: " + e.getMessage());
9170                    }
9171                }
9172            };
9173
9174            int ret = PackageManager.INSTALL_SUCCEEDED;
9175            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9176            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9177                Slog.e(TAG, "Failed to copy package");
9178                return ret;
9179            }
9180
9181            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9182            NativeLibraryHelper.Handle handle = null;
9183            try {
9184                handle = NativeLibraryHelper.Handle.create(codeFile);
9185                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9186                        abiOverride);
9187            } catch (IOException e) {
9188                Slog.e(TAG, "Copying native libraries failed", e);
9189                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9190            } finally {
9191                IoUtils.closeQuietly(handle);
9192            }
9193
9194            return ret;
9195        }
9196
9197        int doPreInstall(int status) {
9198            if (status != PackageManager.INSTALL_SUCCEEDED) {
9199                cleanUp();
9200            }
9201            return status;
9202        }
9203
9204        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9205            if (status != PackageManager.INSTALL_SUCCEEDED) {
9206                cleanUp();
9207                return false;
9208            } else {
9209                final File beforeCodeFile = codeFile;
9210                final File afterCodeFile = getNextCodePath(pkg.packageName);
9211
9212                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9213                try {
9214                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9215                } catch (ErrnoException e) {
9216                    Slog.d(TAG, "Failed to rename", e);
9217                    return false;
9218                }
9219
9220                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9221                    Slog.d(TAG, "Failed to restorecon");
9222                    return false;
9223                }
9224
9225                // Reflect the rename internally
9226                codeFile = afterCodeFile;
9227                resourceFile = afterCodeFile;
9228
9229                // Reflect the rename in scanned details
9230                pkg.codePath = afterCodeFile.getAbsolutePath();
9231                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9232                        pkg.baseCodePath);
9233                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9234                        pkg.splitCodePaths);
9235
9236                // Reflect the rename in app info
9237                pkg.applicationInfo.setCodePath(pkg.codePath);
9238                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9239                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9240                pkg.applicationInfo.setResourcePath(pkg.codePath);
9241                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9242                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9243
9244                return true;
9245            }
9246        }
9247
9248        int doPostInstall(int status, int uid) {
9249            if (status != PackageManager.INSTALL_SUCCEEDED) {
9250                cleanUp();
9251            }
9252            return status;
9253        }
9254
9255        @Override
9256        String getCodePath() {
9257            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9258        }
9259
9260        @Override
9261        String getResourcePath() {
9262            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9263        }
9264
9265        @Override
9266        String getLegacyNativeLibraryPath() {
9267            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9268        }
9269
9270        private boolean cleanUp() {
9271            if (codeFile == null || !codeFile.exists()) {
9272                return false;
9273            }
9274
9275            if (codeFile.isDirectory()) {
9276                FileUtils.deleteContents(codeFile);
9277            }
9278            codeFile.delete();
9279
9280            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9281                resourceFile.delete();
9282            }
9283
9284            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9285                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9286                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9287                }
9288                legacyNativeLibraryPath.delete();
9289            }
9290
9291            return true;
9292        }
9293
9294        void cleanUpResourcesLI() {
9295            // Try enumerating all code paths before deleting
9296            List<String> allCodePaths = Collections.EMPTY_LIST;
9297            if (codeFile != null && codeFile.exists()) {
9298                try {
9299                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9300                    allCodePaths = pkg.getAllCodePaths();
9301                } catch (PackageParserException e) {
9302                    // Ignored; we tried our best
9303                }
9304            }
9305
9306            cleanUp();
9307
9308            if (!allCodePaths.isEmpty()) {
9309                if (instructionSets == null) {
9310                    throw new IllegalStateException("instructionSet == null");
9311                }
9312                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9313                for (String codePath : allCodePaths) {
9314                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9315                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9316                        if (retCode < 0) {
9317                            Slog.w(TAG, "Couldn't remove dex file for package: "
9318                                    + " at location " + codePath + ", retcode=" + retCode);
9319                            // we don't consider this to be a failure of the core package deletion
9320                        }
9321                    }
9322                }
9323            }
9324        }
9325
9326        boolean doPostDeleteLI(boolean delete) {
9327            // XXX err, shouldn't we respect the delete flag?
9328            cleanUpResourcesLI();
9329            return true;
9330        }
9331    }
9332
9333    private boolean isAsecExternal(String cid) {
9334        final String asecPath = PackageHelper.getSdFilesystem(cid);
9335        return !asecPath.startsWith(mAsecInternalPath);
9336    }
9337
9338    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9339            PackageManagerException {
9340        if (copyRet < 0) {
9341            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9342                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9343                throw new PackageManagerException(copyRet, message);
9344            }
9345        }
9346    }
9347
9348    /**
9349     * Extract the MountService "container ID" from the full code path of an
9350     * .apk.
9351     */
9352    static String cidFromCodePath(String fullCodePath) {
9353        int eidx = fullCodePath.lastIndexOf("/");
9354        String subStr1 = fullCodePath.substring(0, eidx);
9355        int sidx = subStr1.lastIndexOf("/");
9356        return subStr1.substring(sidx+1, eidx);
9357    }
9358
9359    /**
9360     * Logic to handle installation of ASEC applications, including copying and
9361     * renaming logic.
9362     */
9363    class AsecInstallArgs extends InstallArgs {
9364        static final String RES_FILE_NAME = "pkg.apk";
9365        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9366
9367        String cid;
9368        String packagePath;
9369        String resourcePath;
9370        String legacyNativeLibraryDir;
9371
9372        /** New install */
9373        AsecInstallArgs(InstallParams params) {
9374            super(params.origin, params.observer, params.installFlags,
9375                    params.installerPackageName, params.getManifestDigest(),
9376                    params.getUser(), null /* instruction sets */,
9377                    params.packageAbiOverride);
9378        }
9379
9380        /** Existing install */
9381        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9382                        boolean isExternal, boolean isForwardLocked) {
9383            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9384                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9385                    instructionSets, null);
9386            // Hackily pretend we're still looking at a full code path
9387            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9388                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9389            }
9390
9391            // Extract cid from fullCodePath
9392            int eidx = fullCodePath.lastIndexOf("/");
9393            String subStr1 = fullCodePath.substring(0, eidx);
9394            int sidx = subStr1.lastIndexOf("/");
9395            cid = subStr1.substring(sidx+1, eidx);
9396            setMountPath(subStr1);
9397        }
9398
9399        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9400            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9401                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9402                    instructionSets, null);
9403            this.cid = cid;
9404            setMountPath(PackageHelper.getSdDir(cid));
9405        }
9406
9407        void createCopyFile() {
9408            cid = mInstallerService.allocateExternalStageCidLegacy();
9409        }
9410
9411        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9412            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9413                    abiOverride);
9414
9415            final File target;
9416            if (isExternal()) {
9417                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9418            } else {
9419                target = Environment.getDataDirectory();
9420            }
9421
9422            final StorageManager storage = StorageManager.from(mContext);
9423            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9424        }
9425
9426        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9427            if (origin.staged) {
9428                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9429                cid = origin.cid;
9430                setMountPath(PackageHelper.getSdDir(cid));
9431                return PackageManager.INSTALL_SUCCEEDED;
9432            }
9433
9434            if (temp) {
9435                createCopyFile();
9436            } else {
9437                /*
9438                 * Pre-emptively destroy the container since it's destroyed if
9439                 * copying fails due to it existing anyway.
9440                 */
9441                PackageHelper.destroySdDir(cid);
9442            }
9443
9444            final String newMountPath = imcs.copyPackageToContainer(
9445                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9446                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9447
9448            if (newMountPath != null) {
9449                setMountPath(newMountPath);
9450                return PackageManager.INSTALL_SUCCEEDED;
9451            } else {
9452                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9453            }
9454        }
9455
9456        @Override
9457        String getCodePath() {
9458            return packagePath;
9459        }
9460
9461        @Override
9462        String getResourcePath() {
9463            return resourcePath;
9464        }
9465
9466        @Override
9467        String getLegacyNativeLibraryPath() {
9468            return legacyNativeLibraryDir;
9469        }
9470
9471        int doPreInstall(int status) {
9472            if (status != PackageManager.INSTALL_SUCCEEDED) {
9473                // Destroy container
9474                PackageHelper.destroySdDir(cid);
9475            } else {
9476                boolean mounted = PackageHelper.isContainerMounted(cid);
9477                if (!mounted) {
9478                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9479                            Process.SYSTEM_UID);
9480                    if (newMountPath != null) {
9481                        setMountPath(newMountPath);
9482                    } else {
9483                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9484                    }
9485                }
9486            }
9487            return status;
9488        }
9489
9490        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9491            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9492            String newMountPath = null;
9493            if (PackageHelper.isContainerMounted(cid)) {
9494                // Unmount the container
9495                if (!PackageHelper.unMountSdDir(cid)) {
9496                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9497                    return false;
9498                }
9499            }
9500            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9501                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9502                        " which might be stale. Will try to clean up.");
9503                // Clean up the stale container and proceed to recreate.
9504                if (!PackageHelper.destroySdDir(newCacheId)) {
9505                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9506                    return false;
9507                }
9508                // Successfully cleaned up stale container. Try to rename again.
9509                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9510                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9511                            + " inspite of cleaning it up.");
9512                    return false;
9513                }
9514            }
9515            if (!PackageHelper.isContainerMounted(newCacheId)) {
9516                Slog.w(TAG, "Mounting container " + newCacheId);
9517                newMountPath = PackageHelper.mountSdDir(newCacheId,
9518                        getEncryptKey(), Process.SYSTEM_UID);
9519            } else {
9520                newMountPath = PackageHelper.getSdDir(newCacheId);
9521            }
9522            if (newMountPath == null) {
9523                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9524                return false;
9525            }
9526            Log.i(TAG, "Succesfully renamed " + cid +
9527                    " to " + newCacheId +
9528                    " at new path: " + newMountPath);
9529            cid = newCacheId;
9530
9531            final File beforeCodeFile = new File(packagePath);
9532            setMountPath(newMountPath);
9533            final File afterCodeFile = new File(packagePath);
9534
9535            // Reflect the rename in scanned details
9536            pkg.codePath = afterCodeFile.getAbsolutePath();
9537            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9538                    pkg.baseCodePath);
9539            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9540                    pkg.splitCodePaths);
9541
9542            // Reflect the rename in app info
9543            pkg.applicationInfo.setCodePath(pkg.codePath);
9544            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9545            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9546            pkg.applicationInfo.setResourcePath(pkg.codePath);
9547            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9548            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9549
9550            return true;
9551        }
9552
9553        private void setMountPath(String mountPath) {
9554            final File mountFile = new File(mountPath);
9555
9556            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9557            if (monolithicFile.exists()) {
9558                packagePath = monolithicFile.getAbsolutePath();
9559                if (isFwdLocked()) {
9560                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9561                } else {
9562                    resourcePath = packagePath;
9563                }
9564            } else {
9565                packagePath = mountFile.getAbsolutePath();
9566                resourcePath = packagePath;
9567            }
9568
9569            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9570        }
9571
9572        int doPostInstall(int status, int uid) {
9573            if (status != PackageManager.INSTALL_SUCCEEDED) {
9574                cleanUp();
9575            } else {
9576                final int groupOwner;
9577                final String protectedFile;
9578                if (isFwdLocked()) {
9579                    groupOwner = UserHandle.getSharedAppGid(uid);
9580                    protectedFile = RES_FILE_NAME;
9581                } else {
9582                    groupOwner = -1;
9583                    protectedFile = null;
9584                }
9585
9586                if (uid < Process.FIRST_APPLICATION_UID
9587                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9588                    Slog.e(TAG, "Failed to finalize " + cid);
9589                    PackageHelper.destroySdDir(cid);
9590                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9591                }
9592
9593                boolean mounted = PackageHelper.isContainerMounted(cid);
9594                if (!mounted) {
9595                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9596                }
9597            }
9598            return status;
9599        }
9600
9601        private void cleanUp() {
9602            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9603
9604            // Destroy secure container
9605            PackageHelper.destroySdDir(cid);
9606        }
9607
9608        private List<String> getAllCodePaths() {
9609            final File codeFile = new File(getCodePath());
9610            if (codeFile != null && codeFile.exists()) {
9611                try {
9612                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9613                    return pkg.getAllCodePaths();
9614                } catch (PackageParserException e) {
9615                    // Ignored; we tried our best
9616                }
9617            }
9618            return Collections.EMPTY_LIST;
9619        }
9620
9621        void cleanUpResourcesLI() {
9622            // Enumerate all code paths before deleting
9623            cleanUpResourcesLI(getAllCodePaths());
9624        }
9625
9626        private void cleanUpResourcesLI(List<String> allCodePaths) {
9627            cleanUp();
9628
9629            if (!allCodePaths.isEmpty()) {
9630                if (instructionSets == null) {
9631                    throw new IllegalStateException("instructionSet == null");
9632                }
9633                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9634                for (String codePath : allCodePaths) {
9635                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9636                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9637                        if (retCode < 0) {
9638                            Slog.w(TAG, "Couldn't remove dex file for package: "
9639                                    + " at location " + codePath + ", retcode=" + retCode);
9640                            // we don't consider this to be a failure of the core package deletion
9641                        }
9642                    }
9643                }
9644            }
9645        }
9646
9647        boolean matchContainer(String app) {
9648            if (cid.startsWith(app)) {
9649                return true;
9650            }
9651            return false;
9652        }
9653
9654        String getPackageName() {
9655            return getAsecPackageName(cid);
9656        }
9657
9658        boolean doPostDeleteLI(boolean delete) {
9659            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9660            final List<String> allCodePaths = getAllCodePaths();
9661            boolean mounted = PackageHelper.isContainerMounted(cid);
9662            if (mounted) {
9663                // Unmount first
9664                if (PackageHelper.unMountSdDir(cid)) {
9665                    mounted = false;
9666                }
9667            }
9668            if (!mounted && delete) {
9669                cleanUpResourcesLI(allCodePaths);
9670            }
9671            return !mounted;
9672        }
9673
9674        @Override
9675        int doPreCopy() {
9676            if (isFwdLocked()) {
9677                if (!PackageHelper.fixSdPermissions(cid,
9678                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9679                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9680                }
9681            }
9682
9683            return PackageManager.INSTALL_SUCCEEDED;
9684        }
9685
9686        @Override
9687        int doPostCopy(int uid) {
9688            if (isFwdLocked()) {
9689                if (uid < Process.FIRST_APPLICATION_UID
9690                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9691                                RES_FILE_NAME)) {
9692                    Slog.e(TAG, "Failed to finalize " + cid);
9693                    PackageHelper.destroySdDir(cid);
9694                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9695                }
9696            }
9697
9698            return PackageManager.INSTALL_SUCCEEDED;
9699        }
9700    }
9701
9702    static String getAsecPackageName(String packageCid) {
9703        int idx = packageCid.lastIndexOf("-");
9704        if (idx == -1) {
9705            return packageCid;
9706        }
9707        return packageCid.substring(0, idx);
9708    }
9709
9710    // Utility method used to create code paths based on package name and available index.
9711    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9712        String idxStr = "";
9713        int idx = 1;
9714        // Fall back to default value of idx=1 if prefix is not
9715        // part of oldCodePath
9716        if (oldCodePath != null) {
9717            String subStr = oldCodePath;
9718            // Drop the suffix right away
9719            if (suffix != null && subStr.endsWith(suffix)) {
9720                subStr = subStr.substring(0, subStr.length() - suffix.length());
9721            }
9722            // If oldCodePath already contains prefix find out the
9723            // ending index to either increment or decrement.
9724            int sidx = subStr.lastIndexOf(prefix);
9725            if (sidx != -1) {
9726                subStr = subStr.substring(sidx + prefix.length());
9727                if (subStr != null) {
9728                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9729                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9730                    }
9731                    try {
9732                        idx = Integer.parseInt(subStr);
9733                        if (idx <= 1) {
9734                            idx++;
9735                        } else {
9736                            idx--;
9737                        }
9738                    } catch(NumberFormatException e) {
9739                    }
9740                }
9741            }
9742        }
9743        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9744        return prefix + idxStr;
9745    }
9746
9747    private File getNextCodePath(String packageName) {
9748        int suffix = 1;
9749        File result;
9750        do {
9751            result = new File(mAppInstallDir, packageName + "-" + suffix);
9752            suffix++;
9753        } while (result.exists());
9754        return result;
9755    }
9756
9757    // Utility method used to ignore ADD/REMOVE events
9758    // by directory observer.
9759    private static boolean ignoreCodePath(String fullPathStr) {
9760        String apkName = deriveCodePathName(fullPathStr);
9761        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9762        if (idx != -1 && ((idx+1) < apkName.length())) {
9763            // Make sure the package ends with a numeral
9764            String version = apkName.substring(idx+1);
9765            try {
9766                Integer.parseInt(version);
9767                return true;
9768            } catch (NumberFormatException e) {}
9769        }
9770        return false;
9771    }
9772
9773    // Utility method that returns the relative package path with respect
9774    // to the installation directory. Like say for /data/data/com.test-1.apk
9775    // string com.test-1 is returned.
9776    static String deriveCodePathName(String codePath) {
9777        if (codePath == null) {
9778            return null;
9779        }
9780        final File codeFile = new File(codePath);
9781        final String name = codeFile.getName();
9782        if (codeFile.isDirectory()) {
9783            return name;
9784        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9785            final int lastDot = name.lastIndexOf('.');
9786            return name.substring(0, lastDot);
9787        } else {
9788            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9789            return null;
9790        }
9791    }
9792
9793    class PackageInstalledInfo {
9794        String name;
9795        int uid;
9796        // The set of users that originally had this package installed.
9797        int[] origUsers;
9798        // The set of users that now have this package installed.
9799        int[] newUsers;
9800        PackageParser.Package pkg;
9801        int returnCode;
9802        String returnMsg;
9803        PackageRemovedInfo removedInfo;
9804
9805        public void setError(int code, String msg) {
9806            returnCode = code;
9807            returnMsg = msg;
9808            Slog.w(TAG, msg);
9809        }
9810
9811        public void setError(String msg, PackageParserException e) {
9812            returnCode = e.error;
9813            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9814            Slog.w(TAG, msg, e);
9815        }
9816
9817        public void setError(String msg, PackageManagerException e) {
9818            returnCode = e.error;
9819            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9820            Slog.w(TAG, msg, e);
9821        }
9822
9823        // In some error cases we want to convey more info back to the observer
9824        String origPackage;
9825        String origPermission;
9826    }
9827
9828    /*
9829     * Install a non-existing package.
9830     */
9831    private void installNewPackageLI(PackageParser.Package pkg,
9832            int parseFlags, int scanFlags, UserHandle user,
9833            String installerPackageName, PackageInstalledInfo res) {
9834        // Remember this for later, in case we need to rollback this install
9835        String pkgName = pkg.packageName;
9836
9837        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9838        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9839        synchronized(mPackages) {
9840            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9841                // A package with the same name is already installed, though
9842                // it has been renamed to an older name.  The package we
9843                // are trying to install should be installed as an update to
9844                // the existing one, but that has not been requested, so bail.
9845                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9846                        + " without first uninstalling package running as "
9847                        + mSettings.mRenamedPackages.get(pkgName));
9848                return;
9849            }
9850            if (mPackages.containsKey(pkgName)) {
9851                // Don't allow installation over an existing package with the same name.
9852                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9853                        + " without first uninstalling.");
9854                return;
9855            }
9856        }
9857
9858        try {
9859            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9860                    System.currentTimeMillis(), user);
9861
9862            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9863            // delete the partially installed application. the data directory will have to be
9864            // restored if it was already existing
9865            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9866                // remove package from internal structures.  Note that we want deletePackageX to
9867                // delete the package data and cache directories that it created in
9868                // scanPackageLocked, unless those directories existed before we even tried to
9869                // install.
9870                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9871                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9872                                res.removedInfo, true);
9873            }
9874
9875        } catch (PackageManagerException e) {
9876            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9877        }
9878    }
9879
9880    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9881        // Upgrade keysets are being used.  Determine if new package has a superset of the
9882        // required keys.
9883        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9884        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9885        for (int i = 0; i < upgradeKeySets.length; i++) {
9886            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9887            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9888                return true;
9889            }
9890        }
9891        return false;
9892    }
9893
9894    private void replacePackageLI(PackageParser.Package pkg,
9895            int parseFlags, int scanFlags, UserHandle user,
9896            String installerPackageName, PackageInstalledInfo res) {
9897        PackageParser.Package oldPackage;
9898        String pkgName = pkg.packageName;
9899        int[] allUsers;
9900        boolean[] perUserInstalled;
9901
9902        // First find the old package info and check signatures
9903        synchronized(mPackages) {
9904            oldPackage = mPackages.get(pkgName);
9905            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9906            PackageSetting ps = mSettings.mPackages.get(pkgName);
9907            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9908                // default to original signature matching
9909                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9910                    != PackageManager.SIGNATURE_MATCH) {
9911                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9912                            "New package has a different signature: " + pkgName);
9913                    return;
9914                }
9915            } else {
9916                if(!checkUpgradeKeySetLP(ps, pkg)) {
9917                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9918                            "New package not signed by keys specified by upgrade-keysets: "
9919                            + pkgName);
9920                    return;
9921                }
9922            }
9923
9924            // In case of rollback, remember per-user/profile install state
9925            allUsers = sUserManager.getUserIds();
9926            perUserInstalled = new boolean[allUsers.length];
9927            for (int i = 0; i < allUsers.length; i++) {
9928                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9929            }
9930        }
9931
9932        boolean sysPkg = (isSystemApp(oldPackage));
9933        if (sysPkg) {
9934            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9935                    user, allUsers, perUserInstalled, installerPackageName, res);
9936        } else {
9937            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9938                    user, allUsers, perUserInstalled, installerPackageName, res);
9939        }
9940    }
9941
9942    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9943            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9944            int[] allUsers, boolean[] perUserInstalled,
9945            String installerPackageName, PackageInstalledInfo res) {
9946        String pkgName = deletedPackage.packageName;
9947        boolean deletedPkg = true;
9948        boolean updatedSettings = false;
9949
9950        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9951                + deletedPackage);
9952        long origUpdateTime;
9953        if (pkg.mExtras != null) {
9954            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9955        } else {
9956            origUpdateTime = 0;
9957        }
9958
9959        // First delete the existing package while retaining the data directory
9960        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9961                res.removedInfo, true)) {
9962            // If the existing package wasn't successfully deleted
9963            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9964            deletedPkg = false;
9965        } else {
9966            // Successfully deleted the old package; proceed with replace.
9967
9968            // If deleted package lived in a container, give users a chance to
9969            // relinquish resources before killing.
9970            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9971                if (DEBUG_INSTALL) {
9972                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9973                }
9974                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9975                final ArrayList<String> pkgList = new ArrayList<String>(1);
9976                pkgList.add(deletedPackage.applicationInfo.packageName);
9977                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9978            }
9979
9980            deleteCodeCacheDirsLI(pkgName);
9981            try {
9982                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9983                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9984                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9985                updatedSettings = true;
9986            } catch (PackageManagerException e) {
9987                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9988            }
9989        }
9990
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            if(updatedSettings) {
9997                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9998                deletePackageLI(
9999                        pkgName, null, true, allUsers, perUserInstalled,
10000                        PackageManager.DELETE_KEEP_DATA,
10001                                res.removedInfo, true);
10002            }
10003            // Since we failed to install the new package we need to restore the old
10004            // package that we deleted.
10005            if (deletedPkg) {
10006                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10007                File restoreFile = new File(deletedPackage.codePath);
10008                // Parse old package
10009                boolean oldOnSd = isExternal(deletedPackage);
10010                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10011                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10012                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10013                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10014                try {
10015                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10016                } catch (PackageManagerException e) {
10017                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10018                            + e.getMessage());
10019                    return;
10020                }
10021                // Restore of old package succeeded. Update permissions.
10022                // writer
10023                synchronized (mPackages) {
10024                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10025                            UPDATE_PERMISSIONS_ALL);
10026                    // can downgrade to reader
10027                    mSettings.writeLPr();
10028                }
10029                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10030            }
10031        }
10032    }
10033
10034    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10035            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10036            int[] allUsers, boolean[] perUserInstalled,
10037            String installerPackageName, PackageInstalledInfo res) {
10038        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10039                + ", old=" + deletedPackage);
10040        boolean disabledSystem = false;
10041        boolean updatedSettings = false;
10042        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10043        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10044            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10045        }
10046        String packageName = deletedPackage.packageName;
10047        if (packageName == null) {
10048            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10049                    "Attempt to delete null packageName.");
10050            return;
10051        }
10052        PackageParser.Package oldPkg;
10053        PackageSetting oldPkgSetting;
10054        // reader
10055        synchronized (mPackages) {
10056            oldPkg = mPackages.get(packageName);
10057            oldPkgSetting = mSettings.mPackages.get(packageName);
10058            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10059                    (oldPkgSetting == null)) {
10060                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10061                        "Couldn't find package:" + packageName + " information");
10062                return;
10063            }
10064        }
10065
10066        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10067
10068        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10069        res.removedInfo.removedPackage = packageName;
10070        // Remove existing system package
10071        removePackageLI(oldPkgSetting, true);
10072        // writer
10073        synchronized (mPackages) {
10074            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10075            if (!disabledSystem && deletedPackage != null) {
10076                // We didn't need to disable the .apk as a current system package,
10077                // which means we are replacing another update that is already
10078                // installed.  We need to make sure to delete the older one's .apk.
10079                res.removedInfo.args = createInstallArgsForExisting(0,
10080                        deletedPackage.applicationInfo.getCodePath(),
10081                        deletedPackage.applicationInfo.getResourcePath(),
10082                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10083                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10084            } else {
10085                res.removedInfo.args = null;
10086            }
10087        }
10088
10089        // Successfully disabled the old package. Now proceed with re-installation
10090        deleteCodeCacheDirsLI(packageName);
10091
10092        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10093        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10094
10095        PackageParser.Package newPackage = null;
10096        try {
10097            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10098            if (newPackage.mExtras != null) {
10099                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10100                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10101                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10102
10103                // is the update attempting to change shared user? that isn't going to work...
10104                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10105                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10106                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10107                            + " to " + newPkgSetting.sharedUser);
10108                    updatedSettings = true;
10109                }
10110            }
10111
10112            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10113                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10114                updatedSettings = true;
10115            }
10116
10117        } catch (PackageManagerException e) {
10118            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10119        }
10120
10121        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10122            // Re installation failed. Restore old information
10123            // Remove new pkg information
10124            if (newPackage != null) {
10125                removeInstalledPackageLI(newPackage, true);
10126            }
10127            // Add back the old system package
10128            try {
10129                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10130            } catch (PackageManagerException e) {
10131                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10132            }
10133            // Restore the old system information in Settings
10134            synchronized (mPackages) {
10135                if (disabledSystem) {
10136                    mSettings.enableSystemPackageLPw(packageName);
10137                }
10138                if (updatedSettings) {
10139                    mSettings.setInstallerPackageName(packageName,
10140                            oldPkgSetting.installerPackageName);
10141                }
10142                mSettings.writeLPr();
10143            }
10144        }
10145    }
10146
10147    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10148            int[] allUsers, boolean[] perUserInstalled,
10149            PackageInstalledInfo res) {
10150        String pkgName = newPackage.packageName;
10151        synchronized (mPackages) {
10152            //write settings. the installStatus will be incomplete at this stage.
10153            //note that the new package setting would have already been
10154            //added to mPackages. It hasn't been persisted yet.
10155            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10156            mSettings.writeLPr();
10157        }
10158
10159        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10160
10161        synchronized (mPackages) {
10162            updatePermissionsLPw(newPackage.packageName, newPackage,
10163                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10164                            ? UPDATE_PERMISSIONS_ALL : 0));
10165            // For system-bundled packages, we assume that installing an upgraded version
10166            // of the package implies that the user actually wants to run that new code,
10167            // so we enable the package.
10168            if (isSystemApp(newPackage)) {
10169                // NB: implicit assumption that system package upgrades apply to all users
10170                if (DEBUG_INSTALL) {
10171                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10172                }
10173                PackageSetting ps = mSettings.mPackages.get(pkgName);
10174                if (ps != null) {
10175                    if (res.origUsers != null) {
10176                        for (int userHandle : res.origUsers) {
10177                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10178                                    userHandle, installerPackageName);
10179                        }
10180                    }
10181                    // Also convey the prior install/uninstall state
10182                    if (allUsers != null && perUserInstalled != null) {
10183                        for (int i = 0; i < allUsers.length; i++) {
10184                            if (DEBUG_INSTALL) {
10185                                Slog.d(TAG, "    user " + allUsers[i]
10186                                        + " => " + perUserInstalled[i]);
10187                            }
10188                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10189                        }
10190                        // these install state changes will be persisted in the
10191                        // upcoming call to mSettings.writeLPr().
10192                    }
10193                }
10194            }
10195            res.name = pkgName;
10196            res.uid = newPackage.applicationInfo.uid;
10197            res.pkg = newPackage;
10198            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10199            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10200            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10201            //to update install status
10202            mSettings.writeLPr();
10203        }
10204    }
10205
10206    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10207        final int installFlags = args.installFlags;
10208        String installerPackageName = args.installerPackageName;
10209        File tmpPackageFile = new File(args.getCodePath());
10210        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10211        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10212        boolean replace = false;
10213        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10214        // Result object to be returned
10215        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10216
10217        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10218        // Retrieve PackageSettings and parse package
10219        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10220                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10221                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10222        PackageParser pp = new PackageParser();
10223        pp.setSeparateProcesses(mSeparateProcesses);
10224        pp.setDisplayMetrics(mMetrics);
10225
10226        final PackageParser.Package pkg;
10227        try {
10228            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10229        } catch (PackageParserException e) {
10230            res.setError("Failed parse during installPackageLI", e);
10231            return;
10232        }
10233
10234        // Mark that we have an install time CPU ABI override.
10235        pkg.cpuAbiOverride = args.abiOverride;
10236
10237        String pkgName = res.name = pkg.packageName;
10238        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10239            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10240                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10241                return;
10242            }
10243        }
10244
10245        try {
10246            pp.collectCertificates(pkg, parseFlags);
10247            pp.collectManifestDigest(pkg);
10248        } catch (PackageParserException e) {
10249            res.setError("Failed collect during installPackageLI", e);
10250            return;
10251        }
10252
10253        /* If the installer passed in a manifest digest, compare it now. */
10254        if (args.manifestDigest != null) {
10255            if (DEBUG_INSTALL) {
10256                final String parsedManifest = pkg.manifestDigest == null ? "null"
10257                        : pkg.manifestDigest.toString();
10258                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10259                        + parsedManifest);
10260            }
10261
10262            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10263                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10264                return;
10265            }
10266        } else if (DEBUG_INSTALL) {
10267            final String parsedManifest = pkg.manifestDigest == null
10268                    ? "null" : pkg.manifestDigest.toString();
10269            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10270        }
10271
10272        // Get rid of all references to package scan path via parser.
10273        pp = null;
10274        String oldCodePath = null;
10275        boolean systemApp = false;
10276        synchronized (mPackages) {
10277            // Check whether the newly-scanned package wants to define an already-defined perm
10278            int N = pkg.permissions.size();
10279            for (int i = N-1; i >= 0; i--) {
10280                PackageParser.Permission perm = pkg.permissions.get(i);
10281                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10282                if (bp != null) {
10283                    // If the defining package is signed with our cert, it's okay.  This
10284                    // also includes the "updating the same package" case, of course.
10285                    // "updating same package" could also involve key-rotation.
10286                    final boolean sigsOk;
10287                    if (!bp.sourcePackage.equals(pkg.packageName)
10288                            || !(bp.packageSetting instanceof PackageSetting)
10289                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10290                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10291                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10292                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10293                    } else {
10294                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10295                    }
10296                    if (!sigsOk) {
10297                        // If the owning package is the system itself, we log but allow
10298                        // install to proceed; we fail the install on all other permission
10299                        // redefinitions.
10300                        if (!bp.sourcePackage.equals("android")) {
10301                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10302                                    + pkg.packageName + " attempting to redeclare permission "
10303                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10304                            res.origPermission = perm.info.name;
10305                            res.origPackage = bp.sourcePackage;
10306                            return;
10307                        } else {
10308                            Slog.w(TAG, "Package " + pkg.packageName
10309                                    + " attempting to redeclare system permission "
10310                                    + perm.info.name + "; ignoring new declaration");
10311                            pkg.permissions.remove(i);
10312                        }
10313                    }
10314                }
10315            }
10316
10317            // Check if installing already existing package
10318            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10319                String oldName = mSettings.mRenamedPackages.get(pkgName);
10320                if (pkg.mOriginalPackages != null
10321                        && pkg.mOriginalPackages.contains(oldName)
10322                        && mPackages.containsKey(oldName)) {
10323                    // This package is derived from an original package,
10324                    // and this device has been updating from that original
10325                    // name.  We must continue using the original name, so
10326                    // rename the new package here.
10327                    pkg.setPackageName(oldName);
10328                    pkgName = pkg.packageName;
10329                    replace = true;
10330                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10331                            + oldName + " pkgName=" + pkgName);
10332                } else if (mPackages.containsKey(pkgName)) {
10333                    // This package, under its official name, already exists
10334                    // on the device; we should replace it.
10335                    replace = true;
10336                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10337                }
10338            }
10339            PackageSetting ps = mSettings.mPackages.get(pkgName);
10340            if (ps != null) {
10341                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10342                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10343                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10344                    systemApp = (ps.pkg.applicationInfo.flags &
10345                            ApplicationInfo.FLAG_SYSTEM) != 0;
10346                }
10347                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10348            }
10349        }
10350
10351        if (systemApp && onSd) {
10352            // Disable updates to system apps on sdcard
10353            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10354                    "Cannot install updates to system apps on sdcard");
10355            return;
10356        }
10357
10358        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10359            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10360            return;
10361        }
10362
10363        if (replace) {
10364            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10365                    installerPackageName, res);
10366        } else {
10367            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10368                    args.user, installerPackageName, res);
10369        }
10370        synchronized (mPackages) {
10371            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10372            if (ps != null) {
10373                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10374            }
10375        }
10376    }
10377
10378    private static boolean isForwardLocked(PackageParser.Package pkg) {
10379        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10380    }
10381
10382    private static boolean isForwardLocked(ApplicationInfo info) {
10383        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10384    }
10385
10386    private boolean isForwardLocked(PackageSetting ps) {
10387        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10388    }
10389
10390    private static boolean isMultiArch(PackageSetting ps) {
10391        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10392    }
10393
10394    private static boolean isMultiArch(ApplicationInfo info) {
10395        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10396    }
10397
10398    private static boolean isExternal(PackageParser.Package pkg) {
10399        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10400    }
10401
10402    private static boolean isExternal(PackageSetting ps) {
10403        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10404    }
10405
10406    private static boolean isExternal(ApplicationInfo info) {
10407        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10408    }
10409
10410    private static boolean isSystemApp(PackageParser.Package pkg) {
10411        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10412    }
10413
10414    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10415        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10416    }
10417
10418    private static boolean isSystemApp(ApplicationInfo info) {
10419        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10420    }
10421
10422    private static boolean isSystemApp(PackageSetting ps) {
10423        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10424    }
10425
10426    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10427        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10428    }
10429
10430    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10431        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10432    }
10433
10434    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10435        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10436    }
10437
10438    private int packageFlagsToInstallFlags(PackageSetting ps) {
10439        int installFlags = 0;
10440        if (isExternal(ps)) {
10441            installFlags |= PackageManager.INSTALL_EXTERNAL;
10442        }
10443        if (isForwardLocked(ps)) {
10444            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10445        }
10446        return installFlags;
10447    }
10448
10449    private void deleteTempPackageFiles() {
10450        final FilenameFilter filter = new FilenameFilter() {
10451            public boolean accept(File dir, String name) {
10452                return name.startsWith("vmdl") && name.endsWith(".tmp");
10453            }
10454        };
10455        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10456            file.delete();
10457        }
10458    }
10459
10460    @Override
10461    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10462            int flags) {
10463        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10464                flags);
10465    }
10466
10467    @Override
10468    public void deletePackage(final String packageName,
10469            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10470        mContext.enforceCallingOrSelfPermission(
10471                android.Manifest.permission.DELETE_PACKAGES, null);
10472        final int uid = Binder.getCallingUid();
10473        if (UserHandle.getUserId(uid) != userId) {
10474            mContext.enforceCallingPermission(
10475                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10476                    "deletePackage for user " + userId);
10477        }
10478        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10479            try {
10480                observer.onPackageDeleted(packageName,
10481                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10482            } catch (RemoteException re) {
10483            }
10484            return;
10485        }
10486
10487        boolean uninstallBlocked = false;
10488        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10489            int[] users = sUserManager.getUserIds();
10490            for (int i = 0; i < users.length; ++i) {
10491                if (getBlockUninstallForUser(packageName, users[i])) {
10492                    uninstallBlocked = true;
10493                    break;
10494                }
10495            }
10496        } else {
10497            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10498        }
10499        if (uninstallBlocked) {
10500            try {
10501                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10502                        null);
10503            } catch (RemoteException re) {
10504            }
10505            return;
10506        }
10507
10508        if (DEBUG_REMOVE) {
10509            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10510        }
10511        // Queue up an async operation since the package deletion may take a little while.
10512        mHandler.post(new Runnable() {
10513            public void run() {
10514                mHandler.removeCallbacks(this);
10515                final int returnCode = deletePackageX(packageName, userId, flags);
10516                if (observer != null) {
10517                    try {
10518                        observer.onPackageDeleted(packageName, returnCode, null);
10519                    } catch (RemoteException e) {
10520                        Log.i(TAG, "Observer no longer exists.");
10521                    } //end catch
10522                } //end if
10523            } //end run
10524        });
10525    }
10526
10527    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10528        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10529                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10530        try {
10531            if (dpm != null) {
10532                if (dpm.isDeviceOwner(packageName)) {
10533                    return true;
10534                }
10535                int[] users;
10536                if (userId == UserHandle.USER_ALL) {
10537                    users = sUserManager.getUserIds();
10538                } else {
10539                    users = new int[]{userId};
10540                }
10541                for (int i = 0; i < users.length; ++i) {
10542                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10543                        return true;
10544                    }
10545                }
10546            }
10547        } catch (RemoteException e) {
10548        }
10549        return false;
10550    }
10551
10552    /**
10553     *  This method is an internal method that could be get invoked either
10554     *  to delete an installed package or to clean up a failed installation.
10555     *  After deleting an installed package, a broadcast is sent to notify any
10556     *  listeners that the package has been installed. For cleaning up a failed
10557     *  installation, the broadcast is not necessary since the package's
10558     *  installation wouldn't have sent the initial broadcast either
10559     *  The key steps in deleting a package are
10560     *  deleting the package information in internal structures like mPackages,
10561     *  deleting the packages base directories through installd
10562     *  updating mSettings to reflect current status
10563     *  persisting settings for later use
10564     *  sending a broadcast if necessary
10565     */
10566    private int deletePackageX(String packageName, int userId, int flags) {
10567        final PackageRemovedInfo info = new PackageRemovedInfo();
10568        final boolean res;
10569
10570        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10571                ? UserHandle.ALL : new UserHandle(userId);
10572
10573        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10574            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10575            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10576        }
10577
10578        boolean removedForAllUsers = false;
10579        boolean systemUpdate = false;
10580
10581        // for the uninstall-updates case and restricted profiles, remember the per-
10582        // userhandle installed state
10583        int[] allUsers;
10584        boolean[] perUserInstalled;
10585        synchronized (mPackages) {
10586            PackageSetting ps = mSettings.mPackages.get(packageName);
10587            allUsers = sUserManager.getUserIds();
10588            perUserInstalled = new boolean[allUsers.length];
10589            for (int i = 0; i < allUsers.length; i++) {
10590                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10591            }
10592        }
10593
10594        synchronized (mInstallLock) {
10595            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10596            res = deletePackageLI(packageName, removeForUser,
10597                    true, allUsers, perUserInstalled,
10598                    flags | REMOVE_CHATTY, info, true);
10599            systemUpdate = info.isRemovedPackageSystemUpdate;
10600            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10601                removedForAllUsers = true;
10602            }
10603            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10604                    + " removedForAllUsers=" + removedForAllUsers);
10605        }
10606
10607        if (res) {
10608            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10609
10610            // If the removed package was a system update, the old system package
10611            // was re-enabled; we need to broadcast this information
10612            if (systemUpdate) {
10613                Bundle extras = new Bundle(1);
10614                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10615                        ? info.removedAppId : info.uid);
10616                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10617
10618                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10619                        extras, null, null, null);
10620                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10621                        extras, null, null, null);
10622                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10623                        null, packageName, null, null);
10624            }
10625        }
10626        // Force a gc here.
10627        Runtime.getRuntime().gc();
10628        // Delete the resources here after sending the broadcast to let
10629        // other processes clean up before deleting resources.
10630        if (info.args != null) {
10631            synchronized (mInstallLock) {
10632                info.args.doPostDeleteLI(true);
10633            }
10634        }
10635
10636        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10637    }
10638
10639    static class PackageRemovedInfo {
10640        String removedPackage;
10641        int uid = -1;
10642        int removedAppId = -1;
10643        int[] removedUsers = null;
10644        boolean isRemovedPackageSystemUpdate = false;
10645        // Clean up resources deleted packages.
10646        InstallArgs args = null;
10647
10648        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10649            Bundle extras = new Bundle(1);
10650            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10651            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10652            if (replacing) {
10653                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10654            }
10655            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10656            if (removedPackage != null) {
10657                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10658                        extras, null, null, removedUsers);
10659                if (fullRemove && !replacing) {
10660                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10661                            extras, null, null, removedUsers);
10662                }
10663            }
10664            if (removedAppId >= 0) {
10665                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10666                        removedUsers);
10667            }
10668        }
10669    }
10670
10671    /*
10672     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10673     * flag is not set, the data directory is removed as well.
10674     * make sure this flag is set for partially installed apps. If not its meaningless to
10675     * delete a partially installed application.
10676     */
10677    private void removePackageDataLI(PackageSetting ps,
10678            int[] allUserHandles, boolean[] perUserInstalled,
10679            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10680        String packageName = ps.name;
10681        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10682        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10683        // Retrieve object to delete permissions for shared user later on
10684        final PackageSetting deletedPs;
10685        // reader
10686        synchronized (mPackages) {
10687            deletedPs = mSettings.mPackages.get(packageName);
10688            if (outInfo != null) {
10689                outInfo.removedPackage = packageName;
10690                outInfo.removedUsers = deletedPs != null
10691                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10692                        : null;
10693            }
10694        }
10695        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10696            removeDataDirsLI(packageName);
10697            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10698        }
10699        // writer
10700        synchronized (mPackages) {
10701            if (deletedPs != null) {
10702                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10703                    if (outInfo != null) {
10704                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10705                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10706                    }
10707                    if (deletedPs != null) {
10708                        updatePermissionsLPw(deletedPs.name, null, 0);
10709                        if (deletedPs.sharedUser != null) {
10710                            // remove permissions associated with package
10711                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10712                        }
10713                    }
10714                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10715                }
10716                // make sure to preserve per-user disabled state if this removal was just
10717                // a downgrade of a system app to the factory package
10718                if (allUserHandles != null && perUserInstalled != null) {
10719                    if (DEBUG_REMOVE) {
10720                        Slog.d(TAG, "Propagating install state across downgrade");
10721                    }
10722                    for (int i = 0; i < allUserHandles.length; i++) {
10723                        if (DEBUG_REMOVE) {
10724                            Slog.d(TAG, "    user " + allUserHandles[i]
10725                                    + " => " + perUserInstalled[i]);
10726                        }
10727                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10728                    }
10729                }
10730            }
10731            // can downgrade to reader
10732            if (writeSettings) {
10733                // Save settings now
10734                mSettings.writeLPr();
10735            }
10736        }
10737        if (outInfo != null) {
10738            // A user ID was deleted here. Go through all users and remove it
10739            // from KeyStore.
10740            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10741        }
10742    }
10743
10744    static boolean locationIsPrivileged(File path) {
10745        try {
10746            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10747                    .getCanonicalPath();
10748            return path.getCanonicalPath().startsWith(privilegedAppDir);
10749        } catch (IOException e) {
10750            Slog.e(TAG, "Unable to access code path " + path);
10751        }
10752        return false;
10753    }
10754
10755    /*
10756     * Tries to delete system package.
10757     */
10758    private boolean deleteSystemPackageLI(PackageSetting newPs,
10759            int[] allUserHandles, boolean[] perUserInstalled,
10760            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10761        final boolean applyUserRestrictions
10762                = (allUserHandles != null) && (perUserInstalled != null);
10763        PackageSetting disabledPs = null;
10764        // Confirm if the system package has been updated
10765        // An updated system app can be deleted. This will also have to restore
10766        // the system pkg from system partition
10767        // reader
10768        synchronized (mPackages) {
10769            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10770        }
10771        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10772                + " disabledPs=" + disabledPs);
10773        if (disabledPs == null) {
10774            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10775            return false;
10776        } else if (DEBUG_REMOVE) {
10777            Slog.d(TAG, "Deleting system pkg from data partition");
10778        }
10779        if (DEBUG_REMOVE) {
10780            if (applyUserRestrictions) {
10781                Slog.d(TAG, "Remembering install states:");
10782                for (int i = 0; i < allUserHandles.length; i++) {
10783                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10784                }
10785            }
10786        }
10787        // Delete the updated package
10788        outInfo.isRemovedPackageSystemUpdate = true;
10789        if (disabledPs.versionCode < newPs.versionCode) {
10790            // Delete data for downgrades
10791            flags &= ~PackageManager.DELETE_KEEP_DATA;
10792        } else {
10793            // Preserve data by setting flag
10794            flags |= PackageManager.DELETE_KEEP_DATA;
10795        }
10796        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10797                allUserHandles, perUserInstalled, outInfo, writeSettings);
10798        if (!ret) {
10799            return false;
10800        }
10801        // writer
10802        synchronized (mPackages) {
10803            // Reinstate the old system package
10804            mSettings.enableSystemPackageLPw(newPs.name);
10805            // Remove any native libraries from the upgraded package.
10806            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10807        }
10808        // Install the system package
10809        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10810        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10811        if (locationIsPrivileged(disabledPs.codePath)) {
10812            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10813        }
10814
10815        final PackageParser.Package newPkg;
10816        try {
10817            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10818        } catch (PackageManagerException e) {
10819            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10820            return false;
10821        }
10822
10823        // writer
10824        synchronized (mPackages) {
10825            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10826            updatePermissionsLPw(newPkg.packageName, newPkg,
10827                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10828            if (applyUserRestrictions) {
10829                if (DEBUG_REMOVE) {
10830                    Slog.d(TAG, "Propagating install state across reinstall");
10831                }
10832                for (int i = 0; i < allUserHandles.length; i++) {
10833                    if (DEBUG_REMOVE) {
10834                        Slog.d(TAG, "    user " + allUserHandles[i]
10835                                + " => " + perUserInstalled[i]);
10836                    }
10837                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10838                }
10839                // Regardless of writeSettings we need to ensure that this restriction
10840                // state propagation is persisted
10841                mSettings.writeAllUsersPackageRestrictionsLPr();
10842            }
10843            // can downgrade to reader here
10844            if (writeSettings) {
10845                mSettings.writeLPr();
10846            }
10847        }
10848        return true;
10849    }
10850
10851    private boolean deleteInstalledPackageLI(PackageSetting ps,
10852            boolean deleteCodeAndResources, int flags,
10853            int[] allUserHandles, boolean[] perUserInstalled,
10854            PackageRemovedInfo outInfo, boolean writeSettings) {
10855        if (outInfo != null) {
10856            outInfo.uid = ps.appId;
10857        }
10858
10859        // Delete package data from internal structures and also remove data if flag is set
10860        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10861
10862        // Delete application code and resources
10863        if (deleteCodeAndResources && (outInfo != null)) {
10864            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10865                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10866                    getAppDexInstructionSets(ps));
10867            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10868        }
10869        return true;
10870    }
10871
10872    @Override
10873    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10874            int userId) {
10875        mContext.enforceCallingOrSelfPermission(
10876                android.Manifest.permission.DELETE_PACKAGES, null);
10877        synchronized (mPackages) {
10878            PackageSetting ps = mSettings.mPackages.get(packageName);
10879            if (ps == null) {
10880                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10881                return false;
10882            }
10883            if (!ps.getInstalled(userId)) {
10884                // Can't block uninstall for an app that is not installed or enabled.
10885                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10886                return false;
10887            }
10888            ps.setBlockUninstall(blockUninstall, userId);
10889            mSettings.writePackageRestrictionsLPr(userId);
10890        }
10891        return true;
10892    }
10893
10894    @Override
10895    public boolean getBlockUninstallForUser(String packageName, int userId) {
10896        synchronized (mPackages) {
10897            PackageSetting ps = mSettings.mPackages.get(packageName);
10898            if (ps == null) {
10899                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10900                return false;
10901            }
10902            return ps.getBlockUninstall(userId);
10903        }
10904    }
10905
10906    /*
10907     * This method handles package deletion in general
10908     */
10909    private boolean deletePackageLI(String packageName, UserHandle user,
10910            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10911            int flags, PackageRemovedInfo outInfo,
10912            boolean writeSettings) {
10913        if (packageName == null) {
10914            Slog.w(TAG, "Attempt to delete null packageName.");
10915            return false;
10916        }
10917        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10918        PackageSetting ps;
10919        boolean dataOnly = false;
10920        int removeUser = -1;
10921        int appId = -1;
10922        synchronized (mPackages) {
10923            ps = mSettings.mPackages.get(packageName);
10924            if (ps == null) {
10925                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10926                return false;
10927            }
10928            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10929                    && user.getIdentifier() != UserHandle.USER_ALL) {
10930                // The caller is asking that the package only be deleted for a single
10931                // user.  To do this, we just mark its uninstalled state and delete
10932                // its data.  If this is a system app, we only allow this to happen if
10933                // they have set the special DELETE_SYSTEM_APP which requests different
10934                // semantics than normal for uninstalling system apps.
10935                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10936                ps.setUserState(user.getIdentifier(),
10937                        COMPONENT_ENABLED_STATE_DEFAULT,
10938                        false, //installed
10939                        true,  //stopped
10940                        true,  //notLaunched
10941                        false, //hidden
10942                        null, null, null,
10943                        false // blockUninstall
10944                        );
10945                if (!isSystemApp(ps)) {
10946                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10947                        // Other user still have this package installed, so all
10948                        // we need to do is clear this user's data and save that
10949                        // it is uninstalled.
10950                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10951                        removeUser = user.getIdentifier();
10952                        appId = ps.appId;
10953                        mSettings.writePackageRestrictionsLPr(removeUser);
10954                    } else {
10955                        // We need to set it back to 'installed' so the uninstall
10956                        // broadcasts will be sent correctly.
10957                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10958                        ps.setInstalled(true, user.getIdentifier());
10959                    }
10960                } else {
10961                    // This is a system app, so we assume that the
10962                    // other users still have this package installed, so all
10963                    // we need to do is clear this user's data and save that
10964                    // it is uninstalled.
10965                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10966                    removeUser = user.getIdentifier();
10967                    appId = ps.appId;
10968                    mSettings.writePackageRestrictionsLPr(removeUser);
10969                }
10970            }
10971        }
10972
10973        if (removeUser >= 0) {
10974            // From above, we determined that we are deleting this only
10975            // for a single user.  Continue the work here.
10976            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10977            if (outInfo != null) {
10978                outInfo.removedPackage = packageName;
10979                outInfo.removedAppId = appId;
10980                outInfo.removedUsers = new int[] {removeUser};
10981            }
10982            mInstaller.clearUserData(packageName, removeUser);
10983            removeKeystoreDataIfNeeded(removeUser, appId);
10984            schedulePackageCleaning(packageName, removeUser, false);
10985            return true;
10986        }
10987
10988        if (dataOnly) {
10989            // Delete application data first
10990            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10991            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10992            return true;
10993        }
10994
10995        boolean ret = false;
10996        if (isSystemApp(ps)) {
10997            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10998            // When an updated system application is deleted we delete the existing resources as well and
10999            // fall back to existing code in system partition
11000            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11001                    flags, outInfo, writeSettings);
11002        } else {
11003            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11004            // Kill application pre-emptively especially for apps on sd.
11005            killApplication(packageName, ps.appId, "uninstall pkg");
11006            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11007                    allUserHandles, perUserInstalled,
11008                    outInfo, writeSettings);
11009        }
11010
11011        return ret;
11012    }
11013
11014    private final class ClearStorageConnection implements ServiceConnection {
11015        IMediaContainerService mContainerService;
11016
11017        @Override
11018        public void onServiceConnected(ComponentName name, IBinder service) {
11019            synchronized (this) {
11020                mContainerService = IMediaContainerService.Stub.asInterface(service);
11021                notifyAll();
11022            }
11023        }
11024
11025        @Override
11026        public void onServiceDisconnected(ComponentName name) {
11027        }
11028    }
11029
11030    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11031        final boolean mounted;
11032        if (Environment.isExternalStorageEmulated()) {
11033            mounted = true;
11034        } else {
11035            final String status = Environment.getExternalStorageState();
11036
11037            mounted = status.equals(Environment.MEDIA_MOUNTED)
11038                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11039        }
11040
11041        if (!mounted) {
11042            return;
11043        }
11044
11045        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11046        int[] users;
11047        if (userId == UserHandle.USER_ALL) {
11048            users = sUserManager.getUserIds();
11049        } else {
11050            users = new int[] { userId };
11051        }
11052        final ClearStorageConnection conn = new ClearStorageConnection();
11053        if (mContext.bindServiceAsUser(
11054                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11055            try {
11056                for (int curUser : users) {
11057                    long timeout = SystemClock.uptimeMillis() + 5000;
11058                    synchronized (conn) {
11059                        long now = SystemClock.uptimeMillis();
11060                        while (conn.mContainerService == null && now < timeout) {
11061                            try {
11062                                conn.wait(timeout - now);
11063                            } catch (InterruptedException e) {
11064                            }
11065                        }
11066                    }
11067                    if (conn.mContainerService == null) {
11068                        return;
11069                    }
11070
11071                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11072                    clearDirectory(conn.mContainerService,
11073                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11074                    if (allData) {
11075                        clearDirectory(conn.mContainerService,
11076                                userEnv.buildExternalStorageAppDataDirs(packageName));
11077                        clearDirectory(conn.mContainerService,
11078                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11079                    }
11080                }
11081            } finally {
11082                mContext.unbindService(conn);
11083            }
11084        }
11085    }
11086
11087    @Override
11088    public void clearApplicationUserData(final String packageName,
11089            final IPackageDataObserver observer, final int userId) {
11090        mContext.enforceCallingOrSelfPermission(
11091                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11092        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11093        // Queue up an async operation since the package deletion may take a little while.
11094        mHandler.post(new Runnable() {
11095            public void run() {
11096                mHandler.removeCallbacks(this);
11097                final boolean succeeded;
11098                synchronized (mInstallLock) {
11099                    succeeded = clearApplicationUserDataLI(packageName, userId);
11100                }
11101                clearExternalStorageDataSync(packageName, userId, true);
11102                if (succeeded) {
11103                    // invoke DeviceStorageMonitor's update method to clear any notifications
11104                    DeviceStorageMonitorInternal
11105                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11106                    if (dsm != null) {
11107                        dsm.checkMemory();
11108                    }
11109                }
11110                if(observer != null) {
11111                    try {
11112                        observer.onRemoveCompleted(packageName, succeeded);
11113                    } catch (RemoteException e) {
11114                        Log.i(TAG, "Observer no longer exists.");
11115                    }
11116                } //end if observer
11117            } //end run
11118        });
11119    }
11120
11121    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11122        if (packageName == null) {
11123            Slog.w(TAG, "Attempt to delete null packageName.");
11124            return false;
11125        }
11126
11127        // Try finding details about the requested package
11128        PackageParser.Package pkg;
11129        synchronized (mPackages) {
11130            pkg = mPackages.get(packageName);
11131            if (pkg == null) {
11132                final PackageSetting ps = mSettings.mPackages.get(packageName);
11133                if (ps != null) {
11134                    pkg = ps.pkg;
11135                }
11136            }
11137        }
11138
11139        if (pkg == null) {
11140            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11141        }
11142
11143        // Always delete data directories for package, even if we found no other
11144        // record of app. This helps users recover from UID mismatches without
11145        // resorting to a full data wipe.
11146        int retCode = mInstaller.clearUserData(packageName, userId);
11147        if (retCode < 0) {
11148            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11149            return false;
11150        }
11151
11152        if (pkg == null) {
11153            return false;
11154        }
11155
11156        if (pkg != null && pkg.applicationInfo != null) {
11157            final int appId = pkg.applicationInfo.uid;
11158            removeKeystoreDataIfNeeded(userId, appId);
11159        }
11160
11161        // Create a native library symlink only if we have native libraries
11162        // and if the native libraries are 32 bit libraries. We do not provide
11163        // this symlink for 64 bit libraries.
11164        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11165                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11166            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11167            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11168                Slog.w(TAG, "Failed linking native library dir");
11169                return false;
11170            }
11171        }
11172
11173        return true;
11174    }
11175
11176    /**
11177     * Remove entries from the keystore daemon. Will only remove it if the
11178     * {@code appId} is valid.
11179     */
11180    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11181        if (appId < 0) {
11182            return;
11183        }
11184
11185        final KeyStore keyStore = KeyStore.getInstance();
11186        if (keyStore != null) {
11187            if (userId == UserHandle.USER_ALL) {
11188                for (final int individual : sUserManager.getUserIds()) {
11189                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11190                }
11191            } else {
11192                keyStore.clearUid(UserHandle.getUid(userId, appId));
11193            }
11194        } else {
11195            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11196        }
11197    }
11198
11199    @Override
11200    public void deleteApplicationCacheFiles(final String packageName,
11201            final IPackageDataObserver observer) {
11202        mContext.enforceCallingOrSelfPermission(
11203                android.Manifest.permission.DELETE_CACHE_FILES, null);
11204        // Queue up an async operation since the package deletion may take a little while.
11205        final int userId = UserHandle.getCallingUserId();
11206        mHandler.post(new Runnable() {
11207            public void run() {
11208                mHandler.removeCallbacks(this);
11209                final boolean succeded;
11210                synchronized (mInstallLock) {
11211                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11212                }
11213                clearExternalStorageDataSync(packageName, userId, false);
11214                if(observer != null) {
11215                    try {
11216                        observer.onRemoveCompleted(packageName, succeded);
11217                    } catch (RemoteException e) {
11218                        Log.i(TAG, "Observer no longer exists.");
11219                    }
11220                } //end if observer
11221            } //end run
11222        });
11223    }
11224
11225    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11226        if (packageName == null) {
11227            Slog.w(TAG, "Attempt to delete null packageName.");
11228            return false;
11229        }
11230        PackageParser.Package p;
11231        synchronized (mPackages) {
11232            p = mPackages.get(packageName);
11233        }
11234        if (p == null) {
11235            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11236            return false;
11237        }
11238        final ApplicationInfo applicationInfo = p.applicationInfo;
11239        if (applicationInfo == null) {
11240            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11241            return false;
11242        }
11243        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11244        if (retCode < 0) {
11245            Slog.w(TAG, "Couldn't remove cache files for package: "
11246                       + packageName + " u" + userId);
11247            return false;
11248        }
11249        return true;
11250    }
11251
11252    @Override
11253    public void getPackageSizeInfo(final String packageName, int userHandle,
11254            final IPackageStatsObserver observer) {
11255        mContext.enforceCallingOrSelfPermission(
11256                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11257        if (packageName == null) {
11258            throw new IllegalArgumentException("Attempt to get size of null packageName");
11259        }
11260
11261        PackageStats stats = new PackageStats(packageName, userHandle);
11262
11263        /*
11264         * Queue up an async operation since the package measurement may take a
11265         * little while.
11266         */
11267        Message msg = mHandler.obtainMessage(INIT_COPY);
11268        msg.obj = new MeasureParams(stats, observer);
11269        mHandler.sendMessage(msg);
11270    }
11271
11272    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11273            PackageStats pStats) {
11274        if (packageName == null) {
11275            Slog.w(TAG, "Attempt to get size of null packageName.");
11276            return false;
11277        }
11278        PackageParser.Package p;
11279        boolean dataOnly = false;
11280        String libDirRoot = null;
11281        String asecPath = null;
11282        PackageSetting ps = null;
11283        synchronized (mPackages) {
11284            p = mPackages.get(packageName);
11285            ps = mSettings.mPackages.get(packageName);
11286            if(p == null) {
11287                dataOnly = true;
11288                if((ps == null) || (ps.pkg == null)) {
11289                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11290                    return false;
11291                }
11292                p = ps.pkg;
11293            }
11294            if (ps != null) {
11295                libDirRoot = ps.legacyNativeLibraryPathString;
11296            }
11297            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11298                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11299                if (secureContainerId != null) {
11300                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11301                }
11302            }
11303        }
11304        String publicSrcDir = null;
11305        if(!dataOnly) {
11306            final ApplicationInfo applicationInfo = p.applicationInfo;
11307            if (applicationInfo == null) {
11308                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11309                return false;
11310            }
11311            if (isForwardLocked(p)) {
11312                publicSrcDir = applicationInfo.getBaseResourcePath();
11313            }
11314        }
11315        // TODO: extend to measure size of split APKs
11316        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11317        // not just the first level.
11318        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11319        // just the primary.
11320        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11321        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11322                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11323        if (res < 0) {
11324            return false;
11325        }
11326
11327        // Fix-up for forward-locked applications in ASEC containers.
11328        if (!isExternal(p)) {
11329            pStats.codeSize += pStats.externalCodeSize;
11330            pStats.externalCodeSize = 0L;
11331        }
11332
11333        return true;
11334    }
11335
11336
11337    @Override
11338    public void addPackageToPreferred(String packageName) {
11339        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11340    }
11341
11342    @Override
11343    public void removePackageFromPreferred(String packageName) {
11344        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11345    }
11346
11347    @Override
11348    public List<PackageInfo> getPreferredPackages(int flags) {
11349        return new ArrayList<PackageInfo>();
11350    }
11351
11352    private int getUidTargetSdkVersionLockedLPr(int uid) {
11353        Object obj = mSettings.getUserIdLPr(uid);
11354        if (obj instanceof SharedUserSetting) {
11355            final SharedUserSetting sus = (SharedUserSetting) obj;
11356            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11357            final Iterator<PackageSetting> it = sus.packages.iterator();
11358            while (it.hasNext()) {
11359                final PackageSetting ps = it.next();
11360                if (ps.pkg != null) {
11361                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11362                    if (v < vers) vers = v;
11363                }
11364            }
11365            return vers;
11366        } else if (obj instanceof PackageSetting) {
11367            final PackageSetting ps = (PackageSetting) obj;
11368            if (ps.pkg != null) {
11369                return ps.pkg.applicationInfo.targetSdkVersion;
11370            }
11371        }
11372        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11373    }
11374
11375    @Override
11376    public void addPreferredActivity(IntentFilter filter, int match,
11377            ComponentName[] set, ComponentName activity, int userId) {
11378        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11379                "Adding preferred");
11380    }
11381
11382    private void addPreferredActivityInternal(IntentFilter filter, int match,
11383            ComponentName[] set, ComponentName activity, boolean always, int userId,
11384            String opname) {
11385        // writer
11386        int callingUid = Binder.getCallingUid();
11387        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11388        if (filter.countActions() == 0) {
11389            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11390            return;
11391        }
11392        synchronized (mPackages) {
11393            if (mContext.checkCallingOrSelfPermission(
11394                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11395                    != PackageManager.PERMISSION_GRANTED) {
11396                if (getUidTargetSdkVersionLockedLPr(callingUid)
11397                        < Build.VERSION_CODES.FROYO) {
11398                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11399                            + callingUid);
11400                    return;
11401                }
11402                mContext.enforceCallingOrSelfPermission(
11403                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11404            }
11405
11406            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11407            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11408                    + userId + ":");
11409            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11410            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11411            mSettings.writePackageRestrictionsLPr(userId);
11412        }
11413    }
11414
11415    @Override
11416    public void replacePreferredActivity(IntentFilter filter, int match,
11417            ComponentName[] set, ComponentName activity, int userId) {
11418        if (filter.countActions() != 1) {
11419            throw new IllegalArgumentException(
11420                    "replacePreferredActivity expects filter to have only 1 action.");
11421        }
11422        if (filter.countDataAuthorities() != 0
11423                || filter.countDataPaths() != 0
11424                || filter.countDataSchemes() > 1
11425                || filter.countDataTypes() != 0) {
11426            throw new IllegalArgumentException(
11427                    "replacePreferredActivity expects filter to have no data authorities, " +
11428                    "paths, or types; and at most one scheme.");
11429        }
11430
11431        final int callingUid = Binder.getCallingUid();
11432        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11433        synchronized (mPackages) {
11434            if (mContext.checkCallingOrSelfPermission(
11435                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11436                    != PackageManager.PERMISSION_GRANTED) {
11437                if (getUidTargetSdkVersionLockedLPr(callingUid)
11438                        < Build.VERSION_CODES.FROYO) {
11439                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11440                            + Binder.getCallingUid());
11441                    return;
11442                }
11443                mContext.enforceCallingOrSelfPermission(
11444                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11445            }
11446
11447            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11448            if (pir != null) {
11449                // Get all of the existing entries that exactly match this filter.
11450                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11451                if (existing != null && existing.size() == 1) {
11452                    PreferredActivity cur = existing.get(0);
11453                    if (DEBUG_PREFERRED) {
11454                        Slog.i(TAG, "Checking replace of preferred:");
11455                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11456                        if (!cur.mPref.mAlways) {
11457                            Slog.i(TAG, "  -- CUR; not mAlways!");
11458                        } else {
11459                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11460                            Slog.i(TAG, "  -- CUR: mSet="
11461                                    + Arrays.toString(cur.mPref.mSetComponents));
11462                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11463                            Slog.i(TAG, "  -- NEW: mMatch="
11464                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11465                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11466                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11467                        }
11468                    }
11469                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11470                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11471                            && cur.mPref.sameSet(set)) {
11472                        // Setting the preferred activity to what it happens to be already
11473                        if (DEBUG_PREFERRED) {
11474                            Slog.i(TAG, "Replacing with same preferred activity "
11475                                    + cur.mPref.mShortComponent + " for user "
11476                                    + userId + ":");
11477                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11478                        }
11479                        return;
11480                    }
11481                }
11482
11483                if (existing != null) {
11484                    if (DEBUG_PREFERRED) {
11485                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11486                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11487                    }
11488                    for (int i = 0; i < existing.size(); i++) {
11489                        PreferredActivity pa = existing.get(i);
11490                        if (DEBUG_PREFERRED) {
11491                            Slog.i(TAG, "Removing existing preferred activity "
11492                                    + pa.mPref.mComponent + ":");
11493                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11494                        }
11495                        pir.removeFilter(pa);
11496                    }
11497                }
11498            }
11499            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11500                    "Replacing preferred");
11501        }
11502    }
11503
11504    @Override
11505    public void clearPackagePreferredActivities(String packageName) {
11506        final int uid = Binder.getCallingUid();
11507        // writer
11508        synchronized (mPackages) {
11509            PackageParser.Package pkg = mPackages.get(packageName);
11510            if (pkg == null || pkg.applicationInfo.uid != uid) {
11511                if (mContext.checkCallingOrSelfPermission(
11512                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11513                        != PackageManager.PERMISSION_GRANTED) {
11514                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11515                            < Build.VERSION_CODES.FROYO) {
11516                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11517                                + Binder.getCallingUid());
11518                        return;
11519                    }
11520                    mContext.enforceCallingOrSelfPermission(
11521                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11522                }
11523            }
11524
11525            int user = UserHandle.getCallingUserId();
11526            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11527                mSettings.writePackageRestrictionsLPr(user);
11528                scheduleWriteSettingsLocked();
11529            }
11530        }
11531    }
11532
11533    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11534    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11535        ArrayList<PreferredActivity> removed = null;
11536        boolean changed = false;
11537        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11538            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11539            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11540            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11541                continue;
11542            }
11543            Iterator<PreferredActivity> it = pir.filterIterator();
11544            while (it.hasNext()) {
11545                PreferredActivity pa = it.next();
11546                // Mark entry for removal only if it matches the package name
11547                // and the entry is of type "always".
11548                if (packageName == null ||
11549                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11550                                && pa.mPref.mAlways)) {
11551                    if (removed == null) {
11552                        removed = new ArrayList<PreferredActivity>();
11553                    }
11554                    removed.add(pa);
11555                }
11556            }
11557            if (removed != null) {
11558                for (int j=0; j<removed.size(); j++) {
11559                    PreferredActivity pa = removed.get(j);
11560                    pir.removeFilter(pa);
11561                }
11562                changed = true;
11563            }
11564        }
11565        return changed;
11566    }
11567
11568    @Override
11569    public void resetPreferredActivities(int userId) {
11570        /* TODO: Actually use userId. Why is it being passed in? */
11571        mContext.enforceCallingOrSelfPermission(
11572                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11573        // writer
11574        synchronized (mPackages) {
11575            int user = UserHandle.getCallingUserId();
11576            clearPackagePreferredActivitiesLPw(null, user);
11577            mSettings.readDefaultPreferredAppsLPw(this, user);
11578            mSettings.writePackageRestrictionsLPr(user);
11579            scheduleWriteSettingsLocked();
11580        }
11581    }
11582
11583    @Override
11584    public int getPreferredActivities(List<IntentFilter> outFilters,
11585            List<ComponentName> outActivities, String packageName) {
11586
11587        int num = 0;
11588        final int userId = UserHandle.getCallingUserId();
11589        // reader
11590        synchronized (mPackages) {
11591            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11592            if (pir != null) {
11593                final Iterator<PreferredActivity> it = pir.filterIterator();
11594                while (it.hasNext()) {
11595                    final PreferredActivity pa = it.next();
11596                    if (packageName == null
11597                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11598                                    && pa.mPref.mAlways)) {
11599                        if (outFilters != null) {
11600                            outFilters.add(new IntentFilter(pa));
11601                        }
11602                        if (outActivities != null) {
11603                            outActivities.add(pa.mPref.mComponent);
11604                        }
11605                    }
11606                }
11607            }
11608        }
11609
11610        return num;
11611    }
11612
11613    @Override
11614    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11615            int userId) {
11616        int callingUid = Binder.getCallingUid();
11617        if (callingUid != Process.SYSTEM_UID) {
11618            throw new SecurityException(
11619                    "addPersistentPreferredActivity can only be run by the system");
11620        }
11621        if (filter.countActions() == 0) {
11622            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11623            return;
11624        }
11625        synchronized (mPackages) {
11626            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11627                    " :");
11628            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11629            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11630                    new PersistentPreferredActivity(filter, activity));
11631            mSettings.writePackageRestrictionsLPr(userId);
11632        }
11633    }
11634
11635    @Override
11636    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11637        int callingUid = Binder.getCallingUid();
11638        if (callingUid != Process.SYSTEM_UID) {
11639            throw new SecurityException(
11640                    "clearPackagePersistentPreferredActivities can only be run by the system");
11641        }
11642        ArrayList<PersistentPreferredActivity> removed = null;
11643        boolean changed = false;
11644        synchronized (mPackages) {
11645            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11646                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11647                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11648                        .valueAt(i);
11649                if (userId != thisUserId) {
11650                    continue;
11651                }
11652                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11653                while (it.hasNext()) {
11654                    PersistentPreferredActivity ppa = it.next();
11655                    // Mark entry for removal only if it matches the package name.
11656                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11657                        if (removed == null) {
11658                            removed = new ArrayList<PersistentPreferredActivity>();
11659                        }
11660                        removed.add(ppa);
11661                    }
11662                }
11663                if (removed != null) {
11664                    for (int j=0; j<removed.size(); j++) {
11665                        PersistentPreferredActivity ppa = removed.get(j);
11666                        ppir.removeFilter(ppa);
11667                    }
11668                    changed = true;
11669                }
11670            }
11671
11672            if (changed) {
11673                mSettings.writePackageRestrictionsLPr(userId);
11674            }
11675        }
11676    }
11677
11678    @Override
11679    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11680            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11681        mContext.enforceCallingOrSelfPermission(
11682                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11683        int callingUid = Binder.getCallingUid();
11684        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11685        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11686        if (intentFilter.countActions() == 0) {
11687            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11688            return;
11689        }
11690        synchronized (mPackages) {
11691            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11692                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11693            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11694            mSettings.writePackageRestrictionsLPr(sourceUserId);
11695        }
11696    }
11697
11698    @Override
11699    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11700            int ownerUserId) {
11701        mContext.enforceCallingOrSelfPermission(
11702                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11703        int callingUid = Binder.getCallingUid();
11704        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11705        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11706        int callingUserId = UserHandle.getUserId(callingUid);
11707        synchronized (mPackages) {
11708            CrossProfileIntentResolver resolver =
11709                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11710            HashSet<CrossProfileIntentFilter> set =
11711                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11712            for (CrossProfileIntentFilter filter : set) {
11713                if (filter.getOwnerPackage().equals(ownerPackage)
11714                        && filter.getOwnerUserId() == callingUserId) {
11715                    resolver.removeFilter(filter);
11716                }
11717            }
11718            mSettings.writePackageRestrictionsLPr(sourceUserId);
11719        }
11720    }
11721
11722    // Enforcing that callingUid is owning pkg on userId
11723    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11724        // The system owns everything.
11725        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11726            return;
11727        }
11728        int callingUserId = UserHandle.getUserId(callingUid);
11729        if (callingUserId != userId) {
11730            throw new SecurityException("calling uid " + callingUid
11731                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11732                    + callingUserId);
11733        }
11734        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11735        if (pi == null) {
11736            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11737                    + callingUserId);
11738        }
11739        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11740            throw new SecurityException("Calling uid " + callingUid
11741                    + " does not own package " + pkg);
11742        }
11743    }
11744
11745    @Override
11746    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11747        Intent intent = new Intent(Intent.ACTION_MAIN);
11748        intent.addCategory(Intent.CATEGORY_HOME);
11749
11750        final int callingUserId = UserHandle.getCallingUserId();
11751        List<ResolveInfo> list = queryIntentActivities(intent, null,
11752                PackageManager.GET_META_DATA, callingUserId);
11753        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11754                true, false, false, callingUserId);
11755
11756        allHomeCandidates.clear();
11757        if (list != null) {
11758            for (ResolveInfo ri : list) {
11759                allHomeCandidates.add(ri);
11760            }
11761        }
11762        return (preferred == null || preferred.activityInfo == null)
11763                ? null
11764                : new ComponentName(preferred.activityInfo.packageName,
11765                        preferred.activityInfo.name);
11766    }
11767
11768    @Override
11769    public void setApplicationEnabledSetting(String appPackageName,
11770            int newState, int flags, int userId, String callingPackage) {
11771        if (!sUserManager.exists(userId)) return;
11772        if (callingPackage == null) {
11773            callingPackage = Integer.toString(Binder.getCallingUid());
11774        }
11775        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11776    }
11777
11778    @Override
11779    public void setComponentEnabledSetting(ComponentName componentName,
11780            int newState, int flags, int userId) {
11781        if (!sUserManager.exists(userId)) return;
11782        setEnabledSetting(componentName.getPackageName(),
11783                componentName.getClassName(), newState, flags, userId, null);
11784    }
11785
11786    private void setEnabledSetting(final String packageName, String className, int newState,
11787            final int flags, int userId, String callingPackage) {
11788        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11789              || newState == COMPONENT_ENABLED_STATE_ENABLED
11790              || newState == COMPONENT_ENABLED_STATE_DISABLED
11791              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11792              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11793            throw new IllegalArgumentException("Invalid new component state: "
11794                    + newState);
11795        }
11796        PackageSetting pkgSetting;
11797        final int uid = Binder.getCallingUid();
11798        final int permission = mContext.checkCallingOrSelfPermission(
11799                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11800        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11801        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11802        boolean sendNow = false;
11803        boolean isApp = (className == null);
11804        String componentName = isApp ? packageName : className;
11805        int packageUid = -1;
11806        ArrayList<String> components;
11807
11808        // writer
11809        synchronized (mPackages) {
11810            pkgSetting = mSettings.mPackages.get(packageName);
11811            if (pkgSetting == null) {
11812                if (className == null) {
11813                    throw new IllegalArgumentException(
11814                            "Unknown package: " + packageName);
11815                }
11816                throw new IllegalArgumentException(
11817                        "Unknown component: " + packageName
11818                        + "/" + className);
11819            }
11820            // Allow root and verify that userId is not being specified by a different user
11821            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11822                throw new SecurityException(
11823                        "Permission Denial: attempt to change component state from pid="
11824                        + Binder.getCallingPid()
11825                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11826            }
11827            if (className == null) {
11828                // We're dealing with an application/package level state change
11829                if (pkgSetting.getEnabled(userId) == newState) {
11830                    // Nothing to do
11831                    return;
11832                }
11833                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11834                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11835                    // Don't care about who enables an app.
11836                    callingPackage = null;
11837                }
11838                pkgSetting.setEnabled(newState, userId, callingPackage);
11839                // pkgSetting.pkg.mSetEnabled = newState;
11840            } else {
11841                // We're dealing with a component level state change
11842                // First, verify that this is a valid class name.
11843                PackageParser.Package pkg = pkgSetting.pkg;
11844                if (pkg == null || !pkg.hasComponentClassName(className)) {
11845                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11846                        throw new IllegalArgumentException("Component class " + className
11847                                + " does not exist in " + packageName);
11848                    } else {
11849                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11850                                + className + " does not exist in " + packageName);
11851                    }
11852                }
11853                switch (newState) {
11854                case COMPONENT_ENABLED_STATE_ENABLED:
11855                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11856                        return;
11857                    }
11858                    break;
11859                case COMPONENT_ENABLED_STATE_DISABLED:
11860                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11861                        return;
11862                    }
11863                    break;
11864                case COMPONENT_ENABLED_STATE_DEFAULT:
11865                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11866                        return;
11867                    }
11868                    break;
11869                default:
11870                    Slog.e(TAG, "Invalid new component state: " + newState);
11871                    return;
11872                }
11873            }
11874            mSettings.writePackageRestrictionsLPr(userId);
11875            components = mPendingBroadcasts.get(userId, packageName);
11876            final boolean newPackage = components == null;
11877            if (newPackage) {
11878                components = new ArrayList<String>();
11879            }
11880            if (!components.contains(componentName)) {
11881                components.add(componentName);
11882            }
11883            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11884                sendNow = true;
11885                // Purge entry from pending broadcast list if another one exists already
11886                // since we are sending one right away.
11887                mPendingBroadcasts.remove(userId, packageName);
11888            } else {
11889                if (newPackage) {
11890                    mPendingBroadcasts.put(userId, packageName, components);
11891                }
11892                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11893                    // Schedule a message
11894                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11895                }
11896            }
11897        }
11898
11899        long callingId = Binder.clearCallingIdentity();
11900        try {
11901            if (sendNow) {
11902                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11903                sendPackageChangedBroadcast(packageName,
11904                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11905            }
11906        } finally {
11907            Binder.restoreCallingIdentity(callingId);
11908        }
11909    }
11910
11911    private void sendPackageChangedBroadcast(String packageName,
11912            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11913        if (DEBUG_INSTALL)
11914            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11915                    + componentNames);
11916        Bundle extras = new Bundle(4);
11917        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11918        String nameList[] = new String[componentNames.size()];
11919        componentNames.toArray(nameList);
11920        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11921        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11922        extras.putInt(Intent.EXTRA_UID, packageUid);
11923        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11924                new int[] {UserHandle.getUserId(packageUid)});
11925    }
11926
11927    @Override
11928    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11929        if (!sUserManager.exists(userId)) return;
11930        final int uid = Binder.getCallingUid();
11931        final int permission = mContext.checkCallingOrSelfPermission(
11932                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11933        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11934        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11935        // writer
11936        synchronized (mPackages) {
11937            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11938                    uid, userId)) {
11939                scheduleWritePackageRestrictionsLocked(userId);
11940            }
11941        }
11942    }
11943
11944    @Override
11945    public String getInstallerPackageName(String packageName) {
11946        // reader
11947        synchronized (mPackages) {
11948            return mSettings.getInstallerPackageNameLPr(packageName);
11949        }
11950    }
11951
11952    @Override
11953    public int getApplicationEnabledSetting(String packageName, int userId) {
11954        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11955        int uid = Binder.getCallingUid();
11956        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11957        // reader
11958        synchronized (mPackages) {
11959            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11960        }
11961    }
11962
11963    @Override
11964    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11965        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11966        int uid = Binder.getCallingUid();
11967        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11968        // reader
11969        synchronized (mPackages) {
11970            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11971        }
11972    }
11973
11974    @Override
11975    public void enterSafeMode() {
11976        enforceSystemOrRoot("Only the system can request entering safe mode");
11977
11978        if (!mSystemReady) {
11979            mSafeMode = true;
11980        }
11981    }
11982
11983    @Override
11984    public void systemReady() {
11985        mSystemReady = true;
11986
11987        // Read the compatibilty setting when the system is ready.
11988        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11989                mContext.getContentResolver(),
11990                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11991        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11992        if (DEBUG_SETTINGS) {
11993            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11994        }
11995
11996        synchronized (mPackages) {
11997            // Verify that all of the preferred activity components actually
11998            // exist.  It is possible for applications to be updated and at
11999            // that point remove a previously declared activity component that
12000            // had been set as a preferred activity.  We try to clean this up
12001            // the next time we encounter that preferred activity, but it is
12002            // possible for the user flow to never be able to return to that
12003            // situation so here we do a sanity check to make sure we haven't
12004            // left any junk around.
12005            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12006            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12007                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12008                removed.clear();
12009                for (PreferredActivity pa : pir.filterSet()) {
12010                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12011                        removed.add(pa);
12012                    }
12013                }
12014                if (removed.size() > 0) {
12015                    for (int r=0; r<removed.size(); r++) {
12016                        PreferredActivity pa = removed.get(r);
12017                        Slog.w(TAG, "Removing dangling preferred activity: "
12018                                + pa.mPref.mComponent);
12019                        pir.removeFilter(pa);
12020                    }
12021                    mSettings.writePackageRestrictionsLPr(
12022                            mSettings.mPreferredActivities.keyAt(i));
12023                }
12024            }
12025        }
12026        sUserManager.systemReady();
12027
12028        // Kick off any messages waiting for system ready
12029        if (mPostSystemReadyMessages != null) {
12030            for (Message msg : mPostSystemReadyMessages) {
12031                msg.sendToTarget();
12032            }
12033            mPostSystemReadyMessages = null;
12034        }
12035    }
12036
12037    @Override
12038    public boolean isSafeMode() {
12039        return mSafeMode;
12040    }
12041
12042    @Override
12043    public boolean hasSystemUidErrors() {
12044        return mHasSystemUidErrors;
12045    }
12046
12047    static String arrayToString(int[] array) {
12048        StringBuffer buf = new StringBuffer(128);
12049        buf.append('[');
12050        if (array != null) {
12051            for (int i=0; i<array.length; i++) {
12052                if (i > 0) buf.append(", ");
12053                buf.append(array[i]);
12054            }
12055        }
12056        buf.append(']');
12057        return buf.toString();
12058    }
12059
12060    static class DumpState {
12061        public static final int DUMP_LIBS = 1 << 0;
12062        public static final int DUMP_FEATURES = 1 << 1;
12063        public static final int DUMP_RESOLVERS = 1 << 2;
12064        public static final int DUMP_PERMISSIONS = 1 << 3;
12065        public static final int DUMP_PACKAGES = 1 << 4;
12066        public static final int DUMP_SHARED_USERS = 1 << 5;
12067        public static final int DUMP_MESSAGES = 1 << 6;
12068        public static final int DUMP_PROVIDERS = 1 << 7;
12069        public static final int DUMP_VERIFIERS = 1 << 8;
12070        public static final int DUMP_PREFERRED = 1 << 9;
12071        public static final int DUMP_PREFERRED_XML = 1 << 10;
12072        public static final int DUMP_KEYSETS = 1 << 11;
12073        public static final int DUMP_VERSION = 1 << 12;
12074        public static final int DUMP_INSTALLS = 1 << 13;
12075
12076        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12077
12078        private int mTypes;
12079
12080        private int mOptions;
12081
12082        private boolean mTitlePrinted;
12083
12084        private SharedUserSetting mSharedUser;
12085
12086        public boolean isDumping(int type) {
12087            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12088                return true;
12089            }
12090
12091            return (mTypes & type) != 0;
12092        }
12093
12094        public void setDump(int type) {
12095            mTypes |= type;
12096        }
12097
12098        public boolean isOptionEnabled(int option) {
12099            return (mOptions & option) != 0;
12100        }
12101
12102        public void setOptionEnabled(int option) {
12103            mOptions |= option;
12104        }
12105
12106        public boolean onTitlePrinted() {
12107            final boolean printed = mTitlePrinted;
12108            mTitlePrinted = true;
12109            return printed;
12110        }
12111
12112        public boolean getTitlePrinted() {
12113            return mTitlePrinted;
12114        }
12115
12116        public void setTitlePrinted(boolean enabled) {
12117            mTitlePrinted = enabled;
12118        }
12119
12120        public SharedUserSetting getSharedUser() {
12121            return mSharedUser;
12122        }
12123
12124        public void setSharedUser(SharedUserSetting user) {
12125            mSharedUser = user;
12126        }
12127    }
12128
12129    @Override
12130    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12131        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12132                != PackageManager.PERMISSION_GRANTED) {
12133            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12134                    + Binder.getCallingPid()
12135                    + ", uid=" + Binder.getCallingUid()
12136                    + " without permission "
12137                    + android.Manifest.permission.DUMP);
12138            return;
12139        }
12140
12141        DumpState dumpState = new DumpState();
12142        boolean fullPreferred = false;
12143        boolean checkin = false;
12144
12145        String packageName = null;
12146
12147        int opti = 0;
12148        while (opti < args.length) {
12149            String opt = args[opti];
12150            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12151                break;
12152            }
12153            opti++;
12154
12155            if ("-a".equals(opt)) {
12156                // Right now we only know how to print all.
12157            } else if ("-h".equals(opt)) {
12158                pw.println("Package manager dump options:");
12159                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12160                pw.println("    --checkin: dump for a checkin");
12161                pw.println("    -f: print details of intent filters");
12162                pw.println("    -h: print this help");
12163                pw.println("  cmd may be one of:");
12164                pw.println("    l[ibraries]: list known shared libraries");
12165                pw.println("    f[ibraries]: list device features");
12166                pw.println("    k[eysets]: print known keysets");
12167                pw.println("    r[esolvers]: dump intent resolvers");
12168                pw.println("    perm[issions]: dump permissions");
12169                pw.println("    pref[erred]: print preferred package settings");
12170                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12171                pw.println("    prov[iders]: dump content providers");
12172                pw.println("    p[ackages]: dump installed packages");
12173                pw.println("    s[hared-users]: dump shared user IDs");
12174                pw.println("    m[essages]: print collected runtime messages");
12175                pw.println("    v[erifiers]: print package verifier info");
12176                pw.println("    version: print database version info");
12177                pw.println("    write: write current settings now");
12178                pw.println("    <package.name>: info about given package");
12179                pw.println("    installs: details about install sessions");
12180                return;
12181            } else if ("--checkin".equals(opt)) {
12182                checkin = true;
12183            } else if ("-f".equals(opt)) {
12184                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12185            } else {
12186                pw.println("Unknown argument: " + opt + "; use -h for help");
12187            }
12188        }
12189
12190        // Is the caller requesting to dump a particular piece of data?
12191        if (opti < args.length) {
12192            String cmd = args[opti];
12193            opti++;
12194            // Is this a package name?
12195            if ("android".equals(cmd) || cmd.contains(".")) {
12196                packageName = cmd;
12197                // When dumping a single package, we always dump all of its
12198                // filter information since the amount of data will be reasonable.
12199                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12200            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12201                dumpState.setDump(DumpState.DUMP_LIBS);
12202            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12203                dumpState.setDump(DumpState.DUMP_FEATURES);
12204            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12205                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12206            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12207                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12208            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12209                dumpState.setDump(DumpState.DUMP_PREFERRED);
12210            } else if ("preferred-xml".equals(cmd)) {
12211                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12212                if (opti < args.length && "--full".equals(args[opti])) {
12213                    fullPreferred = true;
12214                    opti++;
12215                }
12216            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12217                dumpState.setDump(DumpState.DUMP_PACKAGES);
12218            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12219                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12220            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12221                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12222            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12223                dumpState.setDump(DumpState.DUMP_MESSAGES);
12224            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12225                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12226            } else if ("version".equals(cmd)) {
12227                dumpState.setDump(DumpState.DUMP_VERSION);
12228            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12229                dumpState.setDump(DumpState.DUMP_KEYSETS);
12230            } else if ("installs".equals(cmd)) {
12231                dumpState.setDump(DumpState.DUMP_INSTALLS);
12232            } else if ("write".equals(cmd)) {
12233                synchronized (mPackages) {
12234                    mSettings.writeLPr();
12235                    pw.println("Settings written.");
12236                    return;
12237                }
12238            }
12239        }
12240
12241        if (checkin) {
12242            pw.println("vers,1");
12243        }
12244
12245        // reader
12246        synchronized (mPackages) {
12247            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12248                if (!checkin) {
12249                    if (dumpState.onTitlePrinted())
12250                        pw.println();
12251                    pw.println("Database versions:");
12252                    pw.print("  SDK Version:");
12253                    pw.print(" internal=");
12254                    pw.print(mSettings.mInternalSdkPlatform);
12255                    pw.print(" external=");
12256                    pw.println(mSettings.mExternalSdkPlatform);
12257                    pw.print("  DB Version:");
12258                    pw.print(" internal=");
12259                    pw.print(mSettings.mInternalDatabaseVersion);
12260                    pw.print(" external=");
12261                    pw.println(mSettings.mExternalDatabaseVersion);
12262                }
12263            }
12264
12265            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12266                if (!checkin) {
12267                    if (dumpState.onTitlePrinted())
12268                        pw.println();
12269                    pw.println("Verifiers:");
12270                    pw.print("  Required: ");
12271                    pw.print(mRequiredVerifierPackage);
12272                    pw.print(" (uid=");
12273                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12274                    pw.println(")");
12275                } else if (mRequiredVerifierPackage != null) {
12276                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12277                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12278                }
12279            }
12280
12281            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12282                boolean printedHeader = false;
12283                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12284                while (it.hasNext()) {
12285                    String name = it.next();
12286                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12287                    if (!checkin) {
12288                        if (!printedHeader) {
12289                            if (dumpState.onTitlePrinted())
12290                                pw.println();
12291                            pw.println("Libraries:");
12292                            printedHeader = true;
12293                        }
12294                        pw.print("  ");
12295                    } else {
12296                        pw.print("lib,");
12297                    }
12298                    pw.print(name);
12299                    if (!checkin) {
12300                        pw.print(" -> ");
12301                    }
12302                    if (ent.path != null) {
12303                        if (!checkin) {
12304                            pw.print("(jar) ");
12305                            pw.print(ent.path);
12306                        } else {
12307                            pw.print(",jar,");
12308                            pw.print(ent.path);
12309                        }
12310                    } else {
12311                        if (!checkin) {
12312                            pw.print("(apk) ");
12313                            pw.print(ent.apk);
12314                        } else {
12315                            pw.print(",apk,");
12316                            pw.print(ent.apk);
12317                        }
12318                    }
12319                    pw.println();
12320                }
12321            }
12322
12323            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12324                if (dumpState.onTitlePrinted())
12325                    pw.println();
12326                if (!checkin) {
12327                    pw.println("Features:");
12328                }
12329                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12330                while (it.hasNext()) {
12331                    String name = it.next();
12332                    if (!checkin) {
12333                        pw.print("  ");
12334                    } else {
12335                        pw.print("feat,");
12336                    }
12337                    pw.println(name);
12338                }
12339            }
12340
12341            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12342                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12343                        : "Activity Resolver Table:", "  ", packageName,
12344                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12345                    dumpState.setTitlePrinted(true);
12346                }
12347                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12348                        : "Receiver Resolver Table:", "  ", packageName,
12349                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12350                    dumpState.setTitlePrinted(true);
12351                }
12352                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12353                        : "Service Resolver Table:", "  ", packageName,
12354                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12355                    dumpState.setTitlePrinted(true);
12356                }
12357                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12358                        : "Provider Resolver Table:", "  ", packageName,
12359                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12360                    dumpState.setTitlePrinted(true);
12361                }
12362            }
12363
12364            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12365                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12366                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12367                    int user = mSettings.mPreferredActivities.keyAt(i);
12368                    if (pir.dump(pw,
12369                            dumpState.getTitlePrinted()
12370                                ? "\nPreferred Activities User " + user + ":"
12371                                : "Preferred Activities User " + user + ":", "  ",
12372                            packageName, true)) {
12373                        dumpState.setTitlePrinted(true);
12374                    }
12375                }
12376            }
12377
12378            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12379                pw.flush();
12380                FileOutputStream fout = new FileOutputStream(fd);
12381                BufferedOutputStream str = new BufferedOutputStream(fout);
12382                XmlSerializer serializer = new FastXmlSerializer();
12383                try {
12384                    serializer.setOutput(str, "utf-8");
12385                    serializer.startDocument(null, true);
12386                    serializer.setFeature(
12387                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12388                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12389                    serializer.endDocument();
12390                    serializer.flush();
12391                } catch (IllegalArgumentException e) {
12392                    pw.println("Failed writing: " + e);
12393                } catch (IllegalStateException e) {
12394                    pw.println("Failed writing: " + e);
12395                } catch (IOException e) {
12396                    pw.println("Failed writing: " + e);
12397                }
12398            }
12399
12400            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12401                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12402                if (packageName == null) {
12403                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12404                        if (iperm == 0) {
12405                            if (dumpState.onTitlePrinted())
12406                                pw.println();
12407                            pw.println("AppOp Permissions:");
12408                        }
12409                        pw.print("  AppOp Permission ");
12410                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12411                        pw.println(":");
12412                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12413                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12414                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12415                        }
12416                    }
12417                }
12418            }
12419
12420            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12421                boolean printedSomething = false;
12422                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12423                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12424                        continue;
12425                    }
12426                    if (!printedSomething) {
12427                        if (dumpState.onTitlePrinted())
12428                            pw.println();
12429                        pw.println("Registered ContentProviders:");
12430                        printedSomething = true;
12431                    }
12432                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12433                    pw.print("    "); pw.println(p.toString());
12434                }
12435                printedSomething = false;
12436                for (Map.Entry<String, PackageParser.Provider> entry :
12437                        mProvidersByAuthority.entrySet()) {
12438                    PackageParser.Provider p = entry.getValue();
12439                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12440                        continue;
12441                    }
12442                    if (!printedSomething) {
12443                        if (dumpState.onTitlePrinted())
12444                            pw.println();
12445                        pw.println("ContentProvider Authorities:");
12446                        printedSomething = true;
12447                    }
12448                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12449                    pw.print("    "); pw.println(p.toString());
12450                    if (p.info != null && p.info.applicationInfo != null) {
12451                        final String appInfo = p.info.applicationInfo.toString();
12452                        pw.print("      applicationInfo="); pw.println(appInfo);
12453                    }
12454                }
12455            }
12456
12457            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12458                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12459            }
12460
12461            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12462                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12463            }
12464
12465            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12466                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12467            }
12468
12469            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12470                // XXX should handle packageName != null by dumping only install data that
12471                // the given package is involved with.
12472                if (dumpState.onTitlePrinted()) pw.println();
12473                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12474            }
12475
12476            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12477                if (dumpState.onTitlePrinted()) pw.println();
12478                mSettings.dumpReadMessagesLPr(pw, dumpState);
12479
12480                pw.println();
12481                pw.println("Package warning messages:");
12482                final File fname = getSettingsProblemFile();
12483                FileInputStream in = null;
12484                try {
12485                    in = new FileInputStream(fname);
12486                    final int avail = in.available();
12487                    final byte[] data = new byte[avail];
12488                    in.read(data);
12489                    pw.print(new String(data));
12490                } catch (FileNotFoundException e) {
12491                } catch (IOException e) {
12492                } finally {
12493                    if (in != null) {
12494                        try {
12495                            in.close();
12496                        } catch (IOException e) {
12497                        }
12498                    }
12499                }
12500            }
12501
12502            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12503                BufferedReader in = null;
12504                String line = null;
12505                try {
12506                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12507                    while ((line = in.readLine()) != null) {
12508                        pw.print("msg,");
12509                        pw.println(line);
12510                    }
12511                } catch (IOException ignored) {
12512                } finally {
12513                    IoUtils.closeQuietly(in);
12514                }
12515            }
12516        }
12517    }
12518
12519    // ------- apps on sdcard specific code -------
12520    static final boolean DEBUG_SD_INSTALL = false;
12521
12522    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12523
12524    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12525
12526    private boolean mMediaMounted = false;
12527
12528    static String getEncryptKey() {
12529        try {
12530            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12531                    SD_ENCRYPTION_KEYSTORE_NAME);
12532            if (sdEncKey == null) {
12533                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12534                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12535                if (sdEncKey == null) {
12536                    Slog.e(TAG, "Failed to create encryption keys");
12537                    return null;
12538                }
12539            }
12540            return sdEncKey;
12541        } catch (NoSuchAlgorithmException nsae) {
12542            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12543            return null;
12544        } catch (IOException ioe) {
12545            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12546            return null;
12547        }
12548    }
12549
12550    /*
12551     * Update media status on PackageManager.
12552     */
12553    @Override
12554    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12555        int callingUid = Binder.getCallingUid();
12556        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12557            throw new SecurityException("Media status can only be updated by the system");
12558        }
12559        // reader; this apparently protects mMediaMounted, but should probably
12560        // be a different lock in that case.
12561        synchronized (mPackages) {
12562            Log.i(TAG, "Updating external media status from "
12563                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12564                    + (mediaStatus ? "mounted" : "unmounted"));
12565            if (DEBUG_SD_INSTALL)
12566                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12567                        + ", mMediaMounted=" + mMediaMounted);
12568            if (mediaStatus == mMediaMounted) {
12569                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12570                        : 0, -1);
12571                mHandler.sendMessage(msg);
12572                return;
12573            }
12574            mMediaMounted = mediaStatus;
12575        }
12576        // Queue up an async operation since the package installation may take a
12577        // little while.
12578        mHandler.post(new Runnable() {
12579            public void run() {
12580                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12581            }
12582        });
12583    }
12584
12585    /**
12586     * Called by MountService when the initial ASECs to scan are available.
12587     * Should block until all the ASEC containers are finished being scanned.
12588     */
12589    public void scanAvailableAsecs() {
12590        updateExternalMediaStatusInner(true, false, false);
12591        if (mShouldRestoreconData) {
12592            SELinuxMMAC.setRestoreconDone();
12593            mShouldRestoreconData = false;
12594        }
12595    }
12596
12597    /*
12598     * Collect information of applications on external media, map them against
12599     * existing containers and update information based on current mount status.
12600     * Please note that we always have to report status if reportStatus has been
12601     * set to true especially when unloading packages.
12602     */
12603    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12604            boolean externalStorage) {
12605        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12606        int[] uidArr = EmptyArray.INT;
12607
12608        final String[] list = PackageHelper.getSecureContainerList();
12609        if (ArrayUtils.isEmpty(list)) {
12610            Log.i(TAG, "No secure containers found");
12611        } else {
12612            // Process list of secure containers and categorize them
12613            // as active or stale based on their package internal state.
12614
12615            // reader
12616            synchronized (mPackages) {
12617                for (String cid : list) {
12618                    // Leave stages untouched for now; installer service owns them
12619                    if (PackageInstallerService.isStageName(cid)) continue;
12620
12621                    if (DEBUG_SD_INSTALL)
12622                        Log.i(TAG, "Processing container " + cid);
12623                    String pkgName = getAsecPackageName(cid);
12624                    if (pkgName == null) {
12625                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12626                        continue;
12627                    }
12628                    if (DEBUG_SD_INSTALL)
12629                        Log.i(TAG, "Looking for pkg : " + pkgName);
12630
12631                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12632                    if (ps == null) {
12633                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12634                        continue;
12635                    }
12636
12637                    /*
12638                     * Skip packages that are not external if we're unmounting
12639                     * external storage.
12640                     */
12641                    if (externalStorage && !isMounted && !isExternal(ps)) {
12642                        continue;
12643                    }
12644
12645                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12646                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12647                    // The package status is changed only if the code path
12648                    // matches between settings and the container id.
12649                    if (ps.codePathString != null
12650                            && ps.codePathString.startsWith(args.getCodePath())) {
12651                        if (DEBUG_SD_INSTALL) {
12652                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12653                                    + " at code path: " + ps.codePathString);
12654                        }
12655
12656                        // We do have a valid package installed on sdcard
12657                        processCids.put(args, ps.codePathString);
12658                        final int uid = ps.appId;
12659                        if (uid != -1) {
12660                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12661                        }
12662                    } else {
12663                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12664                                + ps.codePathString);
12665                    }
12666                }
12667            }
12668
12669            Arrays.sort(uidArr);
12670        }
12671
12672        // Process packages with valid entries.
12673        if (isMounted) {
12674            if (DEBUG_SD_INSTALL)
12675                Log.i(TAG, "Loading packages");
12676            loadMediaPackages(processCids, uidArr);
12677            startCleaningPackages();
12678            mInstallerService.onSecureContainersAvailable();
12679        } else {
12680            if (DEBUG_SD_INSTALL)
12681                Log.i(TAG, "Unloading packages");
12682            unloadMediaPackages(processCids, uidArr, reportStatus);
12683        }
12684    }
12685
12686    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12687            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12688        int size = pkgList.size();
12689        if (size > 0) {
12690            // Send broadcasts here
12691            Bundle extras = new Bundle();
12692            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12693                    .toArray(new String[size]));
12694            if (uidArr != null) {
12695                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12696            }
12697            if (replacing) {
12698                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12699            }
12700            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12701                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12702            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12703        }
12704    }
12705
12706   /*
12707     * Look at potentially valid container ids from processCids If package
12708     * information doesn't match the one on record or package scanning fails,
12709     * the cid is added to list of removeCids. We currently don't delete stale
12710     * containers.
12711     */
12712    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12713        ArrayList<String> pkgList = new ArrayList<String>();
12714        Set<AsecInstallArgs> keys = processCids.keySet();
12715
12716        for (AsecInstallArgs args : keys) {
12717            String codePath = processCids.get(args);
12718            if (DEBUG_SD_INSTALL)
12719                Log.i(TAG, "Loading container : " + args.cid);
12720            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12721            try {
12722                // Make sure there are no container errors first.
12723                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12724                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12725                            + " when installing from sdcard");
12726                    continue;
12727                }
12728                // Check code path here.
12729                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12730                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12731                            + " does not match one in settings " + codePath);
12732                    continue;
12733                }
12734                // Parse package
12735                int parseFlags = mDefParseFlags;
12736                if (args.isExternal()) {
12737                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12738                }
12739                if (args.isFwdLocked()) {
12740                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12741                }
12742
12743                synchronized (mInstallLock) {
12744                    PackageParser.Package pkg = null;
12745                    try {
12746                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12747                    } catch (PackageManagerException e) {
12748                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12749                    }
12750                    // Scan the package
12751                    if (pkg != null) {
12752                        /*
12753                         * TODO why is the lock being held? doPostInstall is
12754                         * called in other places without the lock. This needs
12755                         * to be straightened out.
12756                         */
12757                        // writer
12758                        synchronized (mPackages) {
12759                            retCode = PackageManager.INSTALL_SUCCEEDED;
12760                            pkgList.add(pkg.packageName);
12761                            // Post process args
12762                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12763                                    pkg.applicationInfo.uid);
12764                        }
12765                    } else {
12766                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12767                    }
12768                }
12769
12770            } finally {
12771                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12772                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12773                }
12774            }
12775        }
12776        // writer
12777        synchronized (mPackages) {
12778            // If the platform SDK has changed since the last time we booted,
12779            // we need to re-grant app permission to catch any new ones that
12780            // appear. This is really a hack, and means that apps can in some
12781            // cases get permissions that the user didn't initially explicitly
12782            // allow... it would be nice to have some better way to handle
12783            // this situation.
12784            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12785            if (regrantPermissions)
12786                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12787                        + mSdkVersion + "; regranting permissions for external storage");
12788            mSettings.mExternalSdkPlatform = mSdkVersion;
12789
12790            // Make sure group IDs have been assigned, and any permission
12791            // changes in other apps are accounted for
12792            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12793                    | (regrantPermissions
12794                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12795                            : 0));
12796
12797            mSettings.updateExternalDatabaseVersion();
12798
12799            // can downgrade to reader
12800            // Persist settings
12801            mSettings.writeLPr();
12802        }
12803        // Send a broadcast to let everyone know we are done processing
12804        if (pkgList.size() > 0) {
12805            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12806        }
12807    }
12808
12809   /*
12810     * Utility method to unload a list of specified containers
12811     */
12812    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12813        // Just unmount all valid containers.
12814        for (AsecInstallArgs arg : cidArgs) {
12815            synchronized (mInstallLock) {
12816                arg.doPostDeleteLI(false);
12817           }
12818       }
12819   }
12820
12821    /*
12822     * Unload packages mounted on external media. This involves deleting package
12823     * data from internal structures, sending broadcasts about diabled packages,
12824     * gc'ing to free up references, unmounting all secure containers
12825     * corresponding to packages on external media, and posting a
12826     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12827     * that we always have to post this message if status has been requested no
12828     * matter what.
12829     */
12830    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12831            final boolean reportStatus) {
12832        if (DEBUG_SD_INSTALL)
12833            Log.i(TAG, "unloading media packages");
12834        ArrayList<String> pkgList = new ArrayList<String>();
12835        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12836        final Set<AsecInstallArgs> keys = processCids.keySet();
12837        for (AsecInstallArgs args : keys) {
12838            String pkgName = args.getPackageName();
12839            if (DEBUG_SD_INSTALL)
12840                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12841            // Delete package internally
12842            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12843            synchronized (mInstallLock) {
12844                boolean res = deletePackageLI(pkgName, null, false, null, null,
12845                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12846                if (res) {
12847                    pkgList.add(pkgName);
12848                } else {
12849                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12850                    failedList.add(args);
12851                }
12852            }
12853        }
12854
12855        // reader
12856        synchronized (mPackages) {
12857            // We didn't update the settings after removing each package;
12858            // write them now for all packages.
12859            mSettings.writeLPr();
12860        }
12861
12862        // We have to absolutely send UPDATED_MEDIA_STATUS only
12863        // after confirming that all the receivers processed the ordered
12864        // broadcast when packages get disabled, force a gc to clean things up.
12865        // and unload all the containers.
12866        if (pkgList.size() > 0) {
12867            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12868                    new IIntentReceiver.Stub() {
12869                public void performReceive(Intent intent, int resultCode, String data,
12870                        Bundle extras, boolean ordered, boolean sticky,
12871                        int sendingUser) throws RemoteException {
12872                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12873                            reportStatus ? 1 : 0, 1, keys);
12874                    mHandler.sendMessage(msg);
12875                }
12876            });
12877        } else {
12878            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12879                    keys);
12880            mHandler.sendMessage(msg);
12881        }
12882    }
12883
12884    /** Binder call */
12885    @Override
12886    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12887            final int flags) {
12888        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12889        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12890        int returnCode = PackageManager.MOVE_SUCCEEDED;
12891        int currInstallFlags = 0;
12892        int newInstallFlags = 0;
12893
12894        File codeFile = null;
12895        String installerPackageName = null;
12896        String packageAbiOverride = null;
12897
12898        // reader
12899        synchronized (mPackages) {
12900            final PackageParser.Package pkg = mPackages.get(packageName);
12901            final PackageSetting ps = mSettings.mPackages.get(packageName);
12902            if (pkg == null || ps == null) {
12903                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12904            } else {
12905                // Disable moving fwd locked apps and system packages
12906                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12907                    Slog.w(TAG, "Cannot move system application");
12908                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12909                } else if (pkg.mOperationPending) {
12910                    Slog.w(TAG, "Attempt to move package which has pending operations");
12911                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12912                } else {
12913                    // Find install location first
12914                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12915                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12916                        Slog.w(TAG, "Ambigous flags specified for move location.");
12917                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12918                    } else {
12919                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12920                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12921                        currInstallFlags = isExternal(pkg)
12922                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12923
12924                        if (newInstallFlags == currInstallFlags) {
12925                            Slog.w(TAG, "No move required. Trying to move to same location");
12926                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12927                        } else {
12928                            if (isForwardLocked(pkg)) {
12929                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12930                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12931                            }
12932                        }
12933                    }
12934                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12935                        pkg.mOperationPending = true;
12936                    }
12937                }
12938
12939                codeFile = new File(pkg.codePath);
12940                installerPackageName = ps.installerPackageName;
12941                packageAbiOverride = ps.cpuAbiOverrideString;
12942            }
12943        }
12944
12945        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12946            try {
12947                observer.packageMoved(packageName, returnCode);
12948            } catch (RemoteException ignored) {
12949            }
12950            return;
12951        }
12952
12953        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12954            @Override
12955            public void onUserActionRequired(Intent intent) throws RemoteException {
12956                throw new IllegalStateException();
12957            }
12958
12959            @Override
12960            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12961                    Bundle extras) throws RemoteException {
12962                Slog.d(TAG, "Install result for move: "
12963                        + PackageManager.installStatusToString(returnCode, msg));
12964
12965                // We usually have a new package now after the install, but if
12966                // we failed we need to clear the pending flag on the original
12967                // package object.
12968                synchronized (mPackages) {
12969                    final PackageParser.Package pkg = mPackages.get(packageName);
12970                    if (pkg != null) {
12971                        pkg.mOperationPending = false;
12972                    }
12973                }
12974
12975                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12976                switch (status) {
12977                    case PackageInstaller.STATUS_SUCCESS:
12978                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12979                        break;
12980                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12981                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12982                        break;
12983                    default:
12984                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12985                        break;
12986                }
12987            }
12988        };
12989
12990        // Treat a move like reinstalling an existing app, which ensures that we
12991        // process everythign uniformly, like unpacking native libraries.
12992        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12993
12994        final Message msg = mHandler.obtainMessage(INIT_COPY);
12995        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12996        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12997                installerPackageName, null, user, packageAbiOverride);
12998        mHandler.sendMessage(msg);
12999    }
13000
13001    @Override
13002    public boolean setInstallLocation(int loc) {
13003        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13004                null);
13005        if (getInstallLocation() == loc) {
13006            return true;
13007        }
13008        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13009                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13010            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13011                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13012            return true;
13013        }
13014        return false;
13015   }
13016
13017    @Override
13018    public int getInstallLocation() {
13019        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13020                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13021                PackageHelper.APP_INSTALL_AUTO);
13022    }
13023
13024    /** Called by UserManagerService */
13025    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13026        mDirtyUsers.remove(userHandle);
13027        mSettings.removeUserLPw(userHandle);
13028        mPendingBroadcasts.remove(userHandle);
13029        if (mInstaller != null) {
13030            // Technically, we shouldn't be doing this with the package lock
13031            // held.  However, this is very rare, and there is already so much
13032            // other disk I/O going on, that we'll let it slide for now.
13033            mInstaller.removeUserDataDirs(userHandle);
13034        }
13035        mUserNeedsBadging.delete(userHandle);
13036        removeUnusedPackagesLILPw(userManager, userHandle);
13037    }
13038
13039    /**
13040     * We're removing userHandle and would like to remove any downloaded packages
13041     * that are no longer in use by any other user.
13042     * @param userHandle the user being removed
13043     */
13044    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13045        final boolean DEBUG_CLEAN_APKS = false;
13046        int [] users = userManager.getUserIdsLPr();
13047        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13048        while (psit.hasNext()) {
13049            PackageSetting ps = psit.next();
13050            if (ps.pkg == null) {
13051                continue;
13052            }
13053            final String packageName = ps.pkg.packageName;
13054            // Skip over if system app
13055            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13056                continue;
13057            }
13058            if (DEBUG_CLEAN_APKS) {
13059                Slog.i(TAG, "Checking package " + packageName);
13060            }
13061            boolean keep = false;
13062            for (int i = 0; i < users.length; i++) {
13063                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13064                    keep = true;
13065                    if (DEBUG_CLEAN_APKS) {
13066                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13067                                + users[i]);
13068                    }
13069                    break;
13070                }
13071            }
13072            if (!keep) {
13073                if (DEBUG_CLEAN_APKS) {
13074                    Slog.i(TAG, "  Removing package " + packageName);
13075                }
13076                mHandler.post(new Runnable() {
13077                    public void run() {
13078                        deletePackageX(packageName, userHandle, 0);
13079                    } //end run
13080                });
13081            }
13082        }
13083    }
13084
13085    /** Called by UserManagerService */
13086    void createNewUserLILPw(int userHandle, File path) {
13087        if (mInstaller != null) {
13088            mInstaller.createUserConfig(userHandle);
13089            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13090        }
13091    }
13092
13093    @Override
13094    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13095        mContext.enforceCallingOrSelfPermission(
13096                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13097                "Only package verification agents can read the verifier device identity");
13098
13099        synchronized (mPackages) {
13100            return mSettings.getVerifierDeviceIdentityLPw();
13101        }
13102    }
13103
13104    @Override
13105    public void setPermissionEnforced(String permission, boolean enforced) {
13106        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13107        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13108            synchronized (mPackages) {
13109                if (mSettings.mReadExternalStorageEnforced == null
13110                        || mSettings.mReadExternalStorageEnforced != enforced) {
13111                    mSettings.mReadExternalStorageEnforced = enforced;
13112                    mSettings.writeLPr();
13113                }
13114            }
13115            // kill any non-foreground processes so we restart them and
13116            // grant/revoke the GID.
13117            final IActivityManager am = ActivityManagerNative.getDefault();
13118            if (am != null) {
13119                final long token = Binder.clearCallingIdentity();
13120                try {
13121                    am.killProcessesBelowForeground("setPermissionEnforcement");
13122                } catch (RemoteException e) {
13123                } finally {
13124                    Binder.restoreCallingIdentity(token);
13125                }
13126            }
13127        } else {
13128            throw new IllegalArgumentException("No selective enforcement for " + permission);
13129        }
13130    }
13131
13132    @Override
13133    @Deprecated
13134    public boolean isPermissionEnforced(String permission) {
13135        return true;
13136    }
13137
13138    @Override
13139    public boolean isStorageLow() {
13140        final long token = Binder.clearCallingIdentity();
13141        try {
13142            final DeviceStorageMonitorInternal
13143                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13144            if (dsm != null) {
13145                return dsm.isMemoryLow();
13146            } else {
13147                return false;
13148            }
13149        } finally {
13150            Binder.restoreCallingIdentity(token);
13151        }
13152    }
13153
13154    @Override
13155    public IPackageInstaller getPackageInstaller() {
13156        return mInstallerService;
13157    }
13158
13159    private boolean userNeedsBadging(int userId) {
13160        int index = mUserNeedsBadging.indexOfKey(userId);
13161        if (index < 0) {
13162            final UserInfo userInfo;
13163            final long token = Binder.clearCallingIdentity();
13164            try {
13165                userInfo = sUserManager.getUserInfo(userId);
13166            } finally {
13167                Binder.restoreCallingIdentity(token);
13168            }
13169            final boolean b;
13170            if (userInfo != null && userInfo.isManagedProfile()) {
13171                b = true;
13172            } else {
13173                b = false;
13174            }
13175            mUserNeedsBadging.put(userId, b);
13176            return b;
13177        }
13178        return mUserNeedsBadging.valueAt(index);
13179    }
13180
13181    @Override
13182    public KeySet getKeySetByAlias(String packageName, String alias) {
13183        if (packageName == null || alias == null) {
13184            return null;
13185        }
13186        synchronized(mPackages) {
13187            final PackageParser.Package pkg = mPackages.get(packageName);
13188            if (pkg == null) {
13189                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13190                throw new IllegalArgumentException("Unknown package: " + packageName);
13191            }
13192            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13193            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13194        }
13195    }
13196
13197    @Override
13198    public KeySet getSigningKeySet(String packageName) {
13199        if (packageName == null) {
13200            return null;
13201        }
13202        synchronized(mPackages) {
13203            final PackageParser.Package pkg = mPackages.get(packageName);
13204            if (pkg == null) {
13205                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13206                throw new IllegalArgumentException("Unknown package: " + packageName);
13207            }
13208            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13209                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13210                throw new SecurityException("May not access signing KeySet of other apps.");
13211            }
13212            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13213            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13214        }
13215    }
13216
13217    @Override
13218    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13219        if (packageName == null || ks == null) {
13220            return false;
13221        }
13222        synchronized(mPackages) {
13223            final PackageParser.Package pkg = mPackages.get(packageName);
13224            if (pkg == null) {
13225                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13226                throw new IllegalArgumentException("Unknown package: " + packageName);
13227            }
13228            IBinder ksh = ks.getToken();
13229            if (ksh instanceof KeySetHandle) {
13230                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13231                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13232            }
13233            return false;
13234        }
13235    }
13236
13237    @Override
13238    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13239        if (packageName == null || ks == null) {
13240            return false;
13241        }
13242        synchronized(mPackages) {
13243            final PackageParser.Package pkg = mPackages.get(packageName);
13244            if (pkg == null) {
13245                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13246                throw new IllegalArgumentException("Unknown package: " + packageName);
13247            }
13248            IBinder ksh = ks.getToken();
13249            if (ksh instanceof KeySetHandle) {
13250                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13251                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13252            }
13253            return false;
13254        }
13255    }
13256}
13257