PackageManagerService.java revision 9b2d26b68347e246e67c588b548e81fca1d29353
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.FileUtils;
142import android.os.Handler;
143import android.os.IBinder;
144import android.os.Looper;
145import android.os.Message;
146import android.os.Parcel;
147import android.os.ParcelFileDescriptor;
148import android.os.Process;
149import android.os.RemoteException;
150import android.os.SELinux;
151import android.os.ServiceManager;
152import android.os.SystemClock;
153import android.os.SystemProperties;
154import android.os.UserHandle;
155import android.os.UserManager;
156import android.security.KeyStore;
157import android.security.SystemKeyStore;
158import android.system.ErrnoException;
159import android.system.Os;
160import android.system.StructStat;
161import android.text.TextUtils;
162import android.util.ArraySet;
163import android.util.AtomicFile;
164import android.util.DisplayMetrics;
165import android.util.EventLog;
166import android.util.ExceptionUtils;
167import android.util.Log;
168import android.util.LogPrinter;
169import android.util.PrintStreamPrinter;
170import android.util.Slog;
171import android.util.SparseArray;
172import android.util.SparseBooleanArray;
173import android.view.Display;
174
175import java.io.BufferedInputStream;
176import java.io.BufferedOutputStream;
177import java.io.File;
178import java.io.FileDescriptor;
179import java.io.FileInputStream;
180import java.io.FileNotFoundException;
181import java.io.FileOutputStream;
182import java.io.FilenameFilter;
183import java.io.IOException;
184import java.io.InputStream;
185import java.io.PrintWriter;
186import java.nio.charset.StandardCharsets;
187import java.security.NoSuchAlgorithmException;
188import java.security.PublicKey;
189import java.security.cert.CertificateEncodingException;
190import java.security.cert.CertificateException;
191import java.text.SimpleDateFormat;
192import java.util.ArrayList;
193import java.util.Arrays;
194import java.util.Collection;
195import java.util.Collections;
196import java.util.Comparator;
197import java.util.Date;
198import java.util.HashMap;
199import java.util.HashSet;
200import java.util.Iterator;
201import java.util.List;
202import java.util.Map;
203import java.util.Set;
204import java.util.concurrent.atomic.AtomicBoolean;
205import java.util.concurrent.atomic.AtomicLong;
206
207import dalvik.system.DexFile;
208import dalvik.system.StaleDexCacheError;
209import dalvik.system.VMRuntime;
210
211import libcore.io.IoUtils;
212import libcore.util.EmptyArray;
213
214/**
215 * Keep track of all those .apks everywhere.
216 *
217 * This is very central to the platform's security; please run the unit
218 * tests whenever making modifications here:
219 *
220mmm frameworks/base/tests/AndroidTests
221adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
222adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
223 *
224 * {@hide}
225 */
226public class PackageManagerService extends IPackageManager.Stub {
227    static final String TAG = "PackageManager";
228    static final boolean DEBUG_SETTINGS = false;
229    static final boolean DEBUG_PREFERRED = false;
230    static final boolean DEBUG_UPGRADE = false;
231    private static final boolean DEBUG_INSTALL = false;
232    private static final boolean DEBUG_REMOVE = false;
233    private static final boolean DEBUG_BROADCASTS = false;
234    private static final boolean DEBUG_SHOW_INFO = false;
235    private static final boolean DEBUG_PACKAGE_INFO = false;
236    private static final boolean DEBUG_INTENT_MATCHING = false;
237    private static final boolean DEBUG_PACKAGE_SCANNING = false;
238    private static final boolean DEBUG_VERIFY = false;
239    private static final boolean DEBUG_DEXOPT = false;
240    private static final boolean DEBUG_ABI_SELECTION = false;
241
242    private static final int RADIO_UID = Process.PHONE_UID;
243    private static final int LOG_UID = Process.LOG_UID;
244    private static final int NFC_UID = Process.NFC_UID;
245    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
246    private static final int SHELL_UID = Process.SHELL_UID;
247
248    // Cap the size of permission trees that 3rd party apps can define
249    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
250
251    // Suffix used during package installation when copying/moving
252    // package apks to install directory.
253    private static final String INSTALL_PACKAGE_SUFFIX = "-";
254
255    static final int SCAN_NO_DEX = 1<<1;
256    static final int SCAN_FORCE_DEX = 1<<2;
257    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
258    static final int SCAN_NEW_INSTALL = 1<<4;
259    static final int SCAN_NO_PATHS = 1<<5;
260    static final int SCAN_UPDATE_TIME = 1<<6;
261    static final int SCAN_DEFER_DEX = 1<<7;
262    static final int SCAN_BOOTING = 1<<8;
263    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
264    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
265    static final int SCAN_REPLACING = 1<<11;
266
267    static final int REMOVE_CHATTY = 1<<16;
268
269    /**
270     * Timeout (in milliseconds) after which the watchdog should declare that
271     * our handler thread is wedged.  The usual default for such things is one
272     * minute but we sometimes do very lengthy I/O operations on this thread,
273     * such as installing multi-gigabyte applications, so ours needs to be longer.
274     */
275    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
276
277    /**
278     * Whether verification is enabled by default.
279     */
280    private static final boolean DEFAULT_VERIFY_ENABLE = true;
281
282    /**
283     * The default maximum time to wait for the verification agent to return in
284     * milliseconds.
285     */
286    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
287
288    /**
289     * The default response for package verification timeout.
290     *
291     * This can be either PackageManager.VERIFICATION_ALLOW or
292     * PackageManager.VERIFICATION_REJECT.
293     */
294    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
295
296    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
297
298    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
299            DEFAULT_CONTAINER_PACKAGE,
300            "com.android.defcontainer.DefaultContainerService");
301
302    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
303
304    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
305
306    private static String sPreferredInstructionSet;
307
308    final ServiceThread mHandlerThread;
309
310    private static final String IDMAP_PREFIX = "/data/resource-cache/";
311    private static final String IDMAP_SUFFIX = "@idmap";
312
313    final PackageHandler mHandler;
314
315    /**
316     * Messages for {@link #mHandler} that need to wait for system ready before
317     * being dispatched.
318     */
319    private ArrayList<Message> mPostSystemReadyMessages;
320
321    final int mSdkVersion = Build.VERSION.SDK_INT;
322
323    final Context mContext;
324    final boolean mFactoryTest;
325    final boolean mOnlyCore;
326    final boolean mLazyDexOpt;
327    final DisplayMetrics mMetrics;
328    final int mDefParseFlags;
329    final String[] mSeparateProcesses;
330
331    // This is where all application persistent data goes.
332    final File mAppDataDir;
333
334    // This is where all application persistent data goes for secondary users.
335    final File mUserAppDataDir;
336
337    /** The location for ASEC container files on internal storage. */
338    final String mAsecInternalPath;
339
340    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
341    // LOCK HELD.  Can be called with mInstallLock held.
342    final Installer mInstaller;
343
344    /** Directory where installed third-party apps stored */
345    final File mAppInstallDir;
346
347    /**
348     * Directory to which applications installed internally have their
349     * 32 bit native libraries copied.
350     */
351    private File mAppLib32InstallDir;
352
353    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
354    // apps.
355    final File mDrmAppPrivateInstallDir;
356
357    // ----------------------------------------------------------------
358
359    // Lock for state used when installing and doing other long running
360    // operations.  Methods that must be called with this lock held have
361    // the suffix "LI".
362    final Object mInstallLock = new Object();
363
364    // ----------------------------------------------------------------
365
366    // Keys are String (package name), values are Package.  This also serves
367    // as the lock for the global state.  Methods that must be called with
368    // this lock held have the prefix "LP".
369    final HashMap<String, PackageParser.Package> mPackages =
370            new HashMap<String, PackageParser.Package>();
371
372    // Tracks available target package names -> overlay package paths.
373    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
374        new HashMap<String, HashMap<String, PackageParser.Package>>();
375
376    final Settings mSettings;
377    boolean mRestoredSettings;
378
379    // System configuration read by SystemConfig.
380    final int[] mGlobalGids;
381    final SparseArray<HashSet<String>> mSystemPermissions;
382    final HashMap<String, FeatureInfo> mAvailableFeatures;
383
384    // If mac_permissions.xml was found for seinfo labeling.
385    boolean mFoundPolicyFile;
386
387    // If a recursive restorecon of /data/data/<pkg> is needed.
388    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
389
390    public static final class SharedLibraryEntry {
391        public final String path;
392        public final String apk;
393
394        SharedLibraryEntry(String _path, String _apk) {
395            path = _path;
396            apk = _apk;
397        }
398    }
399
400    // Currently known shared libraries.
401    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
402            new HashMap<String, SharedLibraryEntry>();
403
404    // All available activities, for your resolving pleasure.
405    final ActivityIntentResolver mActivities =
406            new ActivityIntentResolver();
407
408    // All available receivers, for your resolving pleasure.
409    final ActivityIntentResolver mReceivers =
410            new ActivityIntentResolver();
411
412    // All available services, for your resolving pleasure.
413    final ServiceIntentResolver mServices = new ServiceIntentResolver();
414
415    // All available providers, for your resolving pleasure.
416    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
417
418    // Mapping from provider base names (first directory in content URI codePath)
419    // to the provider information.
420    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
421            new HashMap<String, PackageParser.Provider>();
422
423    // Mapping from instrumentation class names to info about them.
424    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
425            new HashMap<ComponentName, PackageParser.Instrumentation>();
426
427    // Mapping from permission names to info about them.
428    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
429            new HashMap<String, PackageParser.PermissionGroup>();
430
431    // Packages whose data we have transfered into another package, thus
432    // should no longer exist.
433    final HashSet<String> mTransferedPackages = new HashSet<String>();
434
435    // Broadcast actions that are only available to the system.
436    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
437
438    /** List of packages waiting for verification. */
439    final SparseArray<PackageVerificationState> mPendingVerification
440            = new SparseArray<PackageVerificationState>();
441
442    /** Set of packages associated with each app op permission. */
443    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
444
445    final PackageInstallerService mInstallerService;
446
447    HashSet<PackageParser.Package> mDeferredDexOpt = null;
448
449    // Cache of users who need badging.
450    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
451
452    /** Token for keys in mPendingVerification. */
453    private int mPendingVerificationToken = 0;
454
455    volatile boolean mSystemReady;
456    volatile boolean mSafeMode;
457    volatile boolean mHasSystemUidErrors;
458
459    ApplicationInfo mAndroidApplication;
460    final ActivityInfo mResolveActivity = new ActivityInfo();
461    final ResolveInfo mResolveInfo = new ResolveInfo();
462    ComponentName mResolveComponentName;
463    PackageParser.Package mPlatformPackage;
464    ComponentName mCustomResolverComponentName;
465
466    boolean mResolverReplaced = false;
467
468    // Set of pending broadcasts for aggregating enable/disable of components.
469    static class PendingPackageBroadcasts {
470        // for each user id, a map of <package name -> components within that package>
471        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
472
473        public PendingPackageBroadcasts() {
474            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
475        }
476
477        public ArrayList<String> get(int userId, String packageName) {
478            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
479            return packages.get(packageName);
480        }
481
482        public void put(int userId, String packageName, ArrayList<String> components) {
483            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
484            packages.put(packageName, components);
485        }
486
487        public void remove(int userId, String packageName) {
488            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
489            if (packages != null) {
490                packages.remove(packageName);
491            }
492        }
493
494        public void remove(int userId) {
495            mUidMap.remove(userId);
496        }
497
498        public int userIdCount() {
499            return mUidMap.size();
500        }
501
502        public int userIdAt(int n) {
503            return mUidMap.keyAt(n);
504        }
505
506        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
507            return mUidMap.get(userId);
508        }
509
510        public int size() {
511            // total number of pending broadcast entries across all userIds
512            int num = 0;
513            for (int i = 0; i< mUidMap.size(); i++) {
514                num += mUidMap.valueAt(i).size();
515            }
516            return num;
517        }
518
519        public void clear() {
520            mUidMap.clear();
521        }
522
523        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
524            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
525            if (map == null) {
526                map = new HashMap<String, ArrayList<String>>();
527                mUidMap.put(userId, map);
528            }
529            return map;
530        }
531    }
532    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
533
534    // Service Connection to remote media container service to copy
535    // package uri's from external media onto secure containers
536    // or internal storage.
537    private IMediaContainerService mContainerService = null;
538
539    static final int SEND_PENDING_BROADCAST = 1;
540    static final int MCS_BOUND = 3;
541    static final int END_COPY = 4;
542    static final int INIT_COPY = 5;
543    static final int MCS_UNBIND = 6;
544    static final int START_CLEANING_PACKAGE = 7;
545    static final int FIND_INSTALL_LOC = 8;
546    static final int POST_INSTALL = 9;
547    static final int MCS_RECONNECT = 10;
548    static final int MCS_GIVE_UP = 11;
549    static final int UPDATED_MEDIA_STATUS = 12;
550    static final int WRITE_SETTINGS = 13;
551    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
552    static final int PACKAGE_VERIFIED = 15;
553    static final int CHECK_PENDING_VERIFICATION = 16;
554
555    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
556
557    // Delay time in millisecs
558    static final int BROADCAST_DELAY = 10 * 1000;
559
560    static UserManagerService sUserManager;
561
562    // Stores a list of users whose package restrictions file needs to be updated
563    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
564
565    final private DefaultContainerConnection mDefContainerConn =
566            new DefaultContainerConnection();
567    class DefaultContainerConnection implements ServiceConnection {
568        public void onServiceConnected(ComponentName name, IBinder service) {
569            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
570            IMediaContainerService imcs =
571                IMediaContainerService.Stub.asInterface(service);
572            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
573        }
574
575        public void onServiceDisconnected(ComponentName name) {
576            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
577        }
578    };
579
580    // Recordkeeping of restore-after-install operations that are currently in flight
581    // between the Package Manager and the Backup Manager
582    class PostInstallData {
583        public InstallArgs args;
584        public PackageInstalledInfo res;
585
586        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
587            args = _a;
588            res = _r;
589        }
590    };
591    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
592    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
593
594    private final String mRequiredVerifierPackage;
595
596    private final PackageUsage mPackageUsage = new PackageUsage();
597
598    private class PackageUsage {
599        private static final int WRITE_INTERVAL
600            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
601
602        private final Object mFileLock = new Object();
603        private final AtomicLong mLastWritten = new AtomicLong(0);
604        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
605
606        private boolean mIsHistoricalPackageUsageAvailable = true;
607
608        boolean isHistoricalPackageUsageAvailable() {
609            return mIsHistoricalPackageUsageAvailable;
610        }
611
612        void write(boolean force) {
613            if (force) {
614                writeInternal();
615                return;
616            }
617            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
618                && !DEBUG_DEXOPT) {
619                return;
620            }
621            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
622                new Thread("PackageUsage_DiskWriter") {
623                    @Override
624                    public void run() {
625                        try {
626                            writeInternal();
627                        } finally {
628                            mBackgroundWriteRunning.set(false);
629                        }
630                    }
631                }.start();
632            }
633        }
634
635        private void writeInternal() {
636            synchronized (mPackages) {
637                synchronized (mFileLock) {
638                    AtomicFile file = getFile();
639                    FileOutputStream f = null;
640                    try {
641                        f = file.startWrite();
642                        BufferedOutputStream out = new BufferedOutputStream(f);
643                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
644                        StringBuilder sb = new StringBuilder();
645                        for (PackageParser.Package pkg : mPackages.values()) {
646                            if (pkg.mLastPackageUsageTimeInMills == 0) {
647                                continue;
648                            }
649                            sb.setLength(0);
650                            sb.append(pkg.packageName);
651                            sb.append(' ');
652                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
653                            sb.append('\n');
654                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
655                        }
656                        out.flush();
657                        file.finishWrite(f);
658                    } catch (IOException e) {
659                        if (f != null) {
660                            file.failWrite(f);
661                        }
662                        Log.e(TAG, "Failed to write package usage times", e);
663                    }
664                }
665            }
666            mLastWritten.set(SystemClock.elapsedRealtime());
667        }
668
669        void readLP() {
670            synchronized (mFileLock) {
671                AtomicFile file = getFile();
672                BufferedInputStream in = null;
673                try {
674                    in = new BufferedInputStream(file.openRead());
675                    StringBuffer sb = new StringBuffer();
676                    while (true) {
677                        String packageName = readToken(in, sb, ' ');
678                        if (packageName == null) {
679                            break;
680                        }
681                        String timeInMillisString = readToken(in, sb, '\n');
682                        if (timeInMillisString == null) {
683                            throw new IOException("Failed to find last usage time for package "
684                                                  + packageName);
685                        }
686                        PackageParser.Package pkg = mPackages.get(packageName);
687                        if (pkg == null) {
688                            continue;
689                        }
690                        long timeInMillis;
691                        try {
692                            timeInMillis = Long.parseLong(timeInMillisString.toString());
693                        } catch (NumberFormatException e) {
694                            throw new IOException("Failed to parse " + timeInMillisString
695                                                  + " as a long.", e);
696                        }
697                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
698                    }
699                } catch (FileNotFoundException expected) {
700                    mIsHistoricalPackageUsageAvailable = false;
701                } catch (IOException e) {
702                    Log.w(TAG, "Failed to read package usage times", e);
703                } finally {
704                    IoUtils.closeQuietly(in);
705                }
706            }
707            mLastWritten.set(SystemClock.elapsedRealtime());
708        }
709
710        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
711                throws IOException {
712            sb.setLength(0);
713            while (true) {
714                int ch = in.read();
715                if (ch == -1) {
716                    if (sb.length() == 0) {
717                        return null;
718                    }
719                    throw new IOException("Unexpected EOF");
720                }
721                if (ch == endOfToken) {
722                    return sb.toString();
723                }
724                sb.append((char)ch);
725            }
726        }
727
728        private AtomicFile getFile() {
729            File dataDir = Environment.getDataDirectory();
730            File systemDir = new File(dataDir, "system");
731            File fname = new File(systemDir, "package-usage.list");
732            return new AtomicFile(fname);
733        }
734    }
735
736    class PackageHandler extends Handler {
737        private boolean mBound = false;
738        final ArrayList<HandlerParams> mPendingInstalls =
739            new ArrayList<HandlerParams>();
740
741        private boolean connectToService() {
742            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
743                    " DefaultContainerService");
744            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
745            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
746            if (mContext.bindServiceAsUser(service, mDefContainerConn,
747                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
748                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
749                mBound = true;
750                return true;
751            }
752            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
753            return false;
754        }
755
756        private void disconnectService() {
757            mContainerService = null;
758            mBound = false;
759            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
760            mContext.unbindService(mDefContainerConn);
761            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
762        }
763
764        PackageHandler(Looper looper) {
765            super(looper);
766        }
767
768        public void handleMessage(Message msg) {
769            try {
770                doHandleMessage(msg);
771            } finally {
772                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
773            }
774        }
775
776        void doHandleMessage(Message msg) {
777            switch (msg.what) {
778                case INIT_COPY: {
779                    HandlerParams params = (HandlerParams) msg.obj;
780                    int idx = mPendingInstalls.size();
781                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
782                    // If a bind was already initiated we dont really
783                    // need to do anything. The pending install
784                    // will be processed later on.
785                    if (!mBound) {
786                        // If this is the only one pending we might
787                        // have to bind to the service again.
788                        if (!connectToService()) {
789                            Slog.e(TAG, "Failed to bind to media container service");
790                            params.serviceError();
791                            return;
792                        } else {
793                            // Once we bind to the service, the first
794                            // pending request will be processed.
795                            mPendingInstalls.add(idx, params);
796                        }
797                    } else {
798                        mPendingInstalls.add(idx, params);
799                        // Already bound to the service. Just make
800                        // sure we trigger off processing the first request.
801                        if (idx == 0) {
802                            mHandler.sendEmptyMessage(MCS_BOUND);
803                        }
804                    }
805                    break;
806                }
807                case MCS_BOUND: {
808                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
809                    if (msg.obj != null) {
810                        mContainerService = (IMediaContainerService) msg.obj;
811                    }
812                    if (mContainerService == null) {
813                        // Something seriously wrong. Bail out
814                        Slog.e(TAG, "Cannot bind to media container service");
815                        for (HandlerParams params : mPendingInstalls) {
816                            // Indicate service bind error
817                            params.serviceError();
818                        }
819                        mPendingInstalls.clear();
820                    } else if (mPendingInstalls.size() > 0) {
821                        HandlerParams params = mPendingInstalls.get(0);
822                        if (params != null) {
823                            if (params.startCopy()) {
824                                // We are done...  look for more work or to
825                                // go idle.
826                                if (DEBUG_SD_INSTALL) Log.i(TAG,
827                                        "Checking for more work or unbind...");
828                                // Delete pending install
829                                if (mPendingInstalls.size() > 0) {
830                                    mPendingInstalls.remove(0);
831                                }
832                                if (mPendingInstalls.size() == 0) {
833                                    if (mBound) {
834                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
835                                                "Posting delayed MCS_UNBIND");
836                                        removeMessages(MCS_UNBIND);
837                                        Message ubmsg = obtainMessage(MCS_UNBIND);
838                                        // Unbind after a little delay, to avoid
839                                        // continual thrashing.
840                                        sendMessageDelayed(ubmsg, 10000);
841                                    }
842                                } else {
843                                    // There are more pending requests in queue.
844                                    // Just post MCS_BOUND message to trigger processing
845                                    // of next pending install.
846                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
847                                            "Posting MCS_BOUND for next work");
848                                    mHandler.sendEmptyMessage(MCS_BOUND);
849                                }
850                            }
851                        }
852                    } else {
853                        // Should never happen ideally.
854                        Slog.w(TAG, "Empty queue");
855                    }
856                    break;
857                }
858                case MCS_RECONNECT: {
859                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
860                    if (mPendingInstalls.size() > 0) {
861                        if (mBound) {
862                            disconnectService();
863                        }
864                        if (!connectToService()) {
865                            Slog.e(TAG, "Failed to bind to media container service");
866                            for (HandlerParams params : mPendingInstalls) {
867                                // Indicate service bind error
868                                params.serviceError();
869                            }
870                            mPendingInstalls.clear();
871                        }
872                    }
873                    break;
874                }
875                case MCS_UNBIND: {
876                    // If there is no actual work left, then time to unbind.
877                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
878
879                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
880                        if (mBound) {
881                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
882
883                            disconnectService();
884                        }
885                    } else if (mPendingInstalls.size() > 0) {
886                        // There are more pending requests in queue.
887                        // Just post MCS_BOUND message to trigger processing
888                        // of next pending install.
889                        mHandler.sendEmptyMessage(MCS_BOUND);
890                    }
891
892                    break;
893                }
894                case MCS_GIVE_UP: {
895                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
896                    mPendingInstalls.remove(0);
897                    break;
898                }
899                case SEND_PENDING_BROADCAST: {
900                    String packages[];
901                    ArrayList<String> components[];
902                    int size = 0;
903                    int uids[];
904                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
905                    synchronized (mPackages) {
906                        if (mPendingBroadcasts == null) {
907                            return;
908                        }
909                        size = mPendingBroadcasts.size();
910                        if (size <= 0) {
911                            // Nothing to be done. Just return
912                            return;
913                        }
914                        packages = new String[size];
915                        components = new ArrayList[size];
916                        uids = new int[size];
917                        int i = 0;  // filling out the above arrays
918
919                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
920                            int packageUserId = mPendingBroadcasts.userIdAt(n);
921                            Iterator<Map.Entry<String, ArrayList<String>>> it
922                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
923                                            .entrySet().iterator();
924                            while (it.hasNext() && i < size) {
925                                Map.Entry<String, ArrayList<String>> ent = it.next();
926                                packages[i] = ent.getKey();
927                                components[i] = ent.getValue();
928                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
929                                uids[i] = (ps != null)
930                                        ? UserHandle.getUid(packageUserId, ps.appId)
931                                        : -1;
932                                i++;
933                            }
934                        }
935                        size = i;
936                        mPendingBroadcasts.clear();
937                    }
938                    // Send broadcasts
939                    for (int i = 0; i < size; i++) {
940                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
941                    }
942                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
943                    break;
944                }
945                case START_CLEANING_PACKAGE: {
946                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
947                    final String packageName = (String)msg.obj;
948                    final int userId = msg.arg1;
949                    final boolean andCode = msg.arg2 != 0;
950                    synchronized (mPackages) {
951                        if (userId == UserHandle.USER_ALL) {
952                            int[] users = sUserManager.getUserIds();
953                            for (int user : users) {
954                                mSettings.addPackageToCleanLPw(
955                                        new PackageCleanItem(user, packageName, andCode));
956                            }
957                        } else {
958                            mSettings.addPackageToCleanLPw(
959                                    new PackageCleanItem(userId, packageName, andCode));
960                        }
961                    }
962                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
963                    startCleaningPackages();
964                } break;
965                case POST_INSTALL: {
966                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
967                    PostInstallData data = mRunningInstalls.get(msg.arg1);
968                    mRunningInstalls.delete(msg.arg1);
969                    boolean deleteOld = false;
970
971                    if (data != null) {
972                        InstallArgs args = data.args;
973                        PackageInstalledInfo res = data.res;
974
975                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
976                            res.removedInfo.sendBroadcast(false, true, false);
977                            Bundle extras = new Bundle(1);
978                            extras.putInt(Intent.EXTRA_UID, res.uid);
979                            // Determine the set of users who are adding this
980                            // package for the first time vs. those who are seeing
981                            // an update.
982                            int[] firstUsers;
983                            int[] updateUsers = new int[0];
984                            if (res.origUsers == null || res.origUsers.length == 0) {
985                                firstUsers = res.newUsers;
986                            } else {
987                                firstUsers = new int[0];
988                                for (int i=0; i<res.newUsers.length; i++) {
989                                    int user = res.newUsers[i];
990                                    boolean isNew = true;
991                                    for (int j=0; j<res.origUsers.length; j++) {
992                                        if (res.origUsers[j] == user) {
993                                            isNew = false;
994                                            break;
995                                        }
996                                    }
997                                    if (isNew) {
998                                        int[] newFirst = new int[firstUsers.length+1];
999                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1000                                                firstUsers.length);
1001                                        newFirst[firstUsers.length] = user;
1002                                        firstUsers = newFirst;
1003                                    } else {
1004                                        int[] newUpdate = new int[updateUsers.length+1];
1005                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1006                                                updateUsers.length);
1007                                        newUpdate[updateUsers.length] = user;
1008                                        updateUsers = newUpdate;
1009                                    }
1010                                }
1011                            }
1012                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1013                                    res.pkg.applicationInfo.packageName,
1014                                    extras, null, null, firstUsers);
1015                            final boolean update = res.removedInfo.removedPackage != null;
1016                            if (update) {
1017                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1018                            }
1019                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1020                                    res.pkg.applicationInfo.packageName,
1021                                    extras, null, null, updateUsers);
1022                            if (update) {
1023                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1024                                        res.pkg.applicationInfo.packageName,
1025                                        extras, null, null, updateUsers);
1026                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1027                                        null, null,
1028                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1029
1030                                // treat asec-hosted packages like removable media on upgrade
1031                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1032                                    if (DEBUG_INSTALL) {
1033                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1034                                                + " is ASEC-hosted -> AVAILABLE");
1035                                    }
1036                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1037                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1038                                    pkgList.add(res.pkg.applicationInfo.packageName);
1039                                    sendResourcesChangedBroadcast(true, true,
1040                                            pkgList,uidArray, null);
1041                                }
1042                            }
1043                            if (res.removedInfo.args != null) {
1044                                // Remove the replaced package's older resources safely now
1045                                deleteOld = true;
1046                            }
1047
1048                            // Log current value of "unknown sources" setting
1049                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1050                                getUnknownSourcesSettings());
1051                        }
1052                        // Force a gc to clear up things
1053                        Runtime.getRuntime().gc();
1054                        // We delete after a gc for applications  on sdcard.
1055                        if (deleteOld) {
1056                            synchronized (mInstallLock) {
1057                                res.removedInfo.args.doPostDeleteLI(true);
1058                            }
1059                        }
1060                        if (args.observer != null) {
1061                            try {
1062                                Bundle extras = extrasForInstallResult(res);
1063                                args.observer.onPackageInstalled(res.name, res.returnCode,
1064                                        res.returnMsg, extras);
1065                            } catch (RemoteException e) {
1066                                Slog.i(TAG, "Observer no longer exists.");
1067                            }
1068                        }
1069                    } else {
1070                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1071                    }
1072                } break;
1073                case UPDATED_MEDIA_STATUS: {
1074                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1075                    boolean reportStatus = msg.arg1 == 1;
1076                    boolean doGc = msg.arg2 == 1;
1077                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1078                    if (doGc) {
1079                        // Force a gc to clear up stale containers.
1080                        Runtime.getRuntime().gc();
1081                    }
1082                    if (msg.obj != null) {
1083                        @SuppressWarnings("unchecked")
1084                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1085                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1086                        // Unload containers
1087                        unloadAllContainers(args);
1088                    }
1089                    if (reportStatus) {
1090                        try {
1091                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1092                            PackageHelper.getMountService().finishMediaUpdate();
1093                        } catch (RemoteException e) {
1094                            Log.e(TAG, "MountService not running?");
1095                        }
1096                    }
1097                } break;
1098                case WRITE_SETTINGS: {
1099                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1100                    synchronized (mPackages) {
1101                        removeMessages(WRITE_SETTINGS);
1102                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1103                        mSettings.writeLPr();
1104                        mDirtyUsers.clear();
1105                    }
1106                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1107                } break;
1108                case WRITE_PACKAGE_RESTRICTIONS: {
1109                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1110                    synchronized (mPackages) {
1111                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1112                        for (int userId : mDirtyUsers) {
1113                            mSettings.writePackageRestrictionsLPr(userId);
1114                        }
1115                        mDirtyUsers.clear();
1116                    }
1117                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1118                } break;
1119                case CHECK_PENDING_VERIFICATION: {
1120                    final int verificationId = msg.arg1;
1121                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1122
1123                    if ((state != null) && !state.timeoutExtended()) {
1124                        final InstallArgs args = state.getInstallArgs();
1125                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1126
1127                        Slog.i(TAG, "Verification timed out for " + originUri);
1128                        mPendingVerification.remove(verificationId);
1129
1130                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1131
1132                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1133                            Slog.i(TAG, "Continuing with installation of " + originUri);
1134                            state.setVerifierResponse(Binder.getCallingUid(),
1135                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1136                            broadcastPackageVerified(verificationId, originUri,
1137                                    PackageManager.VERIFICATION_ALLOW,
1138                                    state.getInstallArgs().getUser());
1139                            try {
1140                                ret = args.copyApk(mContainerService, true);
1141                            } catch (RemoteException e) {
1142                                Slog.e(TAG, "Could not contact the ContainerService");
1143                            }
1144                        } else {
1145                            broadcastPackageVerified(verificationId, originUri,
1146                                    PackageManager.VERIFICATION_REJECT,
1147                                    state.getInstallArgs().getUser());
1148                        }
1149
1150                        processPendingInstall(args, ret);
1151                        mHandler.sendEmptyMessage(MCS_UNBIND);
1152                    }
1153                    break;
1154                }
1155                case PACKAGE_VERIFIED: {
1156                    final int verificationId = msg.arg1;
1157
1158                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1159                    if (state == null) {
1160                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1161                        break;
1162                    }
1163
1164                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1165
1166                    state.setVerifierResponse(response.callerUid, response.code);
1167
1168                    if (state.isVerificationComplete()) {
1169                        mPendingVerification.remove(verificationId);
1170
1171                        final InstallArgs args = state.getInstallArgs();
1172                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1173
1174                        int ret;
1175                        if (state.isInstallAllowed()) {
1176                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1177                            broadcastPackageVerified(verificationId, originUri,
1178                                    response.code, state.getInstallArgs().getUser());
1179                            try {
1180                                ret = args.copyApk(mContainerService, true);
1181                            } catch (RemoteException e) {
1182                                Slog.e(TAG, "Could not contact the ContainerService");
1183                            }
1184                        } else {
1185                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1186                        }
1187
1188                        processPendingInstall(args, ret);
1189
1190                        mHandler.sendEmptyMessage(MCS_UNBIND);
1191                    }
1192
1193                    break;
1194                }
1195            }
1196        }
1197    }
1198
1199    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1200        Bundle extras = null;
1201        switch (res.returnCode) {
1202            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1203                extras = new Bundle();
1204                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1205                        res.origPermission);
1206                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1207                        res.origPackage);
1208                break;
1209            }
1210        }
1211        return extras;
1212    }
1213
1214    void scheduleWriteSettingsLocked() {
1215        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1216            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1217        }
1218    }
1219
1220    void scheduleWritePackageRestrictionsLocked(int userId) {
1221        if (!sUserManager.exists(userId)) return;
1222        mDirtyUsers.add(userId);
1223        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1224            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1225        }
1226    }
1227
1228    public static final PackageManagerService main(Context context, Installer installer,
1229            boolean factoryTest, boolean onlyCore) {
1230        PackageManagerService m = new PackageManagerService(context, installer,
1231                factoryTest, onlyCore);
1232        ServiceManager.addService("package", m);
1233        return m;
1234    }
1235
1236    static String[] splitString(String str, char sep) {
1237        int count = 1;
1238        int i = 0;
1239        while ((i=str.indexOf(sep, i)) >= 0) {
1240            count++;
1241            i++;
1242        }
1243
1244        String[] res = new String[count];
1245        i=0;
1246        count = 0;
1247        int lastI=0;
1248        while ((i=str.indexOf(sep, i)) >= 0) {
1249            res[count] = str.substring(lastI, i);
1250            count++;
1251            i++;
1252            lastI = i;
1253        }
1254        res[count] = str.substring(lastI, str.length());
1255        return res;
1256    }
1257
1258    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1259        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1260                Context.DISPLAY_SERVICE);
1261        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1262    }
1263
1264    public PackageManagerService(Context context, Installer installer,
1265            boolean factoryTest, boolean onlyCore) {
1266        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1267                SystemClock.uptimeMillis());
1268
1269        if (mSdkVersion <= 0) {
1270            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1271        }
1272
1273        mContext = context;
1274        mFactoryTest = factoryTest;
1275        mOnlyCore = onlyCore;
1276        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1277        mMetrics = new DisplayMetrics();
1278        mSettings = new Settings(context);
1279        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1280                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1281        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1282                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1283        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291
1292        String separateProcesses = SystemProperties.get("debug.separate_processes");
1293        if (separateProcesses != null && separateProcesses.length() > 0) {
1294            if ("*".equals(separateProcesses)) {
1295                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1296                mSeparateProcesses = null;
1297                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1298            } else {
1299                mDefParseFlags = 0;
1300                mSeparateProcesses = separateProcesses.split(",");
1301                Slog.w(TAG, "Running with debug.separate_processes: "
1302                        + separateProcesses);
1303            }
1304        } else {
1305            mDefParseFlags = 0;
1306            mSeparateProcesses = null;
1307        }
1308
1309        mInstaller = installer;
1310
1311        getDefaultDisplayMetrics(context, mMetrics);
1312
1313        SystemConfig systemConfig = SystemConfig.getInstance();
1314        mGlobalGids = systemConfig.getGlobalGids();
1315        mSystemPermissions = systemConfig.getSystemPermissions();
1316        mAvailableFeatures = systemConfig.getAvailableFeatures();
1317
1318        synchronized (mInstallLock) {
1319        // writer
1320        synchronized (mPackages) {
1321            mHandlerThread = new ServiceThread(TAG,
1322                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1323            mHandlerThread.start();
1324            mHandler = new PackageHandler(mHandlerThread.getLooper());
1325            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1326
1327            File dataDir = Environment.getDataDirectory();
1328            mAppDataDir = new File(dataDir, "data");
1329            mAppInstallDir = new File(dataDir, "app");
1330            mAppLib32InstallDir = new File(dataDir, "app-lib");
1331            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1332            mUserAppDataDir = new File(dataDir, "user");
1333            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1334
1335            sUserManager = new UserManagerService(context, this,
1336                    mInstallLock, mPackages);
1337
1338            // Propagate permission configuration in to package manager.
1339            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1340                    = systemConfig.getPermissions();
1341            for (int i=0; i<permConfig.size(); i++) {
1342                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1343                BasePermission bp = mSettings.mPermissions.get(perm.name);
1344                if (bp == null) {
1345                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1346                    mSettings.mPermissions.put(perm.name, bp);
1347                }
1348                if (perm.gids != null) {
1349                    bp.gids = appendInts(bp.gids, perm.gids);
1350                }
1351            }
1352
1353            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1354            for (int i=0; i<libConfig.size(); i++) {
1355                mSharedLibraries.put(libConfig.keyAt(i),
1356                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1357            }
1358
1359            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1360
1361            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1362                    mSdkVersion, mOnlyCore);
1363
1364            String customResolverActivity = Resources.getSystem().getString(
1365                    R.string.config_customResolverActivity);
1366            if (TextUtils.isEmpty(customResolverActivity)) {
1367                customResolverActivity = null;
1368            } else {
1369                mCustomResolverComponentName = ComponentName.unflattenFromString(
1370                        customResolverActivity);
1371            }
1372
1373            long startTime = SystemClock.uptimeMillis();
1374
1375            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1376                    startTime);
1377
1378            // Set flag to monitor and not change apk file paths when
1379            // scanning install directories.
1380            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1381
1382            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1383
1384            /**
1385             * Add everything in the in the boot class path to the
1386             * list of process files because dexopt will have been run
1387             * if necessary during zygote startup.
1388             */
1389            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1390            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1391
1392            if (bootClassPath != null) {
1393                String[] bootClassPathElements = splitString(bootClassPath, ':');
1394                for (String element : bootClassPathElements) {
1395                    alreadyDexOpted.add(element);
1396                }
1397            } else {
1398                Slog.w(TAG, "No BOOTCLASSPATH found!");
1399            }
1400
1401            if (systemServerClassPath != null) {
1402                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1403                for (String element : systemServerClassPathElements) {
1404                    alreadyDexOpted.add(element);
1405                }
1406            } else {
1407                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1408            }
1409
1410            boolean didDexOptLibraryOrTool = false;
1411
1412            final List<String> allInstructionSets = getAllInstructionSets();
1413            final String[] dexCodeInstructionSets =
1414                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1415
1416            /**
1417             * Ensure all external libraries have had dexopt run on them.
1418             */
1419            if (mSharedLibraries.size() > 0) {
1420                // NOTE: For now, we're compiling these system "shared libraries"
1421                // (and framework jars) into all available architectures. It's possible
1422                // to compile them only when we come across an app that uses them (there's
1423                // already logic for that in scanPackageLI) but that adds some complexity.
1424                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1425                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1426                        final String lib = libEntry.path;
1427                        if (lib == null) {
1428                            continue;
1429                        }
1430
1431                        try {
1432                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1433                                                                                 dexCodeInstructionSet,
1434                                                                                 false);
1435                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1436                                alreadyDexOpted.add(lib);
1437
1438                                // The list of "shared libraries" we have at this point is
1439                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1440                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1441                                } else {
1442                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1443                                }
1444                                didDexOptLibraryOrTool = true;
1445                            }
1446                        } catch (FileNotFoundException e) {
1447                            Slog.w(TAG, "Library not found: " + lib);
1448                        } catch (IOException e) {
1449                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1450                                    + e.getMessage());
1451                        }
1452                    }
1453                }
1454            }
1455
1456            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1457
1458            // Gross hack for now: we know this file doesn't contain any
1459            // code, so don't dexopt it to avoid the resulting log spew.
1460            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1461
1462            // Gross hack for now: we know this file is only part of
1463            // the boot class path for art, so don't dexopt it to
1464            // avoid the resulting log spew.
1465            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1466
1467            /**
1468             * And there are a number of commands implemented in Java, which
1469             * we currently need to do the dexopt on so that they can be
1470             * run from a non-root shell.
1471             */
1472            String[] frameworkFiles = frameworkDir.list();
1473            if (frameworkFiles != null) {
1474                // TODO: We could compile these only for the most preferred ABI. We should
1475                // first double check that the dex files for these commands are not referenced
1476                // by other system apps.
1477                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1478                    for (int i=0; i<frameworkFiles.length; i++) {
1479                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1480                        String path = libPath.getPath();
1481                        // Skip the file if we already did it.
1482                        if (alreadyDexOpted.contains(path)) {
1483                            continue;
1484                        }
1485                        // Skip the file if it is not a type we want to dexopt.
1486                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1487                            continue;
1488                        }
1489                        try {
1490                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1491                                                                                 dexCodeInstructionSet,
1492                                                                                 false);
1493                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1494                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1495                                didDexOptLibraryOrTool = true;
1496                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1497                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1498                                didDexOptLibraryOrTool = true;
1499                            }
1500                        } catch (FileNotFoundException e) {
1501                            Slog.w(TAG, "Jar not found: " + path);
1502                        } catch (IOException e) {
1503                            Slog.w(TAG, "Exception reading jar: " + path, e);
1504                        }
1505                    }
1506                }
1507            }
1508
1509            // Collect vendor overlay packages.
1510            // (Do this before scanning any apps.)
1511            // For security and version matching reason, only consider
1512            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1513            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1514            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1515                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1516
1517            // Find base frameworks (resource packages without code).
1518            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1519                    | PackageParser.PARSE_IS_SYSTEM_DIR
1520                    | PackageParser.PARSE_IS_PRIVILEGED,
1521                    scanFlags | SCAN_NO_DEX, 0);
1522
1523            // Collected privileged system packages.
1524            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1525            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1526                    | PackageParser.PARSE_IS_SYSTEM_DIR
1527                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1528
1529            // Collect ordinary system packages.
1530            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1531            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1532                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1533
1534            // Collect all vendor packages.
1535            File vendorAppDir = new File("/vendor/app");
1536            try {
1537                vendorAppDir = vendorAppDir.getCanonicalFile();
1538            } catch (IOException e) {
1539                // failed to look up canonical path, continue with original one
1540            }
1541            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1542                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1543
1544            // Collect all OEM packages.
1545            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1546            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1547                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1548
1549            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1550            mInstaller.moveFiles();
1551
1552            // Prune any system packages that no longer exist.
1553            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1554            if (!mOnlyCore) {
1555                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1556                while (psit.hasNext()) {
1557                    PackageSetting ps = psit.next();
1558
1559                    /*
1560                     * If this is not a system app, it can't be a
1561                     * disable system app.
1562                     */
1563                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1564                        continue;
1565                    }
1566
1567                    /*
1568                     * If the package is scanned, it's not erased.
1569                     */
1570                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1571                    if (scannedPkg != null) {
1572                        /*
1573                         * If the system app is both scanned and in the
1574                         * disabled packages list, then it must have been
1575                         * added via OTA. Remove it from the currently
1576                         * scanned package so the previously user-installed
1577                         * application can be scanned.
1578                         */
1579                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1580                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1581                                    + "; removing system app");
1582                            removePackageLI(ps, true);
1583                        }
1584
1585                        continue;
1586                    }
1587
1588                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1589                        psit.remove();
1590                        String msg = "System package " + ps.name
1591                                + " no longer exists; wiping its data";
1592                        reportSettingsProblem(Log.WARN, msg);
1593                        removeDataDirsLI(ps.name);
1594                    } else {
1595                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1596                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1597                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1598                        }
1599                    }
1600                }
1601            }
1602
1603            //look for any incomplete package installations
1604            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1605            //clean up list
1606            for(int i = 0; i < deletePkgsList.size(); i++) {
1607                //clean up here
1608                cleanupInstallFailedPackage(deletePkgsList.get(i));
1609            }
1610            //delete tmp files
1611            deleteTempPackageFiles();
1612
1613            // Remove any shared userIDs that have no associated packages
1614            mSettings.pruneSharedUsersLPw();
1615
1616            if (!mOnlyCore) {
1617                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1618                        SystemClock.uptimeMillis());
1619                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1620
1621                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1622                        scanFlags, 0);
1623
1624                /**
1625                 * Remove disable package settings for any updated system
1626                 * apps that were removed via an OTA. If they're not a
1627                 * previously-updated app, remove them completely.
1628                 * Otherwise, just revoke their system-level permissions.
1629                 */
1630                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1631                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1632                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1633
1634                    String msg;
1635                    if (deletedPkg == null) {
1636                        msg = "Updated system package " + deletedAppName
1637                                + " no longer exists; wiping its data";
1638                        removeDataDirsLI(deletedAppName);
1639                    } else {
1640                        msg = "Updated system app + " + deletedAppName
1641                                + " no longer present; removing system privileges for "
1642                                + deletedAppName;
1643
1644                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1645
1646                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1647                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1648                    }
1649                    reportSettingsProblem(Log.WARN, msg);
1650                }
1651            }
1652
1653            // Now that we know all of the shared libraries, update all clients to have
1654            // the correct library paths.
1655            updateAllSharedLibrariesLPw();
1656
1657            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1658                // NOTE: We ignore potential failures here during a system scan (like
1659                // the rest of the commands above) because there's precious little we
1660                // can do about it. A settings error is reported, though.
1661                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1662                        false /* force dexopt */, false /* defer dexopt */);
1663            }
1664
1665            // Now that we know all the packages we are keeping,
1666            // read and update their last usage times.
1667            mPackageUsage.readLP();
1668
1669            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1670                    SystemClock.uptimeMillis());
1671            Slog.i(TAG, "Time to scan packages: "
1672                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1673                    + " seconds");
1674
1675            // If the platform SDK has changed since the last time we booted,
1676            // we need to re-grant app permission to catch any new ones that
1677            // appear.  This is really a hack, and means that apps can in some
1678            // cases get permissions that the user didn't initially explicitly
1679            // allow...  it would be nice to have some better way to handle
1680            // this situation.
1681            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1682                    != mSdkVersion;
1683            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1684                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1685                    + "; regranting permissions for internal storage");
1686            mSettings.mInternalSdkPlatform = mSdkVersion;
1687
1688            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1689                    | (regrantPermissions
1690                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1691                            : 0));
1692
1693            // If this is the first boot, and it is a normal boot, then
1694            // we need to initialize the default preferred apps.
1695            if (!mRestoredSettings && !onlyCore) {
1696                mSettings.readDefaultPreferredAppsLPw(this, 0);
1697            }
1698
1699            // If this is first boot after an OTA, and a normal boot, then
1700            // we need to clear code cache directories.
1701            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1702                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1703                for (String pkgName : mSettings.mPackages.keySet()) {
1704                    deleteCodeCacheDirsLI(pkgName);
1705                }
1706                mSettings.mFingerprint = Build.FINGERPRINT;
1707            }
1708
1709            // All the changes are done during package scanning.
1710            mSettings.updateInternalDatabaseVersion();
1711
1712            // can downgrade to reader
1713            mSettings.writeLPr();
1714
1715            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1716                    SystemClock.uptimeMillis());
1717
1718
1719            mRequiredVerifierPackage = getRequiredVerifierLPr();
1720        } // synchronized (mPackages)
1721        } // synchronized (mInstallLock)
1722
1723        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1724
1725        // Now after opening every single application zip, make sure they
1726        // are all flushed.  Not really needed, but keeps things nice and
1727        // tidy.
1728        Runtime.getRuntime().gc();
1729    }
1730
1731    @Override
1732    public boolean isFirstBoot() {
1733        return !mRestoredSettings;
1734    }
1735
1736    @Override
1737    public boolean isOnlyCoreApps() {
1738        return mOnlyCore;
1739    }
1740
1741    private String getRequiredVerifierLPr() {
1742        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1743        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1744                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1745
1746        String requiredVerifier = null;
1747
1748        final int N = receivers.size();
1749        for (int i = 0; i < N; i++) {
1750            final ResolveInfo info = receivers.get(i);
1751
1752            if (info.activityInfo == null) {
1753                continue;
1754            }
1755
1756            final String packageName = info.activityInfo.packageName;
1757
1758            final PackageSetting ps = mSettings.mPackages.get(packageName);
1759            if (ps == null) {
1760                continue;
1761            }
1762
1763            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1764            if (!gp.grantedPermissions
1765                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1766                continue;
1767            }
1768
1769            if (requiredVerifier != null) {
1770                throw new RuntimeException("There can be only one required verifier");
1771            }
1772
1773            requiredVerifier = packageName;
1774        }
1775
1776        return requiredVerifier;
1777    }
1778
1779    @Override
1780    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1781            throws RemoteException {
1782        try {
1783            return super.onTransact(code, data, reply, flags);
1784        } catch (RuntimeException e) {
1785            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1786                Slog.wtf(TAG, "Package Manager Crash", e);
1787            }
1788            throw e;
1789        }
1790    }
1791
1792    void cleanupInstallFailedPackage(PackageSetting ps) {
1793        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1794        removeDataDirsLI(ps.name);
1795        if (ps.codePath != null) {
1796            if (ps.codePath.isDirectory()) {
1797                FileUtils.deleteContents(ps.codePath);
1798            }
1799            ps.codePath.delete();
1800        }
1801        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1802            if (ps.resourcePath.isDirectory()) {
1803                FileUtils.deleteContents(ps.resourcePath);
1804            }
1805            ps.resourcePath.delete();
1806        }
1807        mSettings.removePackageLPw(ps.name);
1808    }
1809
1810    static int[] appendInts(int[] cur, int[] add) {
1811        if (add == null) return cur;
1812        if (cur == null) return add;
1813        final int N = add.length;
1814        for (int i=0; i<N; i++) {
1815            cur = appendInt(cur, add[i]);
1816        }
1817        return cur;
1818    }
1819
1820    static int[] removeInts(int[] cur, int[] rem) {
1821        if (rem == null) return cur;
1822        if (cur == null) return cur;
1823        final int N = rem.length;
1824        for (int i=0; i<N; i++) {
1825            cur = removeInt(cur, rem[i]);
1826        }
1827        return cur;
1828    }
1829
1830    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1831        if (!sUserManager.exists(userId)) return null;
1832        final PackageSetting ps = (PackageSetting) p.mExtras;
1833        if (ps == null) {
1834            return null;
1835        }
1836        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1837        final PackageUserState state = ps.readUserState(userId);
1838        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1839                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1840                state, userId);
1841    }
1842
1843    @Override
1844    public boolean isPackageAvailable(String packageName, int userId) {
1845        if (!sUserManager.exists(userId)) return false;
1846        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1847        synchronized (mPackages) {
1848            PackageParser.Package p = mPackages.get(packageName);
1849            if (p != null) {
1850                final PackageSetting ps = (PackageSetting) p.mExtras;
1851                if (ps != null) {
1852                    final PackageUserState state = ps.readUserState(userId);
1853                    if (state != null) {
1854                        return PackageParser.isAvailable(state);
1855                    }
1856                }
1857            }
1858        }
1859        return false;
1860    }
1861
1862    @Override
1863    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1864        if (!sUserManager.exists(userId)) return null;
1865        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1866        // reader
1867        synchronized (mPackages) {
1868            PackageParser.Package p = mPackages.get(packageName);
1869            if (DEBUG_PACKAGE_INFO)
1870                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1871            if (p != null) {
1872                return generatePackageInfo(p, flags, userId);
1873            }
1874            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1875                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1876            }
1877        }
1878        return null;
1879    }
1880
1881    @Override
1882    public String[] currentToCanonicalPackageNames(String[] names) {
1883        String[] out = new String[names.length];
1884        // reader
1885        synchronized (mPackages) {
1886            for (int i=names.length-1; i>=0; i--) {
1887                PackageSetting ps = mSettings.mPackages.get(names[i]);
1888                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1889            }
1890        }
1891        return out;
1892    }
1893
1894    @Override
1895    public String[] canonicalToCurrentPackageNames(String[] names) {
1896        String[] out = new String[names.length];
1897        // reader
1898        synchronized (mPackages) {
1899            for (int i=names.length-1; i>=0; i--) {
1900                String cur = mSettings.mRenamedPackages.get(names[i]);
1901                out[i] = cur != null ? cur : names[i];
1902            }
1903        }
1904        return out;
1905    }
1906
1907    @Override
1908    public int getPackageUid(String packageName, int userId) {
1909        if (!sUserManager.exists(userId)) return -1;
1910        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1911        // reader
1912        synchronized (mPackages) {
1913            PackageParser.Package p = mPackages.get(packageName);
1914            if(p != null) {
1915                return UserHandle.getUid(userId, p.applicationInfo.uid);
1916            }
1917            PackageSetting ps = mSettings.mPackages.get(packageName);
1918            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1919                return -1;
1920            }
1921            p = ps.pkg;
1922            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1923        }
1924    }
1925
1926    @Override
1927    public int[] getPackageGids(String packageName) {
1928        // reader
1929        synchronized (mPackages) {
1930            PackageParser.Package p = mPackages.get(packageName);
1931            if (DEBUG_PACKAGE_INFO)
1932                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1933            if (p != null) {
1934                final PackageSetting ps = (PackageSetting)p.mExtras;
1935                return ps.getGids();
1936            }
1937        }
1938        // stupid thing to indicate an error.
1939        return new int[0];
1940    }
1941
1942    static final PermissionInfo generatePermissionInfo(
1943            BasePermission bp, int flags) {
1944        if (bp.perm != null) {
1945            return PackageParser.generatePermissionInfo(bp.perm, flags);
1946        }
1947        PermissionInfo pi = new PermissionInfo();
1948        pi.name = bp.name;
1949        pi.packageName = bp.sourcePackage;
1950        pi.nonLocalizedLabel = bp.name;
1951        pi.protectionLevel = bp.protectionLevel;
1952        return pi;
1953    }
1954
1955    @Override
1956    public PermissionInfo getPermissionInfo(String name, int flags) {
1957        // reader
1958        synchronized (mPackages) {
1959            final BasePermission p = mSettings.mPermissions.get(name);
1960            if (p != null) {
1961                return generatePermissionInfo(p, flags);
1962            }
1963            return null;
1964        }
1965    }
1966
1967    @Override
1968    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1969        // reader
1970        synchronized (mPackages) {
1971            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1972            for (BasePermission p : mSettings.mPermissions.values()) {
1973                if (group == null) {
1974                    if (p.perm == null || p.perm.info.group == null) {
1975                        out.add(generatePermissionInfo(p, flags));
1976                    }
1977                } else {
1978                    if (p.perm != null && group.equals(p.perm.info.group)) {
1979                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1980                    }
1981                }
1982            }
1983
1984            if (out.size() > 0) {
1985                return out;
1986            }
1987            return mPermissionGroups.containsKey(group) ? out : null;
1988        }
1989    }
1990
1991    @Override
1992    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1993        // reader
1994        synchronized (mPackages) {
1995            return PackageParser.generatePermissionGroupInfo(
1996                    mPermissionGroups.get(name), flags);
1997        }
1998    }
1999
2000    @Override
2001    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2002        // reader
2003        synchronized (mPackages) {
2004            final int N = mPermissionGroups.size();
2005            ArrayList<PermissionGroupInfo> out
2006                    = new ArrayList<PermissionGroupInfo>(N);
2007            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2008                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2009            }
2010            return out;
2011        }
2012    }
2013
2014    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2015            int userId) {
2016        if (!sUserManager.exists(userId)) return null;
2017        PackageSetting ps = mSettings.mPackages.get(packageName);
2018        if (ps != null) {
2019            if (ps.pkg == null) {
2020                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2021                        flags, userId);
2022                if (pInfo != null) {
2023                    return pInfo.applicationInfo;
2024                }
2025                return null;
2026            }
2027            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2028                    ps.readUserState(userId), userId);
2029        }
2030        return null;
2031    }
2032
2033    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2034            int userId) {
2035        if (!sUserManager.exists(userId)) return null;
2036        PackageSetting ps = mSettings.mPackages.get(packageName);
2037        if (ps != null) {
2038            PackageParser.Package pkg = ps.pkg;
2039            if (pkg == null) {
2040                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2041                    return null;
2042                }
2043                // Only data remains, so we aren't worried about code paths
2044                pkg = new PackageParser.Package(packageName);
2045                pkg.applicationInfo.packageName = packageName;
2046                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2047                pkg.applicationInfo.dataDir =
2048                        getDataPathForPackage(packageName, 0).getPath();
2049                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2050                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2051            }
2052            return generatePackageInfo(pkg, flags, userId);
2053        }
2054        return null;
2055    }
2056
2057    @Override
2058    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2059        if (!sUserManager.exists(userId)) return null;
2060        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2061        // writer
2062        synchronized (mPackages) {
2063            PackageParser.Package p = mPackages.get(packageName);
2064            if (DEBUG_PACKAGE_INFO) Log.v(
2065                    TAG, "getApplicationInfo " + packageName
2066                    + ": " + p);
2067            if (p != null) {
2068                PackageSetting ps = mSettings.mPackages.get(packageName);
2069                if (ps == null) return null;
2070                // Note: isEnabledLP() does not apply here - always return info
2071                return PackageParser.generateApplicationInfo(
2072                        p, flags, ps.readUserState(userId), userId);
2073            }
2074            if ("android".equals(packageName)||"system".equals(packageName)) {
2075                return mAndroidApplication;
2076            }
2077            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2078                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2079            }
2080        }
2081        return null;
2082    }
2083
2084
2085    @Override
2086    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2087        mContext.enforceCallingOrSelfPermission(
2088                android.Manifest.permission.CLEAR_APP_CACHE, null);
2089        // Queue up an async operation since clearing cache may take a little while.
2090        mHandler.post(new Runnable() {
2091            public void run() {
2092                mHandler.removeCallbacks(this);
2093                int retCode = -1;
2094                synchronized (mInstallLock) {
2095                    retCode = mInstaller.freeCache(freeStorageSize);
2096                    if (retCode < 0) {
2097                        Slog.w(TAG, "Couldn't clear application caches");
2098                    }
2099                }
2100                if (observer != null) {
2101                    try {
2102                        observer.onRemoveCompleted(null, (retCode >= 0));
2103                    } catch (RemoteException e) {
2104                        Slog.w(TAG, "RemoveException when invoking call back");
2105                    }
2106                }
2107            }
2108        });
2109    }
2110
2111    @Override
2112    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2113        mContext.enforceCallingOrSelfPermission(
2114                android.Manifest.permission.CLEAR_APP_CACHE, null);
2115        // Queue up an async operation since clearing cache may take a little while.
2116        mHandler.post(new Runnable() {
2117            public void run() {
2118                mHandler.removeCallbacks(this);
2119                int retCode = -1;
2120                synchronized (mInstallLock) {
2121                    retCode = mInstaller.freeCache(freeStorageSize);
2122                    if (retCode < 0) {
2123                        Slog.w(TAG, "Couldn't clear application caches");
2124                    }
2125                }
2126                if(pi != null) {
2127                    try {
2128                        // Callback via pending intent
2129                        int code = (retCode >= 0) ? 1 : 0;
2130                        pi.sendIntent(null, code, null,
2131                                null, null);
2132                    } catch (SendIntentException e1) {
2133                        Slog.i(TAG, "Failed to send pending intent");
2134                    }
2135                }
2136            }
2137        });
2138    }
2139
2140    void freeStorage(long freeStorageSize) throws IOException {
2141        synchronized (mInstallLock) {
2142            if (mInstaller.freeCache(freeStorageSize) < 0) {
2143                throw new IOException("Failed to free enough space");
2144            }
2145        }
2146    }
2147
2148    @Override
2149    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2150        if (!sUserManager.exists(userId)) return null;
2151        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2152        synchronized (mPackages) {
2153            PackageParser.Activity a = mActivities.mActivities.get(component);
2154
2155            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2156            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2157                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2158                if (ps == null) return null;
2159                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2160                        userId);
2161            }
2162            if (mResolveComponentName.equals(component)) {
2163                return mResolveActivity;
2164            }
2165        }
2166        return null;
2167    }
2168
2169    @Override
2170    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2171            String resolvedType) {
2172        synchronized (mPackages) {
2173            PackageParser.Activity a = mActivities.mActivities.get(component);
2174            if (a == null) {
2175                return false;
2176            }
2177            for (int i=0; i<a.intents.size(); i++) {
2178                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2179                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2180                    return true;
2181                }
2182            }
2183            return false;
2184        }
2185    }
2186
2187    @Override
2188    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2189        if (!sUserManager.exists(userId)) return null;
2190        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2191        synchronized (mPackages) {
2192            PackageParser.Activity a = mReceivers.mActivities.get(component);
2193            if (DEBUG_PACKAGE_INFO) Log.v(
2194                TAG, "getReceiverInfo " + component + ": " + a);
2195            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2196                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2197                if (ps == null) return null;
2198                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2199                        userId);
2200            }
2201        }
2202        return null;
2203    }
2204
2205    @Override
2206    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2207        if (!sUserManager.exists(userId)) return null;
2208        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2209        synchronized (mPackages) {
2210            PackageParser.Service s = mServices.mServices.get(component);
2211            if (DEBUG_PACKAGE_INFO) Log.v(
2212                TAG, "getServiceInfo " + component + ": " + s);
2213            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2214                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2215                if (ps == null) return null;
2216                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2217                        userId);
2218            }
2219        }
2220        return null;
2221    }
2222
2223    @Override
2224    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2225        if (!sUserManager.exists(userId)) return null;
2226        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2227        synchronized (mPackages) {
2228            PackageParser.Provider p = mProviders.mProviders.get(component);
2229            if (DEBUG_PACKAGE_INFO) Log.v(
2230                TAG, "getProviderInfo " + component + ": " + p);
2231            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2232                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2233                if (ps == null) return null;
2234                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2235                        userId);
2236            }
2237        }
2238        return null;
2239    }
2240
2241    @Override
2242    public String[] getSystemSharedLibraryNames() {
2243        Set<String> libSet;
2244        synchronized (mPackages) {
2245            libSet = mSharedLibraries.keySet();
2246            int size = libSet.size();
2247            if (size > 0) {
2248                String[] libs = new String[size];
2249                libSet.toArray(libs);
2250                return libs;
2251            }
2252        }
2253        return null;
2254    }
2255
2256    @Override
2257    public FeatureInfo[] getSystemAvailableFeatures() {
2258        Collection<FeatureInfo> featSet;
2259        synchronized (mPackages) {
2260            featSet = mAvailableFeatures.values();
2261            int size = featSet.size();
2262            if (size > 0) {
2263                FeatureInfo[] features = new FeatureInfo[size+1];
2264                featSet.toArray(features);
2265                FeatureInfo fi = new FeatureInfo();
2266                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2267                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2268                features[size] = fi;
2269                return features;
2270            }
2271        }
2272        return null;
2273    }
2274
2275    @Override
2276    public boolean hasSystemFeature(String name) {
2277        synchronized (mPackages) {
2278            return mAvailableFeatures.containsKey(name);
2279        }
2280    }
2281
2282    private void checkValidCaller(int uid, int userId) {
2283        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2284            return;
2285
2286        throw new SecurityException("Caller uid=" + uid
2287                + " is not privileged to communicate with user=" + userId);
2288    }
2289
2290    @Override
2291    public int checkPermission(String permName, String pkgName) {
2292        synchronized (mPackages) {
2293            PackageParser.Package p = mPackages.get(pkgName);
2294            if (p != null && p.mExtras != null) {
2295                PackageSetting ps = (PackageSetting)p.mExtras;
2296                if (ps.sharedUser != null) {
2297                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2298                        return PackageManager.PERMISSION_GRANTED;
2299                    }
2300                } else if (ps.grantedPermissions.contains(permName)) {
2301                    return PackageManager.PERMISSION_GRANTED;
2302                }
2303            }
2304        }
2305        return PackageManager.PERMISSION_DENIED;
2306    }
2307
2308    @Override
2309    public int checkUidPermission(String permName, int uid) {
2310        synchronized (mPackages) {
2311            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2312            if (obj != null) {
2313                GrantedPermissions gp = (GrantedPermissions)obj;
2314                if (gp.grantedPermissions.contains(permName)) {
2315                    return PackageManager.PERMISSION_GRANTED;
2316                }
2317            } else {
2318                HashSet<String> perms = mSystemPermissions.get(uid);
2319                if (perms != null && perms.contains(permName)) {
2320                    return PackageManager.PERMISSION_GRANTED;
2321                }
2322            }
2323        }
2324        return PackageManager.PERMISSION_DENIED;
2325    }
2326
2327    /**
2328     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2329     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2330     * @param message the message to log on security exception
2331     */
2332    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2333            String message) {
2334        if (userId < 0) {
2335            throw new IllegalArgumentException("Invalid userId " + userId);
2336        }
2337        if (userId == UserHandle.getUserId(callingUid)) return;
2338        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2339            if (requireFullPermission) {
2340                mContext.enforceCallingOrSelfPermission(
2341                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2342            } else {
2343                try {
2344                    mContext.enforceCallingOrSelfPermission(
2345                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2346                } catch (SecurityException se) {
2347                    mContext.enforceCallingOrSelfPermission(
2348                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2349                }
2350            }
2351        }
2352    }
2353
2354    private BasePermission findPermissionTreeLP(String permName) {
2355        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2356            if (permName.startsWith(bp.name) &&
2357                    permName.length() > bp.name.length() &&
2358                    permName.charAt(bp.name.length()) == '.') {
2359                return bp;
2360            }
2361        }
2362        return null;
2363    }
2364
2365    private BasePermission checkPermissionTreeLP(String permName) {
2366        if (permName != null) {
2367            BasePermission bp = findPermissionTreeLP(permName);
2368            if (bp != null) {
2369                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2370                    return bp;
2371                }
2372                throw new SecurityException("Calling uid "
2373                        + Binder.getCallingUid()
2374                        + " is not allowed to add to permission tree "
2375                        + bp.name + " owned by uid " + bp.uid);
2376            }
2377        }
2378        throw new SecurityException("No permission tree found for " + permName);
2379    }
2380
2381    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2382        if (s1 == null) {
2383            return s2 == null;
2384        }
2385        if (s2 == null) {
2386            return false;
2387        }
2388        if (s1.getClass() != s2.getClass()) {
2389            return false;
2390        }
2391        return s1.equals(s2);
2392    }
2393
2394    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2395        if (pi1.icon != pi2.icon) return false;
2396        if (pi1.logo != pi2.logo) return false;
2397        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2398        if (!compareStrings(pi1.name, pi2.name)) return false;
2399        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2400        // We'll take care of setting this one.
2401        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2402        // These are not currently stored in settings.
2403        //if (!compareStrings(pi1.group, pi2.group)) return false;
2404        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2405        //if (pi1.labelRes != pi2.labelRes) return false;
2406        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2407        return true;
2408    }
2409
2410    int permissionInfoFootprint(PermissionInfo info) {
2411        int size = info.name.length();
2412        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2413        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2414        return size;
2415    }
2416
2417    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2418        int size = 0;
2419        for (BasePermission perm : mSettings.mPermissions.values()) {
2420            if (perm.uid == tree.uid) {
2421                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2422            }
2423        }
2424        return size;
2425    }
2426
2427    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2428        // We calculate the max size of permissions defined by this uid and throw
2429        // if that plus the size of 'info' would exceed our stated maximum.
2430        if (tree.uid != Process.SYSTEM_UID) {
2431            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2432            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2433                throw new SecurityException("Permission tree size cap exceeded");
2434            }
2435        }
2436    }
2437
2438    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2439        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2440            throw new SecurityException("Label must be specified in permission");
2441        }
2442        BasePermission tree = checkPermissionTreeLP(info.name);
2443        BasePermission bp = mSettings.mPermissions.get(info.name);
2444        boolean added = bp == null;
2445        boolean changed = true;
2446        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2447        if (added) {
2448            enforcePermissionCapLocked(info, tree);
2449            bp = new BasePermission(info.name, tree.sourcePackage,
2450                    BasePermission.TYPE_DYNAMIC);
2451        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2452            throw new SecurityException(
2453                    "Not allowed to modify non-dynamic permission "
2454                    + info.name);
2455        } else {
2456            if (bp.protectionLevel == fixedLevel
2457                    && bp.perm.owner.equals(tree.perm.owner)
2458                    && bp.uid == tree.uid
2459                    && comparePermissionInfos(bp.perm.info, info)) {
2460                changed = false;
2461            }
2462        }
2463        bp.protectionLevel = fixedLevel;
2464        info = new PermissionInfo(info);
2465        info.protectionLevel = fixedLevel;
2466        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2467        bp.perm.info.packageName = tree.perm.info.packageName;
2468        bp.uid = tree.uid;
2469        if (added) {
2470            mSettings.mPermissions.put(info.name, bp);
2471        }
2472        if (changed) {
2473            if (!async) {
2474                mSettings.writeLPr();
2475            } else {
2476                scheduleWriteSettingsLocked();
2477            }
2478        }
2479        return added;
2480    }
2481
2482    @Override
2483    public boolean addPermission(PermissionInfo info) {
2484        synchronized (mPackages) {
2485            return addPermissionLocked(info, false);
2486        }
2487    }
2488
2489    @Override
2490    public boolean addPermissionAsync(PermissionInfo info) {
2491        synchronized (mPackages) {
2492            return addPermissionLocked(info, true);
2493        }
2494    }
2495
2496    @Override
2497    public void removePermission(String name) {
2498        synchronized (mPackages) {
2499            checkPermissionTreeLP(name);
2500            BasePermission bp = mSettings.mPermissions.get(name);
2501            if (bp != null) {
2502                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2503                    throw new SecurityException(
2504                            "Not allowed to modify non-dynamic permission "
2505                            + name);
2506                }
2507                mSettings.mPermissions.remove(name);
2508                mSettings.writeLPr();
2509            }
2510        }
2511    }
2512
2513    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2514        int index = pkg.requestedPermissions.indexOf(bp.name);
2515        if (index == -1) {
2516            throw new SecurityException("Package " + pkg.packageName
2517                    + " has not requested permission " + bp.name);
2518        }
2519        boolean isNormal =
2520                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2521                        == PermissionInfo.PROTECTION_NORMAL);
2522        boolean isDangerous =
2523                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2524                        == PermissionInfo.PROTECTION_DANGEROUS);
2525        boolean isDevelopment =
2526                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2527
2528        if (!isNormal && !isDangerous && !isDevelopment) {
2529            throw new SecurityException("Permission " + bp.name
2530                    + " is not a changeable permission type");
2531        }
2532
2533        if (isNormal || isDangerous) {
2534            if (pkg.requestedPermissionsRequired.get(index)) {
2535                throw new SecurityException("Can't change " + bp.name
2536                        + ". It is required by the application");
2537            }
2538        }
2539    }
2540
2541    @Override
2542    public void grantPermission(String packageName, String permissionName) {
2543        mContext.enforceCallingOrSelfPermission(
2544                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2545        synchronized (mPackages) {
2546            final PackageParser.Package pkg = mPackages.get(packageName);
2547            if (pkg == null) {
2548                throw new IllegalArgumentException("Unknown package: " + packageName);
2549            }
2550            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2551            if (bp == null) {
2552                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2553            }
2554
2555            checkGrantRevokePermissions(pkg, bp);
2556
2557            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2558            if (ps == null) {
2559                return;
2560            }
2561            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2562            if (gp.grantedPermissions.add(permissionName)) {
2563                if (ps.haveGids) {
2564                    gp.gids = appendInts(gp.gids, bp.gids);
2565                }
2566                mSettings.writeLPr();
2567            }
2568        }
2569    }
2570
2571    @Override
2572    public void revokePermission(String packageName, String permissionName) {
2573        int changedAppId = -1;
2574
2575        synchronized (mPackages) {
2576            final PackageParser.Package pkg = mPackages.get(packageName);
2577            if (pkg == null) {
2578                throw new IllegalArgumentException("Unknown package: " + packageName);
2579            }
2580            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2581                mContext.enforceCallingOrSelfPermission(
2582                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2583            }
2584            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2585            if (bp == null) {
2586                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2587            }
2588
2589            checkGrantRevokePermissions(pkg, bp);
2590
2591            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2592            if (ps == null) {
2593                return;
2594            }
2595            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2596            if (gp.grantedPermissions.remove(permissionName)) {
2597                gp.grantedPermissions.remove(permissionName);
2598                if (ps.haveGids) {
2599                    gp.gids = removeInts(gp.gids, bp.gids);
2600                }
2601                mSettings.writeLPr();
2602                changedAppId = ps.appId;
2603            }
2604        }
2605
2606        if (changedAppId >= 0) {
2607            // We changed the perm on someone, kill its processes.
2608            IActivityManager am = ActivityManagerNative.getDefault();
2609            if (am != null) {
2610                final int callingUserId = UserHandle.getCallingUserId();
2611                final long ident = Binder.clearCallingIdentity();
2612                try {
2613                    //XXX we should only revoke for the calling user's app permissions,
2614                    // but for now we impact all users.
2615                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2616                    //        "revoke " + permissionName);
2617                    int[] users = sUserManager.getUserIds();
2618                    for (int user : users) {
2619                        am.killUid(UserHandle.getUid(user, changedAppId),
2620                                "revoke " + permissionName);
2621                    }
2622                } catch (RemoteException e) {
2623                } finally {
2624                    Binder.restoreCallingIdentity(ident);
2625                }
2626            }
2627        }
2628    }
2629
2630    @Override
2631    public boolean isProtectedBroadcast(String actionName) {
2632        synchronized (mPackages) {
2633            return mProtectedBroadcasts.contains(actionName);
2634        }
2635    }
2636
2637    @Override
2638    public int checkSignatures(String pkg1, String pkg2) {
2639        synchronized (mPackages) {
2640            final PackageParser.Package p1 = mPackages.get(pkg1);
2641            final PackageParser.Package p2 = mPackages.get(pkg2);
2642            if (p1 == null || p1.mExtras == null
2643                    || p2 == null || p2.mExtras == null) {
2644                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2645            }
2646            return compareSignatures(p1.mSignatures, p2.mSignatures);
2647        }
2648    }
2649
2650    @Override
2651    public int checkUidSignatures(int uid1, int uid2) {
2652        // Map to base uids.
2653        uid1 = UserHandle.getAppId(uid1);
2654        uid2 = UserHandle.getAppId(uid2);
2655        // reader
2656        synchronized (mPackages) {
2657            Signature[] s1;
2658            Signature[] s2;
2659            Object obj = mSettings.getUserIdLPr(uid1);
2660            if (obj != null) {
2661                if (obj instanceof SharedUserSetting) {
2662                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2663                } else if (obj instanceof PackageSetting) {
2664                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2665                } else {
2666                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2667                }
2668            } else {
2669                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2670            }
2671            obj = mSettings.getUserIdLPr(uid2);
2672            if (obj != null) {
2673                if (obj instanceof SharedUserSetting) {
2674                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2675                } else if (obj instanceof PackageSetting) {
2676                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2677                } else {
2678                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2679                }
2680            } else {
2681                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2682            }
2683            return compareSignatures(s1, s2);
2684        }
2685    }
2686
2687    /**
2688     * Compares two sets of signatures. Returns:
2689     * <br />
2690     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2691     * <br />
2692     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2693     * <br />
2694     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2695     * <br />
2696     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2697     * <br />
2698     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2699     */
2700    static int compareSignatures(Signature[] s1, Signature[] s2) {
2701        if (s1 == null) {
2702            return s2 == null
2703                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2704                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2705        }
2706
2707        if (s2 == null) {
2708            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2709        }
2710
2711        if (s1.length != s2.length) {
2712            return PackageManager.SIGNATURE_NO_MATCH;
2713        }
2714
2715        // Since both signature sets are of size 1, we can compare without HashSets.
2716        if (s1.length == 1) {
2717            return s1[0].equals(s2[0]) ?
2718                    PackageManager.SIGNATURE_MATCH :
2719                    PackageManager.SIGNATURE_NO_MATCH;
2720        }
2721
2722        HashSet<Signature> set1 = new HashSet<Signature>();
2723        for (Signature sig : s1) {
2724            set1.add(sig);
2725        }
2726        HashSet<Signature> set2 = new HashSet<Signature>();
2727        for (Signature sig : s2) {
2728            set2.add(sig);
2729        }
2730        // Make sure s2 contains all signatures in s1.
2731        if (set1.equals(set2)) {
2732            return PackageManager.SIGNATURE_MATCH;
2733        }
2734        return PackageManager.SIGNATURE_NO_MATCH;
2735    }
2736
2737    /**
2738     * If the database version for this type of package (internal storage or
2739     * external storage) is less than the version where package signatures
2740     * were updated, return true.
2741     */
2742    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2743        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2744                DatabaseVersion.SIGNATURE_END_ENTITY))
2745                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2746                        DatabaseVersion.SIGNATURE_END_ENTITY));
2747    }
2748
2749    /**
2750     * Used for backward compatibility to make sure any packages with
2751     * certificate chains get upgraded to the new style. {@code existingSigs}
2752     * will be in the old format (since they were stored on disk from before the
2753     * system upgrade) and {@code scannedSigs} will be in the newer format.
2754     */
2755    private int compareSignaturesCompat(PackageSignatures existingSigs,
2756            PackageParser.Package scannedPkg) {
2757        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2758            return PackageManager.SIGNATURE_NO_MATCH;
2759        }
2760
2761        HashSet<Signature> existingSet = new HashSet<Signature>();
2762        for (Signature sig : existingSigs.mSignatures) {
2763            existingSet.add(sig);
2764        }
2765        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2766        for (Signature sig : scannedPkg.mSignatures) {
2767            try {
2768                Signature[] chainSignatures = sig.getChainSignatures();
2769                for (Signature chainSig : chainSignatures) {
2770                    scannedCompatSet.add(chainSig);
2771                }
2772            } catch (CertificateEncodingException e) {
2773                scannedCompatSet.add(sig);
2774            }
2775        }
2776        /*
2777         * Make sure the expanded scanned set contains all signatures in the
2778         * existing one.
2779         */
2780        if (scannedCompatSet.equals(existingSet)) {
2781            // Migrate the old signatures to the new scheme.
2782            existingSigs.assignSignatures(scannedPkg.mSignatures);
2783            // The new KeySets will be re-added later in the scanning process.
2784            synchronized (mPackages) {
2785                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2786            }
2787            return PackageManager.SIGNATURE_MATCH;
2788        }
2789        return PackageManager.SIGNATURE_NO_MATCH;
2790    }
2791
2792    @Override
2793    public String[] getPackagesForUid(int uid) {
2794        uid = UserHandle.getAppId(uid);
2795        // reader
2796        synchronized (mPackages) {
2797            Object obj = mSettings.getUserIdLPr(uid);
2798            if (obj instanceof SharedUserSetting) {
2799                final SharedUserSetting sus = (SharedUserSetting) obj;
2800                final int N = sus.packages.size();
2801                final String[] res = new String[N];
2802                final Iterator<PackageSetting> it = sus.packages.iterator();
2803                int i = 0;
2804                while (it.hasNext()) {
2805                    res[i++] = it.next().name;
2806                }
2807                return res;
2808            } else if (obj instanceof PackageSetting) {
2809                final PackageSetting ps = (PackageSetting) obj;
2810                return new String[] { ps.name };
2811            }
2812        }
2813        return null;
2814    }
2815
2816    @Override
2817    public String getNameForUid(int uid) {
2818        // reader
2819        synchronized (mPackages) {
2820            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2821            if (obj instanceof SharedUserSetting) {
2822                final SharedUserSetting sus = (SharedUserSetting) obj;
2823                return sus.name + ":" + sus.userId;
2824            } else if (obj instanceof PackageSetting) {
2825                final PackageSetting ps = (PackageSetting) obj;
2826                return ps.name;
2827            }
2828        }
2829        return null;
2830    }
2831
2832    @Override
2833    public int getUidForSharedUser(String sharedUserName) {
2834        if(sharedUserName == null) {
2835            return -1;
2836        }
2837        // reader
2838        synchronized (mPackages) {
2839            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2840            if (suid == null) {
2841                return -1;
2842            }
2843            return suid.userId;
2844        }
2845    }
2846
2847    @Override
2848    public int getFlagsForUid(int uid) {
2849        synchronized (mPackages) {
2850            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2851            if (obj instanceof SharedUserSetting) {
2852                final SharedUserSetting sus = (SharedUserSetting) obj;
2853                return sus.pkgFlags;
2854            } else if (obj instanceof PackageSetting) {
2855                final PackageSetting ps = (PackageSetting) obj;
2856                return ps.pkgFlags;
2857            }
2858        }
2859        return 0;
2860    }
2861
2862    @Override
2863    public String[] getAppOpPermissionPackages(String permissionName) {
2864        synchronized (mPackages) {
2865            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2866            if (pkgs == null) {
2867                return null;
2868            }
2869            return pkgs.toArray(new String[pkgs.size()]);
2870        }
2871    }
2872
2873    @Override
2874    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2875            int flags, int userId) {
2876        if (!sUserManager.exists(userId)) return null;
2877        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2878        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2879        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2880    }
2881
2882    @Override
2883    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2884            IntentFilter filter, int match, ComponentName activity) {
2885        final int userId = UserHandle.getCallingUserId();
2886        if (DEBUG_PREFERRED) {
2887            Log.v(TAG, "setLastChosenActivity intent=" + intent
2888                + " resolvedType=" + resolvedType
2889                + " flags=" + flags
2890                + " filter=" + filter
2891                + " match=" + match
2892                + " activity=" + activity);
2893            filter.dump(new PrintStreamPrinter(System.out), "    ");
2894        }
2895        intent.setComponent(null);
2896        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2897        // Find any earlier preferred or last chosen entries and nuke them
2898        findPreferredActivity(intent, resolvedType,
2899                flags, query, 0, false, true, false, userId);
2900        // Add the new activity as the last chosen for this filter
2901        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2902                "Setting last chosen");
2903    }
2904
2905    @Override
2906    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2907        final int userId = UserHandle.getCallingUserId();
2908        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2909        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2910        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2911                false, false, false, userId);
2912    }
2913
2914    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2915            int flags, List<ResolveInfo> query, int userId) {
2916        if (query != null) {
2917            final int N = query.size();
2918            if (N == 1) {
2919                return query.get(0);
2920            } else if (N > 1) {
2921                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2922                // If there is more than one activity with the same priority,
2923                // then let the user decide between them.
2924                ResolveInfo r0 = query.get(0);
2925                ResolveInfo r1 = query.get(1);
2926                if (DEBUG_INTENT_MATCHING || debug) {
2927                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2928                            + r1.activityInfo.name + "=" + r1.priority);
2929                }
2930                // If the first activity has a higher priority, or a different
2931                // default, then it is always desireable to pick it.
2932                if (r0.priority != r1.priority
2933                        || r0.preferredOrder != r1.preferredOrder
2934                        || r0.isDefault != r1.isDefault) {
2935                    return query.get(0);
2936                }
2937                // If we have saved a preference for a preferred activity for
2938                // this Intent, use that.
2939                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2940                        flags, query, r0.priority, true, false, debug, userId);
2941                if (ri != null) {
2942                    return ri;
2943                }
2944                if (userId != 0) {
2945                    ri = new ResolveInfo(mResolveInfo);
2946                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2947                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2948                            ri.activityInfo.applicationInfo);
2949                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2950                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2951                    return ri;
2952                }
2953                return mResolveInfo;
2954            }
2955        }
2956        return null;
2957    }
2958
2959    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2960            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2961        final int N = query.size();
2962        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2963                .get(userId);
2964        // Get the list of persistent preferred activities that handle the intent
2965        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2966        List<PersistentPreferredActivity> pprefs = ppir != null
2967                ? ppir.queryIntent(intent, resolvedType,
2968                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2969                : null;
2970        if (pprefs != null && pprefs.size() > 0) {
2971            final int M = pprefs.size();
2972            for (int i=0; i<M; i++) {
2973                final PersistentPreferredActivity ppa = pprefs.get(i);
2974                if (DEBUG_PREFERRED || debug) {
2975                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2976                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2977                            + "\n  component=" + ppa.mComponent);
2978                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2979                }
2980                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2981                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2982                if (DEBUG_PREFERRED || debug) {
2983                    Slog.v(TAG, "Found persistent preferred activity:");
2984                    if (ai != null) {
2985                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2986                    } else {
2987                        Slog.v(TAG, "  null");
2988                    }
2989                }
2990                if (ai == null) {
2991                    // This previously registered persistent preferred activity
2992                    // component is no longer known. Ignore it and do NOT remove it.
2993                    continue;
2994                }
2995                for (int j=0; j<N; j++) {
2996                    final ResolveInfo ri = query.get(j);
2997                    if (!ri.activityInfo.applicationInfo.packageName
2998                            .equals(ai.applicationInfo.packageName)) {
2999                        continue;
3000                    }
3001                    if (!ri.activityInfo.name.equals(ai.name)) {
3002                        continue;
3003                    }
3004                    //  Found a persistent preference that can handle the intent.
3005                    if (DEBUG_PREFERRED || debug) {
3006                        Slog.v(TAG, "Returning persistent preferred activity: " +
3007                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3008                    }
3009                    return ri;
3010                }
3011            }
3012        }
3013        return null;
3014    }
3015
3016    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3017            List<ResolveInfo> query, int priority, boolean always,
3018            boolean removeMatches, boolean debug, int userId) {
3019        if (!sUserManager.exists(userId)) return null;
3020        // writer
3021        synchronized (mPackages) {
3022            if (intent.getSelector() != null) {
3023                intent = intent.getSelector();
3024            }
3025            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3026
3027            // Try to find a matching persistent preferred activity.
3028            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3029                    debug, userId);
3030
3031            // If a persistent preferred activity matched, use it.
3032            if (pri != null) {
3033                return pri;
3034            }
3035
3036            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3037            // Get the list of preferred activities that handle the intent
3038            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3039            List<PreferredActivity> prefs = pir != null
3040                    ? pir.queryIntent(intent, resolvedType,
3041                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3042                    : null;
3043            if (prefs != null && prefs.size() > 0) {
3044                boolean changed = false;
3045                try {
3046                    // First figure out how good the original match set is.
3047                    // We will only allow preferred activities that came
3048                    // from the same match quality.
3049                    int match = 0;
3050
3051                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3052
3053                    final int N = query.size();
3054                    for (int j=0; j<N; j++) {
3055                        final ResolveInfo ri = query.get(j);
3056                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3057                                + ": 0x" + Integer.toHexString(match));
3058                        if (ri.match > match) {
3059                            match = ri.match;
3060                        }
3061                    }
3062
3063                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3064                            + Integer.toHexString(match));
3065
3066                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3067                    final int M = prefs.size();
3068                    for (int i=0; i<M; i++) {
3069                        final PreferredActivity pa = prefs.get(i);
3070                        if (DEBUG_PREFERRED || debug) {
3071                            Slog.v(TAG, "Checking PreferredActivity ds="
3072                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3073                                    + "\n  component=" + pa.mPref.mComponent);
3074                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3075                        }
3076                        if (pa.mPref.mMatch != match) {
3077                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3078                                    + Integer.toHexString(pa.mPref.mMatch));
3079                            continue;
3080                        }
3081                        // If it's not an "always" type preferred activity and that's what we're
3082                        // looking for, skip it.
3083                        if (always && !pa.mPref.mAlways) {
3084                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3085                            continue;
3086                        }
3087                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3088                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3089                        if (DEBUG_PREFERRED || debug) {
3090                            Slog.v(TAG, "Found preferred activity:");
3091                            if (ai != null) {
3092                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3093                            } else {
3094                                Slog.v(TAG, "  null");
3095                            }
3096                        }
3097                        if (ai == null) {
3098                            // This previously registered preferred activity
3099                            // component is no longer known.  Most likely an update
3100                            // to the app was installed and in the new version this
3101                            // component no longer exists.  Clean it up by removing
3102                            // it from the preferred activities list, and skip it.
3103                            Slog.w(TAG, "Removing dangling preferred activity: "
3104                                    + pa.mPref.mComponent);
3105                            pir.removeFilter(pa);
3106                            changed = true;
3107                            continue;
3108                        }
3109                        for (int j=0; j<N; j++) {
3110                            final ResolveInfo ri = query.get(j);
3111                            if (!ri.activityInfo.applicationInfo.packageName
3112                                    .equals(ai.applicationInfo.packageName)) {
3113                                continue;
3114                            }
3115                            if (!ri.activityInfo.name.equals(ai.name)) {
3116                                continue;
3117                            }
3118
3119                            if (removeMatches) {
3120                                pir.removeFilter(pa);
3121                                changed = true;
3122                                if (DEBUG_PREFERRED) {
3123                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3124                                }
3125                                break;
3126                            }
3127
3128                            // Okay we found a previously set preferred or last chosen app.
3129                            // If the result set is different from when this
3130                            // was created, we need to clear it and re-ask the
3131                            // user their preference, if we're looking for an "always" type entry.
3132                            if (always && !pa.mPref.sameSet(query, priority)) {
3133                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3134                                        + intent + " type " + resolvedType);
3135                                if (DEBUG_PREFERRED) {
3136                                    Slog.v(TAG, "Removing preferred activity since set changed "
3137                                            + pa.mPref.mComponent);
3138                                }
3139                                pir.removeFilter(pa);
3140                                // Re-add the filter as a "last chosen" entry (!always)
3141                                PreferredActivity lastChosen = new PreferredActivity(
3142                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3143                                pir.addFilter(lastChosen);
3144                                changed = true;
3145                                return null;
3146                            }
3147
3148                            // Yay! Either the set matched or we're looking for the last chosen
3149                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3150                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3151                            return ri;
3152                        }
3153                    }
3154                } finally {
3155                    if (changed) {
3156                        if (DEBUG_PREFERRED) {
3157                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3158                        }
3159                        mSettings.writePackageRestrictionsLPr(userId);
3160                    }
3161                }
3162            }
3163        }
3164        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3165        return null;
3166    }
3167
3168    /*
3169     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3170     */
3171    @Override
3172    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3173            int targetUserId) {
3174        mContext.enforceCallingOrSelfPermission(
3175                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3176        List<CrossProfileIntentFilter> matches =
3177                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3178        if (matches != null) {
3179            int size = matches.size();
3180            for (int i = 0; i < size; i++) {
3181                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3182            }
3183        }
3184        ArrayList<String> packageNames = null;
3185        SparseArray<ArrayList<String>> fromSource =
3186                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3187        if (fromSource != null) {
3188            packageNames = fromSource.get(targetUserId);
3189            if (packageNames != null) {
3190                // We need the package name, so we try to resolve with the loosest flags possible
3191                List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType,
3192                        PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3193                int count = resolveInfos.size();
3194                for (int i = 0; i < count; i++) {
3195                    ResolveInfo resolveInfo = resolveInfos.get(i);
3196                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3197                        return true;
3198                    }
3199                }
3200            }
3201        }
3202        return false;
3203    }
3204
3205    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3206            String resolvedType, int userId) {
3207        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3208        if (resolver != null) {
3209            return resolver.queryIntent(intent, resolvedType, false, userId);
3210        }
3211        return null;
3212    }
3213
3214    @Override
3215    public List<ResolveInfo> queryIntentActivities(Intent intent,
3216            String resolvedType, int flags, int userId) {
3217        if (!sUserManager.exists(userId)) return Collections.emptyList();
3218        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3219        ComponentName comp = intent.getComponent();
3220        if (comp == null) {
3221            if (intent.getSelector() != null) {
3222                intent = intent.getSelector();
3223                comp = intent.getComponent();
3224            }
3225        }
3226
3227        if (comp != null) {
3228            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3229            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3230            if (ai != null) {
3231                final ResolveInfo ri = new ResolveInfo();
3232                ri.activityInfo = ai;
3233                list.add(ri);
3234            }
3235            return list;
3236        }
3237
3238        // reader
3239        synchronized (mPackages) {
3240            final String pkgName = intent.getPackage();
3241            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3242            if (pkgName == null) {
3243                ResolveInfo resolveInfo = null;
3244                if (queryCrossProfile) {
3245                    // Check if the intent needs to be forwarded to another user for this package
3246                    ArrayList<ResolveInfo> crossProfileResult =
3247                            queryIntentActivitiesCrossProfilePackage(
3248                                    intent, resolvedType, flags, userId);
3249                    if (!crossProfileResult.isEmpty()) {
3250                        // Skip the current profile
3251                        return crossProfileResult;
3252                    }
3253                    List<CrossProfileIntentFilter> matchingFilters =
3254                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3255                    // Check for results that need to skip the current profile.
3256                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3257                            resolvedType, flags, userId);
3258                    if (resolveInfo != null) {
3259                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3260                        result.add(resolveInfo);
3261                        return result;
3262                    }
3263                    // Check for cross profile results.
3264                    resolveInfo = queryCrossProfileIntents(
3265                            matchingFilters, intent, resolvedType, flags, userId);
3266                }
3267                // Check for results in the current profile.
3268                List<ResolveInfo> result = mActivities.queryIntent(
3269                        intent, resolvedType, flags, userId);
3270                if (resolveInfo != null) {
3271                    result.add(resolveInfo);
3272                    Collections.sort(result, mResolvePrioritySorter);
3273                }
3274                return result;
3275            }
3276            final PackageParser.Package pkg = mPackages.get(pkgName);
3277            if (pkg != null) {
3278                if (queryCrossProfile) {
3279                    ArrayList<ResolveInfo> crossProfileResult =
3280                            queryIntentActivitiesCrossProfilePackage(
3281                                    intent, resolvedType, flags, userId, pkg, pkgName);
3282                    if (!crossProfileResult.isEmpty()) {
3283                        // Skip the current profile
3284                        return crossProfileResult;
3285                    }
3286                }
3287                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3288                        pkg.activities, userId);
3289            }
3290            return new ArrayList<ResolveInfo>();
3291        }
3292    }
3293
3294    private ResolveInfo querySkipCurrentProfileIntents(
3295            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3296            int flags, int sourceUserId) {
3297        if (matchingFilters != null) {
3298            int size = matchingFilters.size();
3299            for (int i = 0; i < size; i ++) {
3300                CrossProfileIntentFilter filter = matchingFilters.get(i);
3301                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3302                    // Checking if there are activities in the target user that can handle the
3303                    // intent.
3304                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3305                            flags, sourceUserId);
3306                    if (resolveInfo != null) {
3307                        return resolveInfo;
3308                    }
3309                }
3310            }
3311        }
3312        return null;
3313    }
3314
3315    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3316            Intent intent, String resolvedType, int flags, int userId) {
3317        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3318        SparseArray<ArrayList<String>> sourceForwardingInfo =
3319                mSettings.mCrossProfilePackageInfo.get(userId);
3320        if (sourceForwardingInfo != null) {
3321            int NI = sourceForwardingInfo.size();
3322            for (int i = 0; i < NI; i++) {
3323                int targetUserId = sourceForwardingInfo.keyAt(i);
3324                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3325                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3326                        intent, resolvedType, flags, targetUserId);
3327                int NJ = resolveInfos.size();
3328                for (int j = 0; j < NJ; j++) {
3329                    ResolveInfo resolveInfo = resolveInfos.get(j);
3330                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3331                        matchingResolveInfos.add(createForwardingResolveInfo(
3332                                resolveInfo.filter, userId, targetUserId));
3333                    }
3334                }
3335            }
3336        }
3337        return matchingResolveInfos;
3338    }
3339
3340    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3341            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3342            String packageName) {
3343        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3344        SparseArray<ArrayList<String>> sourceForwardingInfo =
3345                mSettings.mCrossProfilePackageInfo.get(userId);
3346        if (sourceForwardingInfo != null) {
3347            int NI = sourceForwardingInfo.size();
3348            for (int i = 0; i < NI; i++) {
3349                int targetUserId = sourceForwardingInfo.keyAt(i);
3350                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3351                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3352                            intent, resolvedType, flags, pkg.activities, targetUserId);
3353                    int NJ = resolveInfos.size();
3354                    for (int j = 0; j < NJ; j++) {
3355                        ResolveInfo resolveInfo = resolveInfos.get(j);
3356                        matchingResolveInfos.add(createForwardingResolveInfo(
3357                                resolveInfo.filter, userId, targetUserId));
3358                    }
3359                }
3360            }
3361        }
3362        return matchingResolveInfos;
3363    }
3364
3365    // Return matching ResolveInfo if any for skip current profile intent filters.
3366    private ResolveInfo queryCrossProfileIntents(
3367            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3368            int flags, int sourceUserId) {
3369        if (matchingFilters != null) {
3370            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3371            // match the same intent. For performance reasons, it is better not to
3372            // run queryIntent twice for the same userId
3373            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3374            int size = matchingFilters.size();
3375            for (int i = 0; i < size; i++) {
3376                CrossProfileIntentFilter filter = matchingFilters.get(i);
3377                int targetUserId = filter.getTargetUserId();
3378                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3379                        && !alreadyTriedUserIds.get(targetUserId)) {
3380                    // Checking if there are activities in the target user that can handle the
3381                    // intent.
3382                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3383                            flags, sourceUserId);
3384                    if (resolveInfo != null) return resolveInfo;
3385                    alreadyTriedUserIds.put(targetUserId, true);
3386                }
3387            }
3388        }
3389        return null;
3390    }
3391
3392    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3393            String resolvedType, int flags, int sourceUserId) {
3394        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3395                resolvedType, flags, filter.getTargetUserId());
3396        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3397            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3398        }
3399        return null;
3400    }
3401
3402    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3403            int sourceUserId, int targetUserId) {
3404        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3405        String className;
3406        if (targetUserId == UserHandle.USER_OWNER) {
3407            className = FORWARD_INTENT_TO_USER_OWNER;
3408        } else {
3409            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3410        }
3411        ComponentName forwardingActivityComponentName = new ComponentName(
3412                mAndroidApplication.packageName, className);
3413        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3414                sourceUserId);
3415        if (targetUserId == UserHandle.USER_OWNER) {
3416            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3417            forwardingResolveInfo.noResourceId = true;
3418        }
3419        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3420        forwardingResolveInfo.priority = 0;
3421        forwardingResolveInfo.preferredOrder = 0;
3422        forwardingResolveInfo.match = 0;
3423        forwardingResolveInfo.isDefault = true;
3424        forwardingResolveInfo.filter = filter;
3425        forwardingResolveInfo.targetUserId = targetUserId;
3426        return forwardingResolveInfo;
3427    }
3428
3429    @Override
3430    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3431            Intent[] specifics, String[] specificTypes, Intent intent,
3432            String resolvedType, int flags, int userId) {
3433        if (!sUserManager.exists(userId)) return Collections.emptyList();
3434        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3435                "query intent activity options");
3436        final String resultsAction = intent.getAction();
3437
3438        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3439                | PackageManager.GET_RESOLVED_FILTER, userId);
3440
3441        if (DEBUG_INTENT_MATCHING) {
3442            Log.v(TAG, "Query " + intent + ": " + results);
3443        }
3444
3445        int specificsPos = 0;
3446        int N;
3447
3448        // todo: note that the algorithm used here is O(N^2).  This
3449        // isn't a problem in our current environment, but if we start running
3450        // into situations where we have more than 5 or 10 matches then this
3451        // should probably be changed to something smarter...
3452
3453        // First we go through and resolve each of the specific items
3454        // that were supplied, taking care of removing any corresponding
3455        // duplicate items in the generic resolve list.
3456        if (specifics != null) {
3457            for (int i=0; i<specifics.length; i++) {
3458                final Intent sintent = specifics[i];
3459                if (sintent == null) {
3460                    continue;
3461                }
3462
3463                if (DEBUG_INTENT_MATCHING) {
3464                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3465                }
3466
3467                String action = sintent.getAction();
3468                if (resultsAction != null && resultsAction.equals(action)) {
3469                    // If this action was explicitly requested, then don't
3470                    // remove things that have it.
3471                    action = null;
3472                }
3473
3474                ResolveInfo ri = null;
3475                ActivityInfo ai = null;
3476
3477                ComponentName comp = sintent.getComponent();
3478                if (comp == null) {
3479                    ri = resolveIntent(
3480                        sintent,
3481                        specificTypes != null ? specificTypes[i] : null,
3482                            flags, userId);
3483                    if (ri == null) {
3484                        continue;
3485                    }
3486                    if (ri == mResolveInfo) {
3487                        // ACK!  Must do something better with this.
3488                    }
3489                    ai = ri.activityInfo;
3490                    comp = new ComponentName(ai.applicationInfo.packageName,
3491                            ai.name);
3492                } else {
3493                    ai = getActivityInfo(comp, flags, userId);
3494                    if (ai == null) {
3495                        continue;
3496                    }
3497                }
3498
3499                // Look for any generic query activities that are duplicates
3500                // of this specific one, and remove them from the results.
3501                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3502                N = results.size();
3503                int j;
3504                for (j=specificsPos; j<N; j++) {
3505                    ResolveInfo sri = results.get(j);
3506                    if ((sri.activityInfo.name.equals(comp.getClassName())
3507                            && sri.activityInfo.applicationInfo.packageName.equals(
3508                                    comp.getPackageName()))
3509                        || (action != null && sri.filter.matchAction(action))) {
3510                        results.remove(j);
3511                        if (DEBUG_INTENT_MATCHING) Log.v(
3512                            TAG, "Removing duplicate item from " + j
3513                            + " due to specific " + specificsPos);
3514                        if (ri == null) {
3515                            ri = sri;
3516                        }
3517                        j--;
3518                        N--;
3519                    }
3520                }
3521
3522                // Add this specific item to its proper place.
3523                if (ri == null) {
3524                    ri = new ResolveInfo();
3525                    ri.activityInfo = ai;
3526                }
3527                results.add(specificsPos, ri);
3528                ri.specificIndex = i;
3529                specificsPos++;
3530            }
3531        }
3532
3533        // Now we go through the remaining generic results and remove any
3534        // duplicate actions that are found here.
3535        N = results.size();
3536        for (int i=specificsPos; i<N-1; i++) {
3537            final ResolveInfo rii = results.get(i);
3538            if (rii.filter == null) {
3539                continue;
3540            }
3541
3542            // Iterate over all of the actions of this result's intent
3543            // filter...  typically this should be just one.
3544            final Iterator<String> it = rii.filter.actionsIterator();
3545            if (it == null) {
3546                continue;
3547            }
3548            while (it.hasNext()) {
3549                final String action = it.next();
3550                if (resultsAction != null && resultsAction.equals(action)) {
3551                    // If this action was explicitly requested, then don't
3552                    // remove things that have it.
3553                    continue;
3554                }
3555                for (int j=i+1; j<N; j++) {
3556                    final ResolveInfo rij = results.get(j);
3557                    if (rij.filter != null && rij.filter.hasAction(action)) {
3558                        results.remove(j);
3559                        if (DEBUG_INTENT_MATCHING) Log.v(
3560                            TAG, "Removing duplicate item from " + j
3561                            + " due to action " + action + " at " + i);
3562                        j--;
3563                        N--;
3564                    }
3565                }
3566            }
3567
3568            // If the caller didn't request filter information, drop it now
3569            // so we don't have to marshall/unmarshall it.
3570            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3571                rii.filter = null;
3572            }
3573        }
3574
3575        // Filter out the caller activity if so requested.
3576        if (caller != null) {
3577            N = results.size();
3578            for (int i=0; i<N; i++) {
3579                ActivityInfo ainfo = results.get(i).activityInfo;
3580                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3581                        && caller.getClassName().equals(ainfo.name)) {
3582                    results.remove(i);
3583                    break;
3584                }
3585            }
3586        }
3587
3588        // If the caller didn't request filter information,
3589        // drop them now so we don't have to
3590        // marshall/unmarshall it.
3591        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3592            N = results.size();
3593            for (int i=0; i<N; i++) {
3594                results.get(i).filter = null;
3595            }
3596        }
3597
3598        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3599        return results;
3600    }
3601
3602    @Override
3603    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3604            int userId) {
3605        if (!sUserManager.exists(userId)) return Collections.emptyList();
3606        ComponentName comp = intent.getComponent();
3607        if (comp == null) {
3608            if (intent.getSelector() != null) {
3609                intent = intent.getSelector();
3610                comp = intent.getComponent();
3611            }
3612        }
3613        if (comp != null) {
3614            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3615            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3616            if (ai != null) {
3617                ResolveInfo ri = new ResolveInfo();
3618                ri.activityInfo = ai;
3619                list.add(ri);
3620            }
3621            return list;
3622        }
3623
3624        // reader
3625        synchronized (mPackages) {
3626            String pkgName = intent.getPackage();
3627            if (pkgName == null) {
3628                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3629            }
3630            final PackageParser.Package pkg = mPackages.get(pkgName);
3631            if (pkg != null) {
3632                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3633                        userId);
3634            }
3635            return null;
3636        }
3637    }
3638
3639    @Override
3640    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3641        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3642        if (!sUserManager.exists(userId)) return null;
3643        if (query != null) {
3644            if (query.size() >= 1) {
3645                // If there is more than one service with the same priority,
3646                // just arbitrarily pick the first one.
3647                return query.get(0);
3648            }
3649        }
3650        return null;
3651    }
3652
3653    @Override
3654    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3655            int userId) {
3656        if (!sUserManager.exists(userId)) return Collections.emptyList();
3657        ComponentName comp = intent.getComponent();
3658        if (comp == null) {
3659            if (intent.getSelector() != null) {
3660                intent = intent.getSelector();
3661                comp = intent.getComponent();
3662            }
3663        }
3664        if (comp != null) {
3665            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3666            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3667            if (si != null) {
3668                final ResolveInfo ri = new ResolveInfo();
3669                ri.serviceInfo = si;
3670                list.add(ri);
3671            }
3672            return list;
3673        }
3674
3675        // reader
3676        synchronized (mPackages) {
3677            String pkgName = intent.getPackage();
3678            if (pkgName == null) {
3679                return mServices.queryIntent(intent, resolvedType, flags, userId);
3680            }
3681            final PackageParser.Package pkg = mPackages.get(pkgName);
3682            if (pkg != null) {
3683                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3684                        userId);
3685            }
3686            return null;
3687        }
3688    }
3689
3690    @Override
3691    public List<ResolveInfo> queryIntentContentProviders(
3692            Intent intent, String resolvedType, int flags, int userId) {
3693        if (!sUserManager.exists(userId)) return Collections.emptyList();
3694        ComponentName comp = intent.getComponent();
3695        if (comp == null) {
3696            if (intent.getSelector() != null) {
3697                intent = intent.getSelector();
3698                comp = intent.getComponent();
3699            }
3700        }
3701        if (comp != null) {
3702            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3703            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3704            if (pi != null) {
3705                final ResolveInfo ri = new ResolveInfo();
3706                ri.providerInfo = pi;
3707                list.add(ri);
3708            }
3709            return list;
3710        }
3711
3712        // reader
3713        synchronized (mPackages) {
3714            String pkgName = intent.getPackage();
3715            if (pkgName == null) {
3716                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3717            }
3718            final PackageParser.Package pkg = mPackages.get(pkgName);
3719            if (pkg != null) {
3720                return mProviders.queryIntentForPackage(
3721                        intent, resolvedType, flags, pkg.providers, userId);
3722            }
3723            return null;
3724        }
3725    }
3726
3727    @Override
3728    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3729        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3730
3731        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3732
3733        // writer
3734        synchronized (mPackages) {
3735            ArrayList<PackageInfo> list;
3736            if (listUninstalled) {
3737                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3738                for (PackageSetting ps : mSettings.mPackages.values()) {
3739                    PackageInfo pi;
3740                    if (ps.pkg != null) {
3741                        pi = generatePackageInfo(ps.pkg, flags, userId);
3742                    } else {
3743                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3744                    }
3745                    if (pi != null) {
3746                        list.add(pi);
3747                    }
3748                }
3749            } else {
3750                list = new ArrayList<PackageInfo>(mPackages.size());
3751                for (PackageParser.Package p : mPackages.values()) {
3752                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3753                    if (pi != null) {
3754                        list.add(pi);
3755                    }
3756                }
3757            }
3758
3759            return new ParceledListSlice<PackageInfo>(list);
3760        }
3761    }
3762
3763    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3764            String[] permissions, boolean[] tmp, int flags, int userId) {
3765        int numMatch = 0;
3766        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3767        for (int i=0; i<permissions.length; i++) {
3768            if (gp.grantedPermissions.contains(permissions[i])) {
3769                tmp[i] = true;
3770                numMatch++;
3771            } else {
3772                tmp[i] = false;
3773            }
3774        }
3775        if (numMatch == 0) {
3776            return;
3777        }
3778        PackageInfo pi;
3779        if (ps.pkg != null) {
3780            pi = generatePackageInfo(ps.pkg, flags, userId);
3781        } else {
3782            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3783        }
3784        // The above might return null in cases of uninstalled apps or install-state
3785        // skew across users/profiles.
3786        if (pi != null) {
3787            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3788                if (numMatch == permissions.length) {
3789                    pi.requestedPermissions = permissions;
3790                } else {
3791                    pi.requestedPermissions = new String[numMatch];
3792                    numMatch = 0;
3793                    for (int i=0; i<permissions.length; i++) {
3794                        if (tmp[i]) {
3795                            pi.requestedPermissions[numMatch] = permissions[i];
3796                            numMatch++;
3797                        }
3798                    }
3799                }
3800            }
3801            list.add(pi);
3802        }
3803    }
3804
3805    @Override
3806    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3807            String[] permissions, int flags, int userId) {
3808        if (!sUserManager.exists(userId)) return null;
3809        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3810
3811        // writer
3812        synchronized (mPackages) {
3813            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3814            boolean[] tmpBools = new boolean[permissions.length];
3815            if (listUninstalled) {
3816                for (PackageSetting ps : mSettings.mPackages.values()) {
3817                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3818                }
3819            } else {
3820                for (PackageParser.Package pkg : mPackages.values()) {
3821                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3822                    if (ps != null) {
3823                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3824                                userId);
3825                    }
3826                }
3827            }
3828
3829            return new ParceledListSlice<PackageInfo>(list);
3830        }
3831    }
3832
3833    @Override
3834    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3835        if (!sUserManager.exists(userId)) return null;
3836        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3837
3838        // writer
3839        synchronized (mPackages) {
3840            ArrayList<ApplicationInfo> list;
3841            if (listUninstalled) {
3842                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3843                for (PackageSetting ps : mSettings.mPackages.values()) {
3844                    ApplicationInfo ai;
3845                    if (ps.pkg != null) {
3846                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3847                                ps.readUserState(userId), userId);
3848                    } else {
3849                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3850                    }
3851                    if (ai != null) {
3852                        list.add(ai);
3853                    }
3854                }
3855            } else {
3856                list = new ArrayList<ApplicationInfo>(mPackages.size());
3857                for (PackageParser.Package p : mPackages.values()) {
3858                    if (p.mExtras != null) {
3859                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3860                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3861                        if (ai != null) {
3862                            list.add(ai);
3863                        }
3864                    }
3865                }
3866            }
3867
3868            return new ParceledListSlice<ApplicationInfo>(list);
3869        }
3870    }
3871
3872    public List<ApplicationInfo> getPersistentApplications(int flags) {
3873        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3874
3875        // reader
3876        synchronized (mPackages) {
3877            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3878            final int userId = UserHandle.getCallingUserId();
3879            while (i.hasNext()) {
3880                final PackageParser.Package p = i.next();
3881                if (p.applicationInfo != null
3882                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3883                        && (!mSafeMode || isSystemApp(p))) {
3884                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3885                    if (ps != null) {
3886                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3887                                ps.readUserState(userId), userId);
3888                        if (ai != null) {
3889                            finalList.add(ai);
3890                        }
3891                    }
3892                }
3893            }
3894        }
3895
3896        return finalList;
3897    }
3898
3899    @Override
3900    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3901        if (!sUserManager.exists(userId)) return null;
3902        // reader
3903        synchronized (mPackages) {
3904            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3905            PackageSetting ps = provider != null
3906                    ? mSettings.mPackages.get(provider.owner.packageName)
3907                    : null;
3908            return ps != null
3909                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3910                    && (!mSafeMode || (provider.info.applicationInfo.flags
3911                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3912                    ? PackageParser.generateProviderInfo(provider, flags,
3913                            ps.readUserState(userId), userId)
3914                    : null;
3915        }
3916    }
3917
3918    /**
3919     * @deprecated
3920     */
3921    @Deprecated
3922    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3923        // reader
3924        synchronized (mPackages) {
3925            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3926                    .entrySet().iterator();
3927            final int userId = UserHandle.getCallingUserId();
3928            while (i.hasNext()) {
3929                Map.Entry<String, PackageParser.Provider> entry = i.next();
3930                PackageParser.Provider p = entry.getValue();
3931                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3932
3933                if (ps != null && p.syncable
3934                        && (!mSafeMode || (p.info.applicationInfo.flags
3935                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3936                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3937                            ps.readUserState(userId), userId);
3938                    if (info != null) {
3939                        outNames.add(entry.getKey());
3940                        outInfo.add(info);
3941                    }
3942                }
3943            }
3944        }
3945    }
3946
3947    @Override
3948    public List<ProviderInfo> queryContentProviders(String processName,
3949            int uid, int flags) {
3950        ArrayList<ProviderInfo> finalList = null;
3951        // reader
3952        synchronized (mPackages) {
3953            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3954            final int userId = processName != null ?
3955                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3956            while (i.hasNext()) {
3957                final PackageParser.Provider p = i.next();
3958                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3959                if (ps != null && p.info.authority != null
3960                        && (processName == null
3961                                || (p.info.processName.equals(processName)
3962                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3963                        && mSettings.isEnabledLPr(p.info, flags, userId)
3964                        && (!mSafeMode
3965                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3966                    if (finalList == null) {
3967                        finalList = new ArrayList<ProviderInfo>(3);
3968                    }
3969                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3970                            ps.readUserState(userId), userId);
3971                    if (info != null) {
3972                        finalList.add(info);
3973                    }
3974                }
3975            }
3976        }
3977
3978        if (finalList != null) {
3979            Collections.sort(finalList, mProviderInitOrderSorter);
3980        }
3981
3982        return finalList;
3983    }
3984
3985    @Override
3986    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3987            int flags) {
3988        // reader
3989        synchronized (mPackages) {
3990            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3991            return PackageParser.generateInstrumentationInfo(i, flags);
3992        }
3993    }
3994
3995    @Override
3996    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3997            int flags) {
3998        ArrayList<InstrumentationInfo> finalList =
3999            new ArrayList<InstrumentationInfo>();
4000
4001        // reader
4002        synchronized (mPackages) {
4003            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4004            while (i.hasNext()) {
4005                final PackageParser.Instrumentation p = i.next();
4006                if (targetPackage == null
4007                        || targetPackage.equals(p.info.targetPackage)) {
4008                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4009                            flags);
4010                    if (ii != null) {
4011                        finalList.add(ii);
4012                    }
4013                }
4014            }
4015        }
4016
4017        return finalList;
4018    }
4019
4020    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4021        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4022        if (overlays == null) {
4023            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4024            return;
4025        }
4026        for (PackageParser.Package opkg : overlays.values()) {
4027            // Not much to do if idmap fails: we already logged the error
4028            // and we certainly don't want to abort installation of pkg simply
4029            // because an overlay didn't fit properly. For these reasons,
4030            // ignore the return value of createIdmapForPackagePairLI.
4031            createIdmapForPackagePairLI(pkg, opkg);
4032        }
4033    }
4034
4035    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4036            PackageParser.Package opkg) {
4037        if (!opkg.mTrustedOverlay) {
4038            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4039                    opkg.baseCodePath + ": overlay not trusted");
4040            return false;
4041        }
4042        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4043        if (overlaySet == null) {
4044            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4045                    opkg.baseCodePath + " but target package has no known overlays");
4046            return false;
4047        }
4048        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4049        // TODO: generate idmap for split APKs
4050        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4051            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4052                    + opkg.baseCodePath);
4053            return false;
4054        }
4055        PackageParser.Package[] overlayArray =
4056            overlaySet.values().toArray(new PackageParser.Package[0]);
4057        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4058            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4059                return p1.mOverlayPriority - p2.mOverlayPriority;
4060            }
4061        };
4062        Arrays.sort(overlayArray, cmp);
4063
4064        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4065        int i = 0;
4066        for (PackageParser.Package p : overlayArray) {
4067            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4068        }
4069        return true;
4070    }
4071
4072    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4073        final File[] files = dir.listFiles();
4074        if (ArrayUtils.isEmpty(files)) {
4075            Log.d(TAG, "No files in app dir " + dir);
4076            return;
4077        }
4078
4079        if (DEBUG_PACKAGE_SCANNING) {
4080            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4081                    + " flags=0x" + Integer.toHexString(parseFlags));
4082        }
4083
4084        for (File file : files) {
4085            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4086                    && !PackageInstallerService.isStageName(file.getName());
4087            if (!isPackage) {
4088                // Ignore entries which are not packages
4089                continue;
4090            }
4091            try {
4092                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4093                        scanFlags, currentTime, null);
4094            } catch (PackageManagerException e) {
4095                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4096
4097                // Delete invalid userdata apps
4098                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4099                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4100                    Slog.w(TAG, "Deleting invalid package at " + file);
4101                    if (file.isDirectory()) {
4102                        FileUtils.deleteContents(file);
4103                    }
4104                    file.delete();
4105                }
4106            }
4107        }
4108    }
4109
4110    private static File getSettingsProblemFile() {
4111        File dataDir = Environment.getDataDirectory();
4112        File systemDir = new File(dataDir, "system");
4113        File fname = new File(systemDir, "uiderrors.txt");
4114        return fname;
4115    }
4116
4117    static void reportSettingsProblem(int priority, String msg) {
4118        try {
4119            File fname = getSettingsProblemFile();
4120            FileOutputStream out = new FileOutputStream(fname, true);
4121            PrintWriter pw = new FastPrintWriter(out);
4122            SimpleDateFormat formatter = new SimpleDateFormat();
4123            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4124            pw.println(dateString + ": " + msg);
4125            pw.close();
4126            FileUtils.setPermissions(
4127                    fname.toString(),
4128                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4129                    -1, -1);
4130        } catch (java.io.IOException e) {
4131        }
4132        Slog.println(priority, TAG, msg);
4133    }
4134
4135    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4136            PackageParser.Package pkg, File srcFile, int parseFlags)
4137            throws PackageManagerException {
4138        if (ps != null
4139                && ps.codePath.equals(srcFile)
4140                && ps.timeStamp == srcFile.lastModified()
4141                && !isCompatSignatureUpdateNeeded(pkg)) {
4142            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4143            if (ps.signatures.mSignatures != null
4144                    && ps.signatures.mSignatures.length != 0
4145                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4146                // Optimization: reuse the existing cached certificates
4147                // if the package appears to be unchanged.
4148                pkg.mSignatures = ps.signatures.mSignatures;
4149                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4150                synchronized (mPackages) {
4151                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4152                }
4153                return;
4154            }
4155
4156            Slog.w(TAG, "PackageSetting for " + ps.name
4157                    + " is missing signatures.  Collecting certs again to recover them.");
4158        } else {
4159            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4160        }
4161
4162        try {
4163            pp.collectCertificates(pkg, parseFlags);
4164            pp.collectManifestDigest(pkg);
4165        } catch (PackageParserException e) {
4166            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4167                    + pkg.packageName + ": " + e.getMessage());
4168        }
4169    }
4170
4171    /*
4172     *  Scan a package and return the newly parsed package.
4173     *  Returns null in case of errors and the error code is stored in mLastScanError
4174     */
4175    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4176            long currentTime, UserHandle user) throws PackageManagerException {
4177        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4178        parseFlags |= mDefParseFlags;
4179        PackageParser pp = new PackageParser();
4180        pp.setSeparateProcesses(mSeparateProcesses);
4181        pp.setOnlyCoreApps(mOnlyCore);
4182        pp.setDisplayMetrics(mMetrics);
4183
4184        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4185            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4186        }
4187
4188        final PackageParser.Package pkg;
4189        try {
4190            pkg = pp.parsePackage(scanFile, parseFlags);
4191        } catch (PackageParserException e) {
4192            throw new PackageManagerException(e.error,
4193                    "Failed to scan " + scanFile + ": " + e.getMessage());
4194        }
4195
4196        PackageSetting ps = null;
4197        PackageSetting updatedPkg;
4198        // reader
4199        synchronized (mPackages) {
4200            // Look to see if we already know about this package.
4201            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4202            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4203                // This package has been renamed to its original name.  Let's
4204                // use that.
4205                ps = mSettings.peekPackageLPr(oldName);
4206            }
4207            // If there was no original package, see one for the real package name.
4208            if (ps == null) {
4209                ps = mSettings.peekPackageLPr(pkg.packageName);
4210            }
4211            // Check to see if this package could be hiding/updating a system
4212            // package.  Must look for it either under the original or real
4213            // package name depending on our state.
4214            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4215            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4216        }
4217        boolean updatedPkgBetter = false;
4218        // First check if this is a system package that may involve an update
4219        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4220            if (ps != null && !ps.codePath.equals(scanFile)) {
4221                // The path has changed from what was last scanned...  check the
4222                // version of the new path against what we have stored to determine
4223                // what to do.
4224                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4225                if (pkg.mVersionCode < ps.versionCode) {
4226                    // The system package has been updated and the code path does not match
4227                    // Ignore entry. Skip it.
4228                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4229                            + " ignored: updated version " + ps.versionCode
4230                            + " better than this " + pkg.mVersionCode);
4231                    if (!updatedPkg.codePath.equals(scanFile)) {
4232                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4233                                + ps.name + " changing from " + updatedPkg.codePathString
4234                                + " to " + scanFile);
4235                        updatedPkg.codePath = scanFile;
4236                        updatedPkg.codePathString = scanFile.toString();
4237                        // This is the point at which we know that the system-disk APK
4238                        // for this package has moved during a reboot (e.g. due to an OTA),
4239                        // so we need to reevaluate it for privilege policy.
4240                        if (locationIsPrivileged(scanFile)) {
4241                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4242                        }
4243                    }
4244                    updatedPkg.pkg = pkg;
4245                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4246                } else {
4247                    // The current app on the system partition is better than
4248                    // what we have updated to on the data partition; switch
4249                    // back to the system partition version.
4250                    // At this point, its safely assumed that package installation for
4251                    // apps in system partition will go through. If not there won't be a working
4252                    // version of the app
4253                    // writer
4254                    synchronized (mPackages) {
4255                        // Just remove the loaded entries from package lists.
4256                        mPackages.remove(ps.name);
4257                    }
4258                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4259                            + "reverting from " + ps.codePathString
4260                            + ": new version " + pkg.mVersionCode
4261                            + " better than installed " + ps.versionCode);
4262
4263                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4264                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4265                            getAppDexInstructionSets(ps));
4266                    synchronized (mInstallLock) {
4267                        args.cleanUpResourcesLI();
4268                    }
4269                    synchronized (mPackages) {
4270                        mSettings.enableSystemPackageLPw(ps.name);
4271                    }
4272                    updatedPkgBetter = true;
4273                }
4274            }
4275        }
4276
4277        if (updatedPkg != null) {
4278            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4279            // initially
4280            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4281
4282            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4283            // flag set initially
4284            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4285                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4286            }
4287        }
4288
4289        // Verify certificates against what was last scanned
4290        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4291
4292        /*
4293         * A new system app appeared, but we already had a non-system one of the
4294         * same name installed earlier.
4295         */
4296        boolean shouldHideSystemApp = false;
4297        if (updatedPkg == null && ps != null
4298                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4299            /*
4300             * Check to make sure the signatures match first. If they don't,
4301             * wipe the installed application and its data.
4302             */
4303            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4304                    != PackageManager.SIGNATURE_MATCH) {
4305                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4306                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4307                ps = null;
4308            } else {
4309                /*
4310                 * If the newly-added system app is an older version than the
4311                 * already installed version, hide it. It will be scanned later
4312                 * and re-added like an update.
4313                 */
4314                if (pkg.mVersionCode < ps.versionCode) {
4315                    shouldHideSystemApp = true;
4316                } else {
4317                    /*
4318                     * The newly found system app is a newer version that the
4319                     * one previously installed. Simply remove the
4320                     * already-installed application and replace it with our own
4321                     * while keeping the application data.
4322                     */
4323                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4324                            + ps.codePathString + ": new version " + pkg.mVersionCode
4325                            + " better than installed " + ps.versionCode);
4326                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4327                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4328                            getAppDexInstructionSets(ps));
4329                    synchronized (mInstallLock) {
4330                        args.cleanUpResourcesLI();
4331                    }
4332                }
4333            }
4334        }
4335
4336        // The apk is forward locked (not public) if its code and resources
4337        // are kept in different files. (except for app in either system or
4338        // vendor path).
4339        // TODO grab this value from PackageSettings
4340        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4341            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4342                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4343            }
4344        }
4345
4346        // TODO: extend to support forward-locked splits
4347        String resourcePath = null;
4348        String baseResourcePath = null;
4349        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4350            if (ps != null && ps.resourcePathString != null) {
4351                resourcePath = ps.resourcePathString;
4352                baseResourcePath = ps.resourcePathString;
4353            } else {
4354                // Should not happen at all. Just log an error.
4355                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4356            }
4357        } else {
4358            resourcePath = pkg.codePath;
4359            baseResourcePath = pkg.baseCodePath;
4360        }
4361
4362        // Set application objects path explicitly.
4363        pkg.applicationInfo.setCodePath(pkg.codePath);
4364        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4365        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4366        pkg.applicationInfo.setResourcePath(resourcePath);
4367        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4368        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4369
4370        // Note that we invoke the following method only if we are about to unpack an application
4371        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4372                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4373
4374        /*
4375         * If the system app should be overridden by a previously installed
4376         * data, hide the system app now and let the /data/app scan pick it up
4377         * again.
4378         */
4379        if (shouldHideSystemApp) {
4380            synchronized (mPackages) {
4381                /*
4382                 * We have to grant systems permissions before we hide, because
4383                 * grantPermissions will assume the package update is trying to
4384                 * expand its permissions.
4385                 */
4386                grantPermissionsLPw(pkg, true);
4387                mSettings.disableSystemPackageLPw(pkg.packageName);
4388            }
4389        }
4390
4391        return scannedPkg;
4392    }
4393
4394    private static String fixProcessName(String defProcessName,
4395            String processName, int uid) {
4396        if (processName == null) {
4397            return defProcessName;
4398        }
4399        return processName;
4400    }
4401
4402    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4403            throws PackageManagerException {
4404        if (pkgSetting.signatures.mSignatures != null) {
4405            // Already existing package. Make sure signatures match
4406            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4407                    == PackageManager.SIGNATURE_MATCH;
4408            if (!match) {
4409                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4410                        == PackageManager.SIGNATURE_MATCH;
4411            }
4412            if (!match) {
4413                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4414                        + pkg.packageName + " signatures do not match the "
4415                        + "previously installed version; ignoring!");
4416            }
4417        }
4418
4419        // Check for shared user signatures
4420        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4421            // Already existing package. Make sure signatures match
4422            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4423                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4424            if (!match) {
4425                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4426                        == PackageManager.SIGNATURE_MATCH;
4427            }
4428            if (!match) {
4429                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4430                        "Package " + pkg.packageName
4431                        + " has no signatures that match those in shared user "
4432                        + pkgSetting.sharedUser.name + "; ignoring!");
4433            }
4434        }
4435    }
4436
4437    /**
4438     * Enforces that only the system UID or root's UID can call a method exposed
4439     * via Binder.
4440     *
4441     * @param message used as message if SecurityException is thrown
4442     * @throws SecurityException if the caller is not system or root
4443     */
4444    private static final void enforceSystemOrRoot(String message) {
4445        final int uid = Binder.getCallingUid();
4446        if (uid != Process.SYSTEM_UID && uid != 0) {
4447            throw new SecurityException(message);
4448        }
4449    }
4450
4451    @Override
4452    public void performBootDexOpt() {
4453        enforceSystemOrRoot("Only the system can request dexopt be performed");
4454
4455        final HashSet<PackageParser.Package> pkgs;
4456        synchronized (mPackages) {
4457            pkgs = mDeferredDexOpt;
4458            mDeferredDexOpt = null;
4459        }
4460
4461        if (pkgs != null) {
4462            // Filter out packages that aren't recently used.
4463            //
4464            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4465            // should do a full dexopt.
4466            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4467                // TODO: add a property to control this?
4468                long dexOptLRUThresholdInMinutes;
4469                if (mLazyDexOpt) {
4470                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4471                } else {
4472                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4473                }
4474                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4475
4476                int total = pkgs.size();
4477                int skipped = 0;
4478                long now = System.currentTimeMillis();
4479                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4480                    PackageParser.Package pkg = i.next();
4481                    long then = pkg.mLastPackageUsageTimeInMills;
4482                    if (then + dexOptLRUThresholdInMills < now) {
4483                        if (DEBUG_DEXOPT) {
4484                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4485                                  ((then == 0) ? "never" : new Date(then)));
4486                        }
4487                        i.remove();
4488                        skipped++;
4489                    }
4490                }
4491                if (DEBUG_DEXOPT) {
4492                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4493                }
4494            }
4495
4496            int i = 0;
4497            for (PackageParser.Package pkg : pkgs) {
4498                i++;
4499                if (DEBUG_DEXOPT) {
4500                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4501                          + ": " + pkg.packageName);
4502                }
4503                if (!isFirstBoot()) {
4504                    try {
4505                        ActivityManagerNative.getDefault().showBootMessage(
4506                                mContext.getResources().getString(
4507                                        R.string.android_upgrading_apk,
4508                                        i, pkgs.size()), true);
4509                    } catch (RemoteException e) {
4510                    }
4511                }
4512                PackageParser.Package p = pkg;
4513                synchronized (mInstallLock) {
4514                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4515                            true /* include dependencies */);
4516                }
4517            }
4518        }
4519    }
4520
4521    @Override
4522    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4523        return performDexOpt(packageName, instructionSet, false);
4524    }
4525
4526    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4527        if (info.primaryCpuAbi == null) {
4528            return getPreferredInstructionSet();
4529        }
4530
4531        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4532    }
4533
4534    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4535        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4536        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4537        if (!dexopt && !updateUsage) {
4538            // We aren't going to dexopt or update usage, so bail early.
4539            return false;
4540        }
4541        PackageParser.Package p;
4542        final String targetInstructionSet;
4543        synchronized (mPackages) {
4544            p = mPackages.get(packageName);
4545            if (p == null) {
4546                return false;
4547            }
4548            if (updateUsage) {
4549                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4550            }
4551            mPackageUsage.write(false);
4552            if (!dexopt) {
4553                // We aren't going to dexopt, so bail early.
4554                return false;
4555            }
4556
4557            targetInstructionSet = instructionSet != null ? instructionSet :
4558                    getPrimaryInstructionSet(p.applicationInfo);
4559            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4560                return false;
4561            }
4562        }
4563
4564        synchronized (mInstallLock) {
4565            final String[] instructionSets = new String[] { targetInstructionSet };
4566            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4567                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4568        }
4569    }
4570
4571    public HashSet<String> getPackagesThatNeedDexOpt() {
4572        HashSet<String> pkgs = null;
4573        synchronized (mPackages) {
4574            for (PackageParser.Package p : mPackages.values()) {
4575                if (DEBUG_DEXOPT) {
4576                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4577                }
4578                if (!p.mDexOptPerformed.isEmpty()) {
4579                    continue;
4580                }
4581                if (pkgs == null) {
4582                    pkgs = new HashSet<String>();
4583                }
4584                pkgs.add(p.packageName);
4585            }
4586        }
4587        return pkgs;
4588    }
4589
4590    public void shutdown() {
4591        mPackageUsage.write(true);
4592    }
4593
4594    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4595             boolean forceDex, boolean defer, HashSet<String> done) {
4596        for (int i=0; i<libs.size(); i++) {
4597            PackageParser.Package libPkg;
4598            String libName;
4599            synchronized (mPackages) {
4600                libName = libs.get(i);
4601                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4602                if (lib != null && lib.apk != null) {
4603                    libPkg = mPackages.get(lib.apk);
4604                } else {
4605                    libPkg = null;
4606                }
4607            }
4608            if (libPkg != null && !done.contains(libName)) {
4609                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4610            }
4611        }
4612    }
4613
4614    static final int DEX_OPT_SKIPPED = 0;
4615    static final int DEX_OPT_PERFORMED = 1;
4616    static final int DEX_OPT_DEFERRED = 2;
4617    static final int DEX_OPT_FAILED = -1;
4618
4619    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4620            boolean forceDex, boolean defer, HashSet<String> done) {
4621        final String[] instructionSets = targetInstructionSets != null ?
4622                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4623
4624        if (done != null) {
4625            done.add(pkg.packageName);
4626            if (pkg.usesLibraries != null) {
4627                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4628            }
4629            if (pkg.usesOptionalLibraries != null) {
4630                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4631            }
4632        }
4633
4634        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4635            return DEX_OPT_SKIPPED;
4636        }
4637
4638        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4639
4640        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4641        boolean performedDexOpt = false;
4642        // There are three basic cases here:
4643        // 1.) we need to dexopt, either because we are forced or it is needed
4644        // 2.) we are defering a needed dexopt
4645        // 3.) we are skipping an unneeded dexopt
4646        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4647        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4648            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4649                continue;
4650            }
4651
4652            for (String path : paths) {
4653                try {
4654                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4655                    // patckage or the one we find does not match the image checksum (i.e. it was
4656                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4657                    // odex file and it matches the checksum of the image but not its base address,
4658                    // meaning we need to move it.
4659                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4660                            pkg.packageName, dexCodeInstructionSet, defer);
4661                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4662                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4663                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4664                                + " vmSafeMode=" + vmSafeMode);
4665                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4666                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4667                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4668
4669                        if (ret < 0) {
4670                            // Don't bother running dexopt again if we failed, it will probably
4671                            // just result in an error again. Also, don't bother dexopting for other
4672                            // paths & ISAs.
4673                            return DEX_OPT_FAILED;
4674                        }
4675
4676                        performedDexOpt = true;
4677                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4678                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4679                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4680                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4681                                pkg.packageName, dexCodeInstructionSet);
4682
4683                        if (ret < 0) {
4684                            // Don't bother running patchoat again if we failed, it will probably
4685                            // just result in an error again. Also, don't bother dexopting for other
4686                            // paths & ISAs.
4687                            return DEX_OPT_FAILED;
4688                        }
4689
4690                        performedDexOpt = true;
4691                    }
4692
4693                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4694                    // paths and instruction sets. We'll deal with them all together when we process
4695                    // our list of deferred dexopts.
4696                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4697                        if (mDeferredDexOpt == null) {
4698                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4699                        }
4700                        mDeferredDexOpt.add(pkg);
4701                        return DEX_OPT_DEFERRED;
4702                    }
4703                } catch (FileNotFoundException e) {
4704                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4705                    return DEX_OPT_FAILED;
4706                } catch (IOException e) {
4707                    Slog.w(TAG, "IOException reading apk: " + path, e);
4708                    return DEX_OPT_FAILED;
4709                } catch (StaleDexCacheError e) {
4710                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4711                    return DEX_OPT_FAILED;
4712                } catch (Exception e) {
4713                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4714                    return DEX_OPT_FAILED;
4715                }
4716            }
4717
4718            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4719            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4720            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4721            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4722            // it.
4723            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4724        }
4725
4726        // If we've gotten here, we're sure that no error occurred and that we haven't
4727        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4728        // we've skipped all of them because they are up to date. In both cases this
4729        // package doesn't need dexopt any longer.
4730        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4731    }
4732
4733    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4734        if (info.primaryCpuAbi != null) {
4735            if (info.secondaryCpuAbi != null) {
4736                return new String[] {
4737                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4738                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4739            } else {
4740                return new String[] {
4741                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4742            }
4743        }
4744
4745        return new String[] { getPreferredInstructionSet() };
4746    }
4747
4748    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4749        if (ps.primaryCpuAbiString != null) {
4750            if (ps.secondaryCpuAbiString != null) {
4751                return new String[] {
4752                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4753                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4754            } else {
4755                return new String[] {
4756                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4757            }
4758        }
4759
4760        return new String[] { getPreferredInstructionSet() };
4761    }
4762
4763    private static String getPreferredInstructionSet() {
4764        if (sPreferredInstructionSet == null) {
4765            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4766        }
4767
4768        return sPreferredInstructionSet;
4769    }
4770
4771    private static List<String> getAllInstructionSets() {
4772        final String[] allAbis = Build.SUPPORTED_ABIS;
4773        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4774
4775        for (String abi : allAbis) {
4776            final String instructionSet = VMRuntime.getInstructionSet(abi);
4777            if (!allInstructionSets.contains(instructionSet)) {
4778                allInstructionSets.add(instructionSet);
4779            }
4780        }
4781
4782        return allInstructionSets;
4783    }
4784
4785    /**
4786     * Returns the instruction set that should be used to compile dex code. In the presence of
4787     * a native bridge this might be different than the one shared libraries use.
4788     */
4789    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4790        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4791        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4792    }
4793
4794    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4795        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4796        for (String instructionSet : instructionSets) {
4797            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4798        }
4799        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4800    }
4801
4802    @Override
4803    public void forceDexOpt(String packageName) {
4804        enforceSystemOrRoot("forceDexOpt");
4805
4806        PackageParser.Package pkg;
4807        synchronized (mPackages) {
4808            pkg = mPackages.get(packageName);
4809            if (pkg == null) {
4810                throw new IllegalArgumentException("Missing package: " + packageName);
4811            }
4812        }
4813
4814        synchronized (mInstallLock) {
4815            final String[] instructionSets = new String[] {
4816                    getPrimaryInstructionSet(pkg.applicationInfo) };
4817            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4818            if (res != DEX_OPT_PERFORMED) {
4819                throw new IllegalStateException("Failed to dexopt: " + res);
4820            }
4821        }
4822    }
4823
4824    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4825                                boolean forceDex, boolean defer, boolean inclDependencies) {
4826        HashSet<String> done;
4827        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4828            done = new HashSet<String>();
4829            done.add(pkg.packageName);
4830        } else {
4831            done = null;
4832        }
4833        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4834    }
4835
4836    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4837        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4838            Slog.w(TAG, "Unable to update from " + oldPkg.name
4839                    + " to " + newPkg.packageName
4840                    + ": old package not in system partition");
4841            return false;
4842        } else if (mPackages.get(oldPkg.name) != null) {
4843            Slog.w(TAG, "Unable to update from " + oldPkg.name
4844                    + " to " + newPkg.packageName
4845                    + ": old package still exists");
4846            return false;
4847        }
4848        return true;
4849    }
4850
4851    File getDataPathForUser(int userId) {
4852        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4853    }
4854
4855    private File getDataPathForPackage(String packageName, int userId) {
4856        /*
4857         * Until we fully support multiple users, return the directory we
4858         * previously would have. The PackageManagerTests will need to be
4859         * revised when this is changed back..
4860         */
4861        if (userId == 0) {
4862            return new File(mAppDataDir, packageName);
4863        } else {
4864            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4865                + File.separator + packageName);
4866        }
4867    }
4868
4869    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4870        int[] users = sUserManager.getUserIds();
4871        int res = mInstaller.install(packageName, uid, uid, seinfo);
4872        if (res < 0) {
4873            return res;
4874        }
4875        for (int user : users) {
4876            if (user != 0) {
4877                res = mInstaller.createUserData(packageName,
4878                        UserHandle.getUid(user, uid), user, seinfo);
4879                if (res < 0) {
4880                    return res;
4881                }
4882            }
4883        }
4884        return res;
4885    }
4886
4887    private int removeDataDirsLI(String packageName) {
4888        int[] users = sUserManager.getUserIds();
4889        int res = 0;
4890        for (int user : users) {
4891            int resInner = mInstaller.remove(packageName, user);
4892            if (resInner < 0) {
4893                res = resInner;
4894            }
4895        }
4896
4897        return res;
4898    }
4899
4900    private int deleteCodeCacheDirsLI(String packageName) {
4901        int[] users = sUserManager.getUserIds();
4902        int res = 0;
4903        for (int user : users) {
4904            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4905            if (resInner < 0) {
4906                res = resInner;
4907            }
4908        }
4909        return res;
4910    }
4911
4912    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4913            PackageParser.Package changingLib) {
4914        if (file.path != null) {
4915            usesLibraryFiles.add(file.path);
4916            return;
4917        }
4918        PackageParser.Package p = mPackages.get(file.apk);
4919        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4920            // If we are doing this while in the middle of updating a library apk,
4921            // then we need to make sure to use that new apk for determining the
4922            // dependencies here.  (We haven't yet finished committing the new apk
4923            // to the package manager state.)
4924            if (p == null || p.packageName.equals(changingLib.packageName)) {
4925                p = changingLib;
4926            }
4927        }
4928        if (p != null) {
4929            usesLibraryFiles.addAll(p.getAllCodePaths());
4930        }
4931    }
4932
4933    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4934            PackageParser.Package changingLib) throws PackageManagerException {
4935        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4936            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4937            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4938            for (int i=0; i<N; i++) {
4939                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4940                if (file == null) {
4941                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4942                            "Package " + pkg.packageName + " requires unavailable shared library "
4943                            + pkg.usesLibraries.get(i) + "; failing!");
4944                }
4945                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4946            }
4947            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4948            for (int i=0; i<N; i++) {
4949                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4950                if (file == null) {
4951                    Slog.w(TAG, "Package " + pkg.packageName
4952                            + " desires unavailable shared library "
4953                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4954                } else {
4955                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4956                }
4957            }
4958            N = usesLibraryFiles.size();
4959            if (N > 0) {
4960                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4961            } else {
4962                pkg.usesLibraryFiles = null;
4963            }
4964        }
4965    }
4966
4967    private static boolean hasString(List<String> list, List<String> which) {
4968        if (list == null) {
4969            return false;
4970        }
4971        for (int i=list.size()-1; i>=0; i--) {
4972            for (int j=which.size()-1; j>=0; j--) {
4973                if (which.get(j).equals(list.get(i))) {
4974                    return true;
4975                }
4976            }
4977        }
4978        return false;
4979    }
4980
4981    private void updateAllSharedLibrariesLPw() {
4982        for (PackageParser.Package pkg : mPackages.values()) {
4983            try {
4984                updateSharedLibrariesLPw(pkg, null);
4985            } catch (PackageManagerException e) {
4986                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4987            }
4988        }
4989    }
4990
4991    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4992            PackageParser.Package changingPkg) {
4993        ArrayList<PackageParser.Package> res = null;
4994        for (PackageParser.Package pkg : mPackages.values()) {
4995            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4996                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4997                if (res == null) {
4998                    res = new ArrayList<PackageParser.Package>();
4999                }
5000                res.add(pkg);
5001                try {
5002                    updateSharedLibrariesLPw(pkg, changingPkg);
5003                } catch (PackageManagerException e) {
5004                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5005                }
5006            }
5007        }
5008        return res;
5009    }
5010
5011    /**
5012     * Derive the value of the {@code cpuAbiOverride} based on the provided
5013     * value and an optional stored value from the package settings.
5014     */
5015    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5016        String cpuAbiOverride = null;
5017
5018        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5019            cpuAbiOverride = null;
5020        } else if (abiOverride != null) {
5021            cpuAbiOverride = abiOverride;
5022        } else if (settings != null) {
5023            cpuAbiOverride = settings.cpuAbiOverrideString;
5024        }
5025
5026        return cpuAbiOverride;
5027    }
5028
5029    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5030            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5031        boolean success = false;
5032        try {
5033            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5034                    currentTime, user);
5035            success = true;
5036            return res;
5037        } finally {
5038            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5039                removeDataDirsLI(pkg.packageName);
5040            }
5041        }
5042    }
5043
5044    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5045            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5046        final File scanFile = new File(pkg.codePath);
5047        if (pkg.applicationInfo.getCodePath() == null ||
5048                pkg.applicationInfo.getResourcePath() == null) {
5049            // Bail out. The resource and code paths haven't been set.
5050            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5051                    "Code and resource paths haven't been set correctly");
5052        }
5053
5054        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5055            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5056        }
5057
5058        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5059            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5060        }
5061
5062        if (mCustomResolverComponentName != null &&
5063                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5064            setUpCustomResolverActivity(pkg);
5065        }
5066
5067        if (pkg.packageName.equals("android")) {
5068            synchronized (mPackages) {
5069                if (mAndroidApplication != null) {
5070                    Slog.w(TAG, "*************************************************");
5071                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5072                    Slog.w(TAG, " file=" + scanFile);
5073                    Slog.w(TAG, "*************************************************");
5074                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5075                            "Core android package being redefined.  Skipping.");
5076                }
5077
5078                // Set up information for our fall-back user intent resolution activity.
5079                mPlatformPackage = pkg;
5080                pkg.mVersionCode = mSdkVersion;
5081                mAndroidApplication = pkg.applicationInfo;
5082
5083                if (!mResolverReplaced) {
5084                    mResolveActivity.applicationInfo = mAndroidApplication;
5085                    mResolveActivity.name = ResolverActivity.class.getName();
5086                    mResolveActivity.packageName = mAndroidApplication.packageName;
5087                    mResolveActivity.processName = "system:ui";
5088                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5089                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5090                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5091                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5092                    mResolveActivity.exported = true;
5093                    mResolveActivity.enabled = true;
5094                    mResolveInfo.activityInfo = mResolveActivity;
5095                    mResolveInfo.priority = 0;
5096                    mResolveInfo.preferredOrder = 0;
5097                    mResolveInfo.match = 0;
5098                    mResolveComponentName = new ComponentName(
5099                            mAndroidApplication.packageName, mResolveActivity.name);
5100                }
5101            }
5102        }
5103
5104        if (DEBUG_PACKAGE_SCANNING) {
5105            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5106                Log.d(TAG, "Scanning package " + pkg.packageName);
5107        }
5108
5109        if (mPackages.containsKey(pkg.packageName)
5110                || mSharedLibraries.containsKey(pkg.packageName)) {
5111            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5112                    "Application package " + pkg.packageName
5113                    + " already installed.  Skipping duplicate.");
5114        }
5115
5116        // Initialize package source and resource directories
5117        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5118        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5119
5120        SharedUserSetting suid = null;
5121        PackageSetting pkgSetting = null;
5122
5123        if (!isSystemApp(pkg)) {
5124            // Only system apps can use these features.
5125            pkg.mOriginalPackages = null;
5126            pkg.mRealPackage = null;
5127            pkg.mAdoptPermissions = null;
5128        }
5129
5130        // writer
5131        synchronized (mPackages) {
5132            if (pkg.mSharedUserId != null) {
5133                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5134                if (suid == null) {
5135                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5136                            "Creating application package " + pkg.packageName
5137                            + " for shared user failed");
5138                }
5139                if (DEBUG_PACKAGE_SCANNING) {
5140                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5141                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5142                                + "): packages=" + suid.packages);
5143                }
5144            }
5145
5146            // Check if we are renaming from an original package name.
5147            PackageSetting origPackage = null;
5148            String realName = null;
5149            if (pkg.mOriginalPackages != null) {
5150                // This package may need to be renamed to a previously
5151                // installed name.  Let's check on that...
5152                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5153                if (pkg.mOriginalPackages.contains(renamed)) {
5154                    // This package had originally been installed as the
5155                    // original name, and we have already taken care of
5156                    // transitioning to the new one.  Just update the new
5157                    // one to continue using the old name.
5158                    realName = pkg.mRealPackage;
5159                    if (!pkg.packageName.equals(renamed)) {
5160                        // Callers into this function may have already taken
5161                        // care of renaming the package; only do it here if
5162                        // it is not already done.
5163                        pkg.setPackageName(renamed);
5164                    }
5165
5166                } else {
5167                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5168                        if ((origPackage = mSettings.peekPackageLPr(
5169                                pkg.mOriginalPackages.get(i))) != null) {
5170                            // We do have the package already installed under its
5171                            // original name...  should we use it?
5172                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5173                                // New package is not compatible with original.
5174                                origPackage = null;
5175                                continue;
5176                            } else if (origPackage.sharedUser != null) {
5177                                // Make sure uid is compatible between packages.
5178                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5179                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5180                                            + " to " + pkg.packageName + ": old uid "
5181                                            + origPackage.sharedUser.name
5182                                            + " differs from " + pkg.mSharedUserId);
5183                                    origPackage = null;
5184                                    continue;
5185                                }
5186                            } else {
5187                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5188                                        + pkg.packageName + " to old name " + origPackage.name);
5189                            }
5190                            break;
5191                        }
5192                    }
5193                }
5194            }
5195
5196            if (mTransferedPackages.contains(pkg.packageName)) {
5197                Slog.w(TAG, "Package " + pkg.packageName
5198                        + " was transferred to another, but its .apk remains");
5199            }
5200
5201            // Just create the setting, don't add it yet. For already existing packages
5202            // the PkgSetting exists already and doesn't have to be created.
5203            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5204                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5205                    pkg.applicationInfo.primaryCpuAbi,
5206                    pkg.applicationInfo.secondaryCpuAbi,
5207                    pkg.applicationInfo.flags, user, false);
5208            if (pkgSetting == null) {
5209                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5210                        "Creating application package " + pkg.packageName + " failed");
5211            }
5212
5213            if (pkgSetting.origPackage != null) {
5214                // If we are first transitioning from an original package,
5215                // fix up the new package's name now.  We need to do this after
5216                // looking up the package under its new name, so getPackageLP
5217                // can take care of fiddling things correctly.
5218                pkg.setPackageName(origPackage.name);
5219
5220                // File a report about this.
5221                String msg = "New package " + pkgSetting.realName
5222                        + " renamed to replace old package " + pkgSetting.name;
5223                reportSettingsProblem(Log.WARN, msg);
5224
5225                // Make a note of it.
5226                mTransferedPackages.add(origPackage.name);
5227
5228                // No longer need to retain this.
5229                pkgSetting.origPackage = null;
5230            }
5231
5232            if (realName != null) {
5233                // Make a note of it.
5234                mTransferedPackages.add(pkg.packageName);
5235            }
5236
5237            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5238                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5239            }
5240
5241            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5242                // Check all shared libraries and map to their actual file path.
5243                // We only do this here for apps not on a system dir, because those
5244                // are the only ones that can fail an install due to this.  We
5245                // will take care of the system apps by updating all of their
5246                // library paths after the scan is done.
5247                updateSharedLibrariesLPw(pkg, null);
5248            }
5249
5250            if (mFoundPolicyFile) {
5251                SELinuxMMAC.assignSeinfoValue(pkg);
5252            }
5253
5254            pkg.applicationInfo.uid = pkgSetting.appId;
5255            pkg.mExtras = pkgSetting;
5256            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5257                try {
5258                    verifySignaturesLP(pkgSetting, pkg);
5259                } catch (PackageManagerException e) {
5260                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5261                        throw e;
5262                    }
5263                    // The signature has changed, but this package is in the system
5264                    // image...  let's recover!
5265                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5266                    // However...  if this package is part of a shared user, but it
5267                    // doesn't match the signature of the shared user, let's fail.
5268                    // What this means is that you can't change the signatures
5269                    // associated with an overall shared user, which doesn't seem all
5270                    // that unreasonable.
5271                    if (pkgSetting.sharedUser != null) {
5272                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5273                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5274                            throw new PackageManagerException(
5275                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5276                                            "Signature mismatch for shared user : "
5277                                            + pkgSetting.sharedUser);
5278                        }
5279                    }
5280                    // File a report about this.
5281                    String msg = "System package " + pkg.packageName
5282                        + " signature changed; retaining data.";
5283                    reportSettingsProblem(Log.WARN, msg);
5284                }
5285            } else {
5286                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5287                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5288                            + pkg.packageName + " upgrade keys do not match the "
5289                            + "previously installed version");
5290                } else {
5291                    // signatures may have changed as result of upgrade
5292                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5293                }
5294            }
5295            // Verify that this new package doesn't have any content providers
5296            // that conflict with existing packages.  Only do this if the
5297            // package isn't already installed, since we don't want to break
5298            // things that are installed.
5299            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5300                final int N = pkg.providers.size();
5301                int i;
5302                for (i=0; i<N; i++) {
5303                    PackageParser.Provider p = pkg.providers.get(i);
5304                    if (p.info.authority != null) {
5305                        String names[] = p.info.authority.split(";");
5306                        for (int j = 0; j < names.length; j++) {
5307                            if (mProvidersByAuthority.containsKey(names[j])) {
5308                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5309                                final String otherPackageName =
5310                                        ((other != null && other.getComponentName() != null) ?
5311                                                other.getComponentName().getPackageName() : "?");
5312                                throw new PackageManagerException(
5313                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5314                                                "Can't install because provider name " + names[j]
5315                                                + " (in package " + pkg.applicationInfo.packageName
5316                                                + ") is already used by " + otherPackageName);
5317                            }
5318                        }
5319                    }
5320                }
5321            }
5322
5323            if (pkg.mAdoptPermissions != null) {
5324                // This package wants to adopt ownership of permissions from
5325                // another package.
5326                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5327                    final String origName = pkg.mAdoptPermissions.get(i);
5328                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5329                    if (orig != null) {
5330                        if (verifyPackageUpdateLPr(orig, pkg)) {
5331                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5332                                    + pkg.packageName);
5333                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5334                        }
5335                    }
5336                }
5337            }
5338        }
5339
5340        final String pkgName = pkg.packageName;
5341
5342        final long scanFileTime = scanFile.lastModified();
5343        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5344        pkg.applicationInfo.processName = fixProcessName(
5345                pkg.applicationInfo.packageName,
5346                pkg.applicationInfo.processName,
5347                pkg.applicationInfo.uid);
5348
5349        File dataPath;
5350        if (mPlatformPackage == pkg) {
5351            // The system package is special.
5352            dataPath = new File(Environment.getDataDirectory(), "system");
5353
5354            pkg.applicationInfo.dataDir = dataPath.getPath();
5355
5356        } else {
5357            // This is a normal package, need to make its data directory.
5358            dataPath = getDataPathForPackage(pkg.packageName, 0);
5359
5360            boolean uidError = false;
5361            if (dataPath.exists()) {
5362                int currentUid = 0;
5363                try {
5364                    StructStat stat = Os.stat(dataPath.getPath());
5365                    currentUid = stat.st_uid;
5366                } catch (ErrnoException e) {
5367                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5368                }
5369
5370                // If we have mismatched owners for the data path, we have a problem.
5371                if (currentUid != pkg.applicationInfo.uid) {
5372                    boolean recovered = false;
5373                    if (currentUid == 0) {
5374                        // The directory somehow became owned by root.  Wow.
5375                        // This is probably because the system was stopped while
5376                        // installd was in the middle of messing with its libs
5377                        // directory.  Ask installd to fix that.
5378                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5379                                pkg.applicationInfo.uid);
5380                        if (ret >= 0) {
5381                            recovered = true;
5382                            String msg = "Package " + pkg.packageName
5383                                    + " unexpectedly changed to uid 0; recovered to " +
5384                                    + pkg.applicationInfo.uid;
5385                            reportSettingsProblem(Log.WARN, msg);
5386                        }
5387                    }
5388                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5389                            || (scanFlags&SCAN_BOOTING) != 0)) {
5390                        // If this is a system app, we can at least delete its
5391                        // current data so the application will still work.
5392                        int ret = removeDataDirsLI(pkgName);
5393                        if (ret >= 0) {
5394                            // TODO: Kill the processes first
5395                            // Old data gone!
5396                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5397                                    ? "System package " : "Third party package ";
5398                            String msg = prefix + pkg.packageName
5399                                    + " has changed from uid: "
5400                                    + currentUid + " to "
5401                                    + pkg.applicationInfo.uid + "; old data erased";
5402                            reportSettingsProblem(Log.WARN, msg);
5403                            recovered = true;
5404
5405                            // And now re-install the app.
5406                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5407                                                   pkg.applicationInfo.seinfo);
5408                            if (ret == -1) {
5409                                // Ack should not happen!
5410                                msg = prefix + pkg.packageName
5411                                        + " could not have data directory re-created after delete.";
5412                                reportSettingsProblem(Log.WARN, msg);
5413                                throw new PackageManagerException(
5414                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5415                            }
5416                        }
5417                        if (!recovered) {
5418                            mHasSystemUidErrors = true;
5419                        }
5420                    } else if (!recovered) {
5421                        // If we allow this install to proceed, we will be broken.
5422                        // Abort, abort!
5423                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5424                                "scanPackageLI");
5425                    }
5426                    if (!recovered) {
5427                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5428                            + pkg.applicationInfo.uid + "/fs_"
5429                            + currentUid;
5430                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5431                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5432                        String msg = "Package " + pkg.packageName
5433                                + " has mismatched uid: "
5434                                + currentUid + " on disk, "
5435                                + pkg.applicationInfo.uid + " in settings";
5436                        // writer
5437                        synchronized (mPackages) {
5438                            mSettings.mReadMessages.append(msg);
5439                            mSettings.mReadMessages.append('\n');
5440                            uidError = true;
5441                            if (!pkgSetting.uidError) {
5442                                reportSettingsProblem(Log.ERROR, msg);
5443                            }
5444                        }
5445                    }
5446                }
5447                pkg.applicationInfo.dataDir = dataPath.getPath();
5448                if (mShouldRestoreconData) {
5449                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5450                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5451                                pkg.applicationInfo.uid);
5452                }
5453            } else {
5454                if (DEBUG_PACKAGE_SCANNING) {
5455                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5456                        Log.v(TAG, "Want this data dir: " + dataPath);
5457                }
5458                //invoke installer to do the actual installation
5459                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5460                                           pkg.applicationInfo.seinfo);
5461                if (ret < 0) {
5462                    // Error from installer
5463                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5464                            "Unable to create data dirs [errorCode=" + ret + "]");
5465                }
5466
5467                if (dataPath.exists()) {
5468                    pkg.applicationInfo.dataDir = dataPath.getPath();
5469                } else {
5470                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5471                    pkg.applicationInfo.dataDir = null;
5472                }
5473            }
5474
5475            pkgSetting.uidError = uidError;
5476        }
5477
5478        final String path = scanFile.getPath();
5479        final String codePath = pkg.applicationInfo.getCodePath();
5480        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5481        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5482            setBundledAppAbisAndRoots(pkg, pkgSetting);
5483
5484            // If we haven't found any native libraries for the app, check if it has
5485            // renderscript code. We'll need to force the app to 32 bit if it has
5486            // renderscript bitcode.
5487            if (pkg.applicationInfo.primaryCpuAbi == null
5488                    && pkg.applicationInfo.secondaryCpuAbi == null
5489                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5490                NativeLibraryHelper.Handle handle = null;
5491                try {
5492                    handle = NativeLibraryHelper.Handle.create(scanFile);
5493                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5494                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5495                    }
5496                } catch (IOException ioe) {
5497                    Slog.w(TAG, "Error scanning system app : " + ioe);
5498                } finally {
5499                    IoUtils.closeQuietly(handle);
5500                }
5501            }
5502
5503            setNativeLibraryPaths(pkg);
5504        } else {
5505            // TODO: We can probably be smarter about this stuff. For installed apps,
5506            // we can calculate this information at install time once and for all. For
5507            // system apps, we can probably assume that this information doesn't change
5508            // after the first boot scan. As things stand, we do lots of unnecessary work.
5509
5510            // Give ourselves some initial paths; we'll come back for another
5511            // pass once we've determined ABI below.
5512            setNativeLibraryPaths(pkg);
5513
5514            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5515            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5516            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5517
5518            NativeLibraryHelper.Handle handle = null;
5519            try {
5520                handle = NativeLibraryHelper.Handle.create(scanFile);
5521                // TODO(multiArch): This can be null for apps that didn't go through the
5522                // usual installation process. We can calculate it again, like we
5523                // do during install time.
5524                //
5525                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5526                // unnecessary.
5527                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5528
5529                // Null out the abis so that they can be recalculated.
5530                pkg.applicationInfo.primaryCpuAbi = null;
5531                pkg.applicationInfo.secondaryCpuAbi = null;
5532                if (isMultiArch(pkg.applicationInfo)) {
5533                    // Warn if we've set an abiOverride for multi-lib packages..
5534                    // By definition, we need to copy both 32 and 64 bit libraries for
5535                    // such packages.
5536                    if (pkg.cpuAbiOverride != null
5537                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5538                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5539                    }
5540
5541                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5542                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5543                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5544                        if (isAsec) {
5545                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5546                        } else {
5547                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5548                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5549                                    useIsaSpecificSubdirs);
5550                        }
5551                    }
5552
5553                    maybeThrowExceptionForMultiArchCopy(
5554                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5555
5556                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5557                        if (isAsec) {
5558                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5559                        } else {
5560                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5561                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5562                                    useIsaSpecificSubdirs);
5563                        }
5564                    }
5565
5566                    maybeThrowExceptionForMultiArchCopy(
5567                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5568
5569                    if (abi64 >= 0) {
5570                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5571                    }
5572
5573                    if (abi32 >= 0) {
5574                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5575                        if (abi64 >= 0) {
5576                            pkg.applicationInfo.secondaryCpuAbi = abi;
5577                        } else {
5578                            pkg.applicationInfo.primaryCpuAbi = abi;
5579                        }
5580                    }
5581                } else {
5582                    String[] abiList = (cpuAbiOverride != null) ?
5583                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5584
5585                    // Enable gross and lame hacks for apps that are built with old
5586                    // SDK tools. We must scan their APKs for renderscript bitcode and
5587                    // not launch them if it's present. Don't bother checking on devices
5588                    // that don't have 64 bit support.
5589                    boolean needsRenderScriptOverride = false;
5590                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5591                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5592                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5593                        needsRenderScriptOverride = true;
5594                    }
5595
5596                    final int copyRet;
5597                    if (isAsec) {
5598                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5599                    } else {
5600                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5601                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5602                    }
5603
5604                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5605                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5606                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5607                    }
5608
5609                    if (copyRet >= 0) {
5610                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5611                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5612                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5613                    } else if (needsRenderScriptOverride) {
5614                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5615                    }
5616                }
5617            } catch (IOException ioe) {
5618                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5619            } finally {
5620                IoUtils.closeQuietly(handle);
5621            }
5622
5623            // Now that we've calculated the ABIs and determined if it's an internal app,
5624            // we will go ahead and populate the nativeLibraryPath.
5625            setNativeLibraryPaths(pkg);
5626
5627            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5628            final int[] userIds = sUserManager.getUserIds();
5629            synchronized (mInstallLock) {
5630                // Create a native library symlink only if we have native libraries
5631                // and if the native libraries are 32 bit libraries. We do not provide
5632                // this symlink for 64 bit libraries.
5633                if (pkg.applicationInfo.primaryCpuAbi != null &&
5634                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5635                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5636                    for (int userId : userIds) {
5637                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5638                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5639                                    "Failed linking native library dir (user=" + userId + ")");
5640                        }
5641                    }
5642                }
5643            }
5644        }
5645
5646        // This is a special case for the "system" package, where the ABI is
5647        // dictated by the zygote configuration (and init.rc). We should keep track
5648        // of this ABI so that we can deal with "normal" applications that run under
5649        // the same UID correctly.
5650        if (mPlatformPackage == pkg) {
5651            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5652                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5653        }
5654
5655        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5656        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5657        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5658        // Copy the derived override back to the parsed package, so that we can
5659        // update the package settings accordingly.
5660        pkg.cpuAbiOverride = cpuAbiOverride;
5661
5662        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5663                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5664                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5665
5666        // Push the derived path down into PackageSettings so we know what to
5667        // clean up at uninstall time.
5668        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5669
5670        if (DEBUG_ABI_SELECTION) {
5671            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5672                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5673                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5674        }
5675
5676        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5677            // We don't do this here during boot because we can do it all
5678            // at once after scanning all existing packages.
5679            //
5680            // We also do this *before* we perform dexopt on this package, so that
5681            // we can avoid redundant dexopts, and also to make sure we've got the
5682            // code and package path correct.
5683            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5684                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5685        }
5686
5687        if ((scanFlags & SCAN_NO_DEX) == 0) {
5688            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5689                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5690                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5691            }
5692        }
5693
5694        if (mFactoryTest && pkg.requestedPermissions.contains(
5695                android.Manifest.permission.FACTORY_TEST)) {
5696            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5697        }
5698
5699        ArrayList<PackageParser.Package> clientLibPkgs = null;
5700
5701        // writer
5702        synchronized (mPackages) {
5703            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5704                // Only system apps can add new shared libraries.
5705                if (pkg.libraryNames != null) {
5706                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5707                        String name = pkg.libraryNames.get(i);
5708                        boolean allowed = false;
5709                        if (isUpdatedSystemApp(pkg)) {
5710                            // New library entries can only be added through the
5711                            // system image.  This is important to get rid of a lot
5712                            // of nasty edge cases: for example if we allowed a non-
5713                            // system update of the app to add a library, then uninstalling
5714                            // the update would make the library go away, and assumptions
5715                            // we made such as through app install filtering would now
5716                            // have allowed apps on the device which aren't compatible
5717                            // with it.  Better to just have the restriction here, be
5718                            // conservative, and create many fewer cases that can negatively
5719                            // impact the user experience.
5720                            final PackageSetting sysPs = mSettings
5721                                    .getDisabledSystemPkgLPr(pkg.packageName);
5722                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5723                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5724                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5725                                        allowed = true;
5726                                        allowed = true;
5727                                        break;
5728                                    }
5729                                }
5730                            }
5731                        } else {
5732                            allowed = true;
5733                        }
5734                        if (allowed) {
5735                            if (!mSharedLibraries.containsKey(name)) {
5736                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5737                            } else if (!name.equals(pkg.packageName)) {
5738                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5739                                        + name + " already exists; skipping");
5740                            }
5741                        } else {
5742                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5743                                    + name + " that is not declared on system image; skipping");
5744                        }
5745                    }
5746                    if ((scanFlags&SCAN_BOOTING) == 0) {
5747                        // If we are not booting, we need to update any applications
5748                        // that are clients of our shared library.  If we are booting,
5749                        // this will all be done once the scan is complete.
5750                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5751                    }
5752                }
5753            }
5754        }
5755
5756        // We also need to dexopt any apps that are dependent on this library.  Note that
5757        // if these fail, we should abort the install since installing the library will
5758        // result in some apps being broken.
5759        if (clientLibPkgs != null) {
5760            if ((scanFlags & SCAN_NO_DEX) == 0) {
5761                for (int i = 0; i < clientLibPkgs.size(); i++) {
5762                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5763                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5764                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5765                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5766                                "scanPackageLI failed to dexopt clientLibPkgs");
5767                    }
5768                }
5769            }
5770        }
5771
5772        // Request the ActivityManager to kill the process(only for existing packages)
5773        // so that we do not end up in a confused state while the user is still using the older
5774        // version of the application while the new one gets installed.
5775        if ((scanFlags & SCAN_REPLACING) != 0) {
5776            killApplication(pkg.applicationInfo.packageName,
5777                        pkg.applicationInfo.uid, "update pkg");
5778        }
5779
5780        // Also need to kill any apps that are dependent on the library.
5781        if (clientLibPkgs != null) {
5782            for (int i=0; i<clientLibPkgs.size(); i++) {
5783                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5784                killApplication(clientPkg.applicationInfo.packageName,
5785                        clientPkg.applicationInfo.uid, "update lib");
5786            }
5787        }
5788
5789        // writer
5790        synchronized (mPackages) {
5791            // We don't expect installation to fail beyond this point
5792
5793            // Add the new setting to mSettings
5794            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5795            // Add the new setting to mPackages
5796            mPackages.put(pkg.applicationInfo.packageName, pkg);
5797            // Make sure we don't accidentally delete its data.
5798            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5799            while (iter.hasNext()) {
5800                PackageCleanItem item = iter.next();
5801                if (pkgName.equals(item.packageName)) {
5802                    iter.remove();
5803                }
5804            }
5805
5806            // Take care of first install / last update times.
5807            if (currentTime != 0) {
5808                if (pkgSetting.firstInstallTime == 0) {
5809                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5810                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5811                    pkgSetting.lastUpdateTime = currentTime;
5812                }
5813            } else if (pkgSetting.firstInstallTime == 0) {
5814                // We need *something*.  Take time time stamp of the file.
5815                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5816            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5817                if (scanFileTime != pkgSetting.timeStamp) {
5818                    // A package on the system image has changed; consider this
5819                    // to be an update.
5820                    pkgSetting.lastUpdateTime = scanFileTime;
5821                }
5822            }
5823
5824            // Add the package's KeySets to the global KeySetManagerService
5825            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5826            try {
5827                // Old KeySetData no longer valid.
5828                ksms.removeAppKeySetDataLPw(pkg.packageName);
5829                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5830                if (pkg.mKeySetMapping != null) {
5831                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5832                            pkg.mKeySetMapping.entrySet()) {
5833                        if (entry.getValue() != null) {
5834                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5835                                                          entry.getValue(), entry.getKey());
5836                        }
5837                    }
5838                    if (pkg.mUpgradeKeySets != null) {
5839                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5840                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5841                        }
5842                    }
5843                }
5844            } catch (NullPointerException e) {
5845                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5846            } catch (IllegalArgumentException e) {
5847                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5848            }
5849
5850            int N = pkg.providers.size();
5851            StringBuilder r = null;
5852            int i;
5853            for (i=0; i<N; i++) {
5854                PackageParser.Provider p = pkg.providers.get(i);
5855                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5856                        p.info.processName, pkg.applicationInfo.uid);
5857                mProviders.addProvider(p);
5858                p.syncable = p.info.isSyncable;
5859                if (p.info.authority != null) {
5860                    String names[] = p.info.authority.split(";");
5861                    p.info.authority = null;
5862                    for (int j = 0; j < names.length; j++) {
5863                        if (j == 1 && p.syncable) {
5864                            // We only want the first authority for a provider to possibly be
5865                            // syncable, so if we already added this provider using a different
5866                            // authority clear the syncable flag. We copy the provider before
5867                            // changing it because the mProviders object contains a reference
5868                            // to a provider that we don't want to change.
5869                            // Only do this for the second authority since the resulting provider
5870                            // object can be the same for all future authorities for this provider.
5871                            p = new PackageParser.Provider(p);
5872                            p.syncable = false;
5873                        }
5874                        if (!mProvidersByAuthority.containsKey(names[j])) {
5875                            mProvidersByAuthority.put(names[j], p);
5876                            if (p.info.authority == null) {
5877                                p.info.authority = names[j];
5878                            } else {
5879                                p.info.authority = p.info.authority + ";" + names[j];
5880                            }
5881                            if (DEBUG_PACKAGE_SCANNING) {
5882                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5883                                    Log.d(TAG, "Registered content provider: " + names[j]
5884                                            + ", className = " + p.info.name + ", isSyncable = "
5885                                            + p.info.isSyncable);
5886                            }
5887                        } else {
5888                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5889                            Slog.w(TAG, "Skipping provider name " + names[j] +
5890                                    " (in package " + pkg.applicationInfo.packageName +
5891                                    "): name already used by "
5892                                    + ((other != null && other.getComponentName() != null)
5893                                            ? other.getComponentName().getPackageName() : "?"));
5894                        }
5895                    }
5896                }
5897                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5898                    if (r == null) {
5899                        r = new StringBuilder(256);
5900                    } else {
5901                        r.append(' ');
5902                    }
5903                    r.append(p.info.name);
5904                }
5905            }
5906            if (r != null) {
5907                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5908            }
5909
5910            N = pkg.services.size();
5911            r = null;
5912            for (i=0; i<N; i++) {
5913                PackageParser.Service s = pkg.services.get(i);
5914                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5915                        s.info.processName, pkg.applicationInfo.uid);
5916                mServices.addService(s);
5917                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5918                    if (r == null) {
5919                        r = new StringBuilder(256);
5920                    } else {
5921                        r.append(' ');
5922                    }
5923                    r.append(s.info.name);
5924                }
5925            }
5926            if (r != null) {
5927                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5928            }
5929
5930            N = pkg.receivers.size();
5931            r = null;
5932            for (i=0; i<N; i++) {
5933                PackageParser.Activity a = pkg.receivers.get(i);
5934                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5935                        a.info.processName, pkg.applicationInfo.uid);
5936                mReceivers.addActivity(a, "receiver");
5937                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5938                    if (r == null) {
5939                        r = new StringBuilder(256);
5940                    } else {
5941                        r.append(' ');
5942                    }
5943                    r.append(a.info.name);
5944                }
5945            }
5946            if (r != null) {
5947                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5948            }
5949
5950            N = pkg.activities.size();
5951            r = null;
5952            for (i=0; i<N; i++) {
5953                PackageParser.Activity a = pkg.activities.get(i);
5954                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5955                        a.info.processName, pkg.applicationInfo.uid);
5956                mActivities.addActivity(a, "activity");
5957                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5958                    if (r == null) {
5959                        r = new StringBuilder(256);
5960                    } else {
5961                        r.append(' ');
5962                    }
5963                    r.append(a.info.name);
5964                }
5965            }
5966            if (r != null) {
5967                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5968            }
5969
5970            N = pkg.permissionGroups.size();
5971            r = null;
5972            for (i=0; i<N; i++) {
5973                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5974                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5975                if (cur == null) {
5976                    mPermissionGroups.put(pg.info.name, pg);
5977                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5978                        if (r == null) {
5979                            r = new StringBuilder(256);
5980                        } else {
5981                            r.append(' ');
5982                        }
5983                        r.append(pg.info.name);
5984                    }
5985                } else {
5986                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5987                            + pg.info.packageName + " ignored: original from "
5988                            + cur.info.packageName);
5989                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5990                        if (r == null) {
5991                            r = new StringBuilder(256);
5992                        } else {
5993                            r.append(' ');
5994                        }
5995                        r.append("DUP:");
5996                        r.append(pg.info.name);
5997                    }
5998                }
5999            }
6000            if (r != null) {
6001                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6002            }
6003
6004            N = pkg.permissions.size();
6005            r = null;
6006            for (i=0; i<N; i++) {
6007                PackageParser.Permission p = pkg.permissions.get(i);
6008                HashMap<String, BasePermission> permissionMap =
6009                        p.tree ? mSettings.mPermissionTrees
6010                        : mSettings.mPermissions;
6011                p.group = mPermissionGroups.get(p.info.group);
6012                if (p.info.group == null || p.group != null) {
6013                    BasePermission bp = permissionMap.get(p.info.name);
6014                    if (bp == null) {
6015                        bp = new BasePermission(p.info.name, p.info.packageName,
6016                                BasePermission.TYPE_NORMAL);
6017                        permissionMap.put(p.info.name, bp);
6018                    }
6019                    if (bp.perm == null) {
6020                        if (bp.sourcePackage != null
6021                                && !bp.sourcePackage.equals(p.info.packageName)) {
6022                            // If this is a permission that was formerly defined by a non-system
6023                            // app, but is now defined by a system app (following an upgrade),
6024                            // discard the previous declaration and consider the system's to be
6025                            // canonical.
6026                            if (isSystemApp(p.owner)) {
6027                                String msg = "New decl " + p.owner + " of permission  "
6028                                        + p.info.name + " is system";
6029                                reportSettingsProblem(Log.WARN, msg);
6030                                bp.sourcePackage = null;
6031                            }
6032                        }
6033                        if (bp.sourcePackage == null
6034                                || bp.sourcePackage.equals(p.info.packageName)) {
6035                            BasePermission tree = findPermissionTreeLP(p.info.name);
6036                            if (tree == null
6037                                    || tree.sourcePackage.equals(p.info.packageName)) {
6038                                bp.packageSetting = pkgSetting;
6039                                bp.perm = p;
6040                                bp.uid = pkg.applicationInfo.uid;
6041                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6042                                    if (r == null) {
6043                                        r = new StringBuilder(256);
6044                                    } else {
6045                                        r.append(' ');
6046                                    }
6047                                    r.append(p.info.name);
6048                                }
6049                            } else {
6050                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6051                                        + p.info.packageName + " ignored: base tree "
6052                                        + tree.name + " is from package "
6053                                        + tree.sourcePackage);
6054                            }
6055                        } else {
6056                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6057                                    + p.info.packageName + " ignored: original from "
6058                                    + bp.sourcePackage);
6059                        }
6060                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6061                        if (r == null) {
6062                            r = new StringBuilder(256);
6063                        } else {
6064                            r.append(' ');
6065                        }
6066                        r.append("DUP:");
6067                        r.append(p.info.name);
6068                    }
6069                    if (bp.perm == p) {
6070                        bp.protectionLevel = p.info.protectionLevel;
6071                    }
6072                } else {
6073                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6074                            + p.info.packageName + " ignored: no group "
6075                            + p.group);
6076                }
6077            }
6078            if (r != null) {
6079                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6080            }
6081
6082            N = pkg.instrumentation.size();
6083            r = null;
6084            for (i=0; i<N; i++) {
6085                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6086                a.info.packageName = pkg.applicationInfo.packageName;
6087                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6088                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6089                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6090                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6091                a.info.dataDir = pkg.applicationInfo.dataDir;
6092
6093                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6094                // need other information about the application, like the ABI and what not ?
6095                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6096                mInstrumentation.put(a.getComponentName(), a);
6097                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6098                    if (r == null) {
6099                        r = new StringBuilder(256);
6100                    } else {
6101                        r.append(' ');
6102                    }
6103                    r.append(a.info.name);
6104                }
6105            }
6106            if (r != null) {
6107                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6108            }
6109
6110            if (pkg.protectedBroadcasts != null) {
6111                N = pkg.protectedBroadcasts.size();
6112                for (i=0; i<N; i++) {
6113                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6114                }
6115            }
6116
6117            pkgSetting.setTimeStamp(scanFileTime);
6118
6119            // Create idmap files for pairs of (packages, overlay packages).
6120            // Note: "android", ie framework-res.apk, is handled by native layers.
6121            if (pkg.mOverlayTarget != null) {
6122                // This is an overlay package.
6123                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6124                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6125                        mOverlays.put(pkg.mOverlayTarget,
6126                                new HashMap<String, PackageParser.Package>());
6127                    }
6128                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6129                    map.put(pkg.packageName, pkg);
6130                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6131                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6132                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6133                                "scanPackageLI failed to createIdmap");
6134                    }
6135                }
6136            } else if (mOverlays.containsKey(pkg.packageName) &&
6137                    !pkg.packageName.equals("android")) {
6138                // This is a regular package, with one or more known overlay packages.
6139                createIdmapsForPackageLI(pkg);
6140            }
6141        }
6142
6143        return pkg;
6144    }
6145
6146    /**
6147     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6148     * i.e, so that all packages can be run inside a single process if required.
6149     *
6150     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6151     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6152     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6153     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6154     * updating a package that belongs to a shared user.
6155     *
6156     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6157     * adds unnecessary complexity.
6158     */
6159    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6160            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6161        String requiredInstructionSet = null;
6162        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6163            requiredInstructionSet = VMRuntime.getInstructionSet(
6164                     scannedPackage.applicationInfo.primaryCpuAbi);
6165        }
6166
6167        PackageSetting requirer = null;
6168        for (PackageSetting ps : packagesForUser) {
6169            // If packagesForUser contains scannedPackage, we skip it. This will happen
6170            // when scannedPackage is an update of an existing package. Without this check,
6171            // we will never be able to change the ABI of any package belonging to a shared
6172            // user, even if it's compatible with other packages.
6173            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6174                if (ps.primaryCpuAbiString == null) {
6175                    continue;
6176                }
6177
6178                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6179                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6180                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6181                    // this but there's not much we can do.
6182                    String errorMessage = "Instruction set mismatch, "
6183                            + ((requirer == null) ? "[caller]" : requirer)
6184                            + " requires " + requiredInstructionSet + " whereas " + ps
6185                            + " requires " + instructionSet;
6186                    Slog.w(TAG, errorMessage);
6187                }
6188
6189                if (requiredInstructionSet == null) {
6190                    requiredInstructionSet = instructionSet;
6191                    requirer = ps;
6192                }
6193            }
6194        }
6195
6196        if (requiredInstructionSet != null) {
6197            String adjustedAbi;
6198            if (requirer != null) {
6199                // requirer != null implies that either scannedPackage was null or that scannedPackage
6200                // did not require an ABI, in which case we have to adjust scannedPackage to match
6201                // the ABI of the set (which is the same as requirer's ABI)
6202                adjustedAbi = requirer.primaryCpuAbiString;
6203                if (scannedPackage != null) {
6204                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6205                }
6206            } else {
6207                // requirer == null implies that we're updating all ABIs in the set to
6208                // match scannedPackage.
6209                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6210            }
6211
6212            for (PackageSetting ps : packagesForUser) {
6213                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6214                    if (ps.primaryCpuAbiString != null) {
6215                        continue;
6216                    }
6217
6218                    ps.primaryCpuAbiString = adjustedAbi;
6219                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6220                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6221                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6222
6223                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6224                                deferDexOpt, true) == DEX_OPT_FAILED) {
6225                            ps.primaryCpuAbiString = null;
6226                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6227                            return;
6228                        } else {
6229                            mInstaller.rmdex(ps.codePathString,
6230                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6231                        }
6232                    }
6233                }
6234            }
6235        }
6236    }
6237
6238    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6239        synchronized (mPackages) {
6240            mResolverReplaced = true;
6241            // Set up information for custom user intent resolution activity.
6242            mResolveActivity.applicationInfo = pkg.applicationInfo;
6243            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6244            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6245            mResolveActivity.processName = null;
6246            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6247            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6248                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6249            mResolveActivity.theme = 0;
6250            mResolveActivity.exported = true;
6251            mResolveActivity.enabled = true;
6252            mResolveInfo.activityInfo = mResolveActivity;
6253            mResolveInfo.priority = 0;
6254            mResolveInfo.preferredOrder = 0;
6255            mResolveInfo.match = 0;
6256            mResolveComponentName = mCustomResolverComponentName;
6257            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6258                    mResolveComponentName);
6259        }
6260    }
6261
6262    private static String calculateBundledApkRoot(final String codePathString) {
6263        final File codePath = new File(codePathString);
6264        final File codeRoot;
6265        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6266            codeRoot = Environment.getRootDirectory();
6267        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6268            codeRoot = Environment.getOemDirectory();
6269        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6270            codeRoot = Environment.getVendorDirectory();
6271        } else {
6272            // Unrecognized code path; take its top real segment as the apk root:
6273            // e.g. /something/app/blah.apk => /something
6274            try {
6275                File f = codePath.getCanonicalFile();
6276                File parent = f.getParentFile();    // non-null because codePath is a file
6277                File tmp;
6278                while ((tmp = parent.getParentFile()) != null) {
6279                    f = parent;
6280                    parent = tmp;
6281                }
6282                codeRoot = f;
6283                Slog.w(TAG, "Unrecognized code path "
6284                        + codePath + " - using " + codeRoot);
6285            } catch (IOException e) {
6286                // Can't canonicalize the code path -- shenanigans?
6287                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6288                return Environment.getRootDirectory().getPath();
6289            }
6290        }
6291        return codeRoot.getPath();
6292    }
6293
6294    /**
6295     * Derive and set the location of native libraries for the given package,
6296     * which varies depending on where and how the package was installed.
6297     */
6298    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6299        final ApplicationInfo info = pkg.applicationInfo;
6300        final String codePath = pkg.codePath;
6301        final File codeFile = new File(codePath);
6302        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6303        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6304
6305        info.nativeLibraryRootDir = null;
6306        info.nativeLibraryRootRequiresIsa = false;
6307        info.nativeLibraryDir = null;
6308        info.secondaryNativeLibraryDir = null;
6309
6310        if (isApkFile(codeFile)) {
6311            // Monolithic install
6312            if (bundledApp) {
6313                // If "/system/lib64/apkname" exists, assume that is the per-package
6314                // native library directory to use; otherwise use "/system/lib/apkname".
6315                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6316                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6317                        getPrimaryInstructionSet(info));
6318
6319                // This is a bundled system app so choose the path based on the ABI.
6320                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6321                // is just the default path.
6322                final String apkName = deriveCodePathName(codePath);
6323                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6324                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6325                        apkName).getAbsolutePath();
6326
6327                if (info.secondaryCpuAbi != null) {
6328                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6329                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6330                            secondaryLibDir, apkName).getAbsolutePath();
6331                }
6332            } else if (asecApp) {
6333                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6334                        .getAbsolutePath();
6335            } else {
6336                final String apkName = deriveCodePathName(codePath);
6337                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6338                        .getAbsolutePath();
6339            }
6340
6341            info.nativeLibraryRootRequiresIsa = false;
6342            info.nativeLibraryDir = info.nativeLibraryRootDir;
6343        } else {
6344            // Cluster install
6345            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6346            info.nativeLibraryRootRequiresIsa = true;
6347
6348            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6349                    getPrimaryInstructionSet(info)).getAbsolutePath();
6350
6351            if (info.secondaryCpuAbi != null) {
6352                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6353                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6354            }
6355        }
6356    }
6357
6358    /**
6359     * Calculate the abis and roots for a bundled app. These can uniquely
6360     * be determined from the contents of the system partition, i.e whether
6361     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6362     * of this information, and instead assume that the system was built
6363     * sensibly.
6364     */
6365    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6366                                           PackageSetting pkgSetting) {
6367        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6368
6369        // If "/system/lib64/apkname" exists, assume that is the per-package
6370        // native library directory to use; otherwise use "/system/lib/apkname".
6371        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6372        setBundledAppAbi(pkg, apkRoot, apkName);
6373        // pkgSetting might be null during rescan following uninstall of updates
6374        // to a bundled app, so accommodate that possibility.  The settings in
6375        // that case will be established later from the parsed package.
6376        //
6377        // If the settings aren't null, sync them up with what we've just derived.
6378        // note that apkRoot isn't stored in the package settings.
6379        if (pkgSetting != null) {
6380            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6381            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6382        }
6383    }
6384
6385    /**
6386     * Deduces the ABI of a bundled app and sets the relevant fields on the
6387     * parsed pkg object.
6388     *
6389     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6390     *        under which system libraries are installed.
6391     * @param apkName the name of the installed package.
6392     */
6393    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6394        final File codeFile = new File(pkg.codePath);
6395
6396        final boolean has64BitLibs;
6397        final boolean has32BitLibs;
6398        if (isApkFile(codeFile)) {
6399            // Monolithic install
6400            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6401            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6402        } else {
6403            // Cluster install
6404            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6405            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6406                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6407                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6408                has64BitLibs = (new File(rootDir, isa)).exists();
6409            } else {
6410                has64BitLibs = false;
6411            }
6412            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6413                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6414                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6415                has32BitLibs = (new File(rootDir, isa)).exists();
6416            } else {
6417                has32BitLibs = false;
6418            }
6419        }
6420
6421        if (has64BitLibs && !has32BitLibs) {
6422            // The package has 64 bit libs, but not 32 bit libs. Its primary
6423            // ABI should be 64 bit. We can safely assume here that the bundled
6424            // native libraries correspond to the most preferred ABI in the list.
6425
6426            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6427            pkg.applicationInfo.secondaryCpuAbi = null;
6428        } else if (has32BitLibs && !has64BitLibs) {
6429            // The package has 32 bit libs but not 64 bit libs. Its primary
6430            // ABI should be 32 bit.
6431
6432            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6433            pkg.applicationInfo.secondaryCpuAbi = null;
6434        } else if (has32BitLibs && has64BitLibs) {
6435            // The application has both 64 and 32 bit bundled libraries. We check
6436            // here that the app declares multiArch support, and warn if it doesn't.
6437            //
6438            // We will be lenient here and record both ABIs. The primary will be the
6439            // ABI that's higher on the list, i.e, a device that's configured to prefer
6440            // 64 bit apps will see a 64 bit primary ABI,
6441
6442            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6443                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6444            }
6445
6446            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6447                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6448                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6449            } else {
6450                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6451                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6452            }
6453        } else {
6454            pkg.applicationInfo.primaryCpuAbi = null;
6455            pkg.applicationInfo.secondaryCpuAbi = null;
6456        }
6457    }
6458
6459    private void killApplication(String pkgName, int appId, String reason) {
6460        // Request the ActivityManager to kill the process(only for existing packages)
6461        // so that we do not end up in a confused state while the user is still using the older
6462        // version of the application while the new one gets installed.
6463        IActivityManager am = ActivityManagerNative.getDefault();
6464        if (am != null) {
6465            try {
6466                am.killApplicationWithAppId(pkgName, appId, reason);
6467            } catch (RemoteException e) {
6468            }
6469        }
6470    }
6471
6472    void removePackageLI(PackageSetting ps, boolean chatty) {
6473        if (DEBUG_INSTALL) {
6474            if (chatty)
6475                Log.d(TAG, "Removing package " + ps.name);
6476        }
6477
6478        // writer
6479        synchronized (mPackages) {
6480            mPackages.remove(ps.name);
6481            final PackageParser.Package pkg = ps.pkg;
6482            if (pkg != null) {
6483                cleanPackageDataStructuresLILPw(pkg, chatty);
6484            }
6485        }
6486    }
6487
6488    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6489        if (DEBUG_INSTALL) {
6490            if (chatty)
6491                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6492        }
6493
6494        // writer
6495        synchronized (mPackages) {
6496            mPackages.remove(pkg.applicationInfo.packageName);
6497            cleanPackageDataStructuresLILPw(pkg, chatty);
6498        }
6499    }
6500
6501    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6502        int N = pkg.providers.size();
6503        StringBuilder r = null;
6504        int i;
6505        for (i=0; i<N; i++) {
6506            PackageParser.Provider p = pkg.providers.get(i);
6507            mProviders.removeProvider(p);
6508            if (p.info.authority == null) {
6509
6510                /* There was another ContentProvider with this authority when
6511                 * this app was installed so this authority is null,
6512                 * Ignore it as we don't have to unregister the provider.
6513                 */
6514                continue;
6515            }
6516            String names[] = p.info.authority.split(";");
6517            for (int j = 0; j < names.length; j++) {
6518                if (mProvidersByAuthority.get(names[j]) == p) {
6519                    mProvidersByAuthority.remove(names[j]);
6520                    if (DEBUG_REMOVE) {
6521                        if (chatty)
6522                            Log.d(TAG, "Unregistered content provider: " + names[j]
6523                                    + ", className = " + p.info.name + ", isSyncable = "
6524                                    + p.info.isSyncable);
6525                    }
6526                }
6527            }
6528            if (DEBUG_REMOVE && chatty) {
6529                if (r == null) {
6530                    r = new StringBuilder(256);
6531                } else {
6532                    r.append(' ');
6533                }
6534                r.append(p.info.name);
6535            }
6536        }
6537        if (r != null) {
6538            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6539        }
6540
6541        N = pkg.services.size();
6542        r = null;
6543        for (i=0; i<N; i++) {
6544            PackageParser.Service s = pkg.services.get(i);
6545            mServices.removeService(s);
6546            if (chatty) {
6547                if (r == null) {
6548                    r = new StringBuilder(256);
6549                } else {
6550                    r.append(' ');
6551                }
6552                r.append(s.info.name);
6553            }
6554        }
6555        if (r != null) {
6556            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6557        }
6558
6559        N = pkg.receivers.size();
6560        r = null;
6561        for (i=0; i<N; i++) {
6562            PackageParser.Activity a = pkg.receivers.get(i);
6563            mReceivers.removeActivity(a, "receiver");
6564            if (DEBUG_REMOVE && chatty) {
6565                if (r == null) {
6566                    r = new StringBuilder(256);
6567                } else {
6568                    r.append(' ');
6569                }
6570                r.append(a.info.name);
6571            }
6572        }
6573        if (r != null) {
6574            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6575        }
6576
6577        N = pkg.activities.size();
6578        r = null;
6579        for (i=0; i<N; i++) {
6580            PackageParser.Activity a = pkg.activities.get(i);
6581            mActivities.removeActivity(a, "activity");
6582            if (DEBUG_REMOVE && chatty) {
6583                if (r == null) {
6584                    r = new StringBuilder(256);
6585                } else {
6586                    r.append(' ');
6587                }
6588                r.append(a.info.name);
6589            }
6590        }
6591        if (r != null) {
6592            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6593        }
6594
6595        N = pkg.permissions.size();
6596        r = null;
6597        for (i=0; i<N; i++) {
6598            PackageParser.Permission p = pkg.permissions.get(i);
6599            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6600            if (bp == null) {
6601                bp = mSettings.mPermissionTrees.get(p.info.name);
6602            }
6603            if (bp != null && bp.perm == p) {
6604                bp.perm = null;
6605                if (DEBUG_REMOVE && chatty) {
6606                    if (r == null) {
6607                        r = new StringBuilder(256);
6608                    } else {
6609                        r.append(' ');
6610                    }
6611                    r.append(p.info.name);
6612                }
6613            }
6614            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6615                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6616                if (appOpPerms != null) {
6617                    appOpPerms.remove(pkg.packageName);
6618                }
6619            }
6620        }
6621        if (r != null) {
6622            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6623        }
6624
6625        N = pkg.requestedPermissions.size();
6626        r = null;
6627        for (i=0; i<N; i++) {
6628            String perm = pkg.requestedPermissions.get(i);
6629            BasePermission bp = mSettings.mPermissions.get(perm);
6630            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6631                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6632                if (appOpPerms != null) {
6633                    appOpPerms.remove(pkg.packageName);
6634                    if (appOpPerms.isEmpty()) {
6635                        mAppOpPermissionPackages.remove(perm);
6636                    }
6637                }
6638            }
6639        }
6640        if (r != null) {
6641            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6642        }
6643
6644        N = pkg.instrumentation.size();
6645        r = null;
6646        for (i=0; i<N; i++) {
6647            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6648            mInstrumentation.remove(a.getComponentName());
6649            if (DEBUG_REMOVE && chatty) {
6650                if (r == null) {
6651                    r = new StringBuilder(256);
6652                } else {
6653                    r.append(' ');
6654                }
6655                r.append(a.info.name);
6656            }
6657        }
6658        if (r != null) {
6659            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6660        }
6661
6662        r = null;
6663        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6664            // Only system apps can hold shared libraries.
6665            if (pkg.libraryNames != null) {
6666                for (i=0; i<pkg.libraryNames.size(); i++) {
6667                    String name = pkg.libraryNames.get(i);
6668                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6669                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6670                        mSharedLibraries.remove(name);
6671                        if (DEBUG_REMOVE && chatty) {
6672                            if (r == null) {
6673                                r = new StringBuilder(256);
6674                            } else {
6675                                r.append(' ');
6676                            }
6677                            r.append(name);
6678                        }
6679                    }
6680                }
6681            }
6682        }
6683        if (r != null) {
6684            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6685        }
6686    }
6687
6688    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6689        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6690            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6691                return true;
6692            }
6693        }
6694        return false;
6695    }
6696
6697    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6698    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6699    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6700
6701    private void updatePermissionsLPw(String changingPkg,
6702            PackageParser.Package pkgInfo, int flags) {
6703        // Make sure there are no dangling permission trees.
6704        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6705        while (it.hasNext()) {
6706            final BasePermission bp = it.next();
6707            if (bp.packageSetting == null) {
6708                // We may not yet have parsed the package, so just see if
6709                // we still know about its settings.
6710                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6711            }
6712            if (bp.packageSetting == null) {
6713                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6714                        + " from package " + bp.sourcePackage);
6715                it.remove();
6716            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6717                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6718                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6719                            + " from package " + bp.sourcePackage);
6720                    flags |= UPDATE_PERMISSIONS_ALL;
6721                    it.remove();
6722                }
6723            }
6724        }
6725
6726        // Make sure all dynamic permissions have been assigned to a package,
6727        // and make sure there are no dangling permissions.
6728        it = mSettings.mPermissions.values().iterator();
6729        while (it.hasNext()) {
6730            final BasePermission bp = it.next();
6731            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6732                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6733                        + bp.name + " pkg=" + bp.sourcePackage
6734                        + " info=" + bp.pendingInfo);
6735                if (bp.packageSetting == null && bp.pendingInfo != null) {
6736                    final BasePermission tree = findPermissionTreeLP(bp.name);
6737                    if (tree != null && tree.perm != null) {
6738                        bp.packageSetting = tree.packageSetting;
6739                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6740                                new PermissionInfo(bp.pendingInfo));
6741                        bp.perm.info.packageName = tree.perm.info.packageName;
6742                        bp.perm.info.name = bp.name;
6743                        bp.uid = tree.uid;
6744                    }
6745                }
6746            }
6747            if (bp.packageSetting == null) {
6748                // We may not yet have parsed the package, so just see if
6749                // we still know about its settings.
6750                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6751            }
6752            if (bp.packageSetting == null) {
6753                Slog.w(TAG, "Removing dangling permission: " + bp.name
6754                        + " from package " + bp.sourcePackage);
6755                it.remove();
6756            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6757                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6758                    Slog.i(TAG, "Removing old permission: " + bp.name
6759                            + " from package " + bp.sourcePackage);
6760                    flags |= UPDATE_PERMISSIONS_ALL;
6761                    it.remove();
6762                }
6763            }
6764        }
6765
6766        // Now update the permissions for all packages, in particular
6767        // replace the granted permissions of the system packages.
6768        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6769            for (PackageParser.Package pkg : mPackages.values()) {
6770                if (pkg != pkgInfo) {
6771                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6772                }
6773            }
6774        }
6775
6776        if (pkgInfo != null) {
6777            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6778        }
6779    }
6780
6781    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6782        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6783        if (ps == null) {
6784            return;
6785        }
6786        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6787        HashSet<String> origPermissions = gp.grantedPermissions;
6788        boolean changedPermission = false;
6789
6790        if (replace) {
6791            ps.permissionsFixed = false;
6792            if (gp == ps) {
6793                origPermissions = new HashSet<String>(gp.grantedPermissions);
6794                gp.grantedPermissions.clear();
6795                gp.gids = mGlobalGids;
6796            }
6797        }
6798
6799        if (gp.gids == null) {
6800            gp.gids = mGlobalGids;
6801        }
6802
6803        final int N = pkg.requestedPermissions.size();
6804        for (int i=0; i<N; i++) {
6805            final String name = pkg.requestedPermissions.get(i);
6806            final boolean required = pkg.requestedPermissionsRequired.get(i);
6807            final BasePermission bp = mSettings.mPermissions.get(name);
6808            if (DEBUG_INSTALL) {
6809                if (gp != ps) {
6810                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6811                }
6812            }
6813
6814            if (bp == null || bp.packageSetting == null) {
6815                Slog.w(TAG, "Unknown permission " + name
6816                        + " in package " + pkg.packageName);
6817                continue;
6818            }
6819
6820            final String perm = bp.name;
6821            boolean allowed;
6822            boolean allowedSig = false;
6823            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6824                // Keep track of app op permissions.
6825                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6826                if (pkgs == null) {
6827                    pkgs = new ArraySet<>();
6828                    mAppOpPermissionPackages.put(bp.name, pkgs);
6829                }
6830                pkgs.add(pkg.packageName);
6831            }
6832            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6833            if (level == PermissionInfo.PROTECTION_NORMAL
6834                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6835                // We grant a normal or dangerous permission if any of the following
6836                // are true:
6837                // 1) The permission is required
6838                // 2) The permission is optional, but was granted in the past
6839                // 3) The permission is optional, but was requested by an
6840                //    app in /system (not /data)
6841                //
6842                // Otherwise, reject the permission.
6843                allowed = (required || origPermissions.contains(perm)
6844                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6845            } else if (bp.packageSetting == null) {
6846                // This permission is invalid; skip it.
6847                allowed = false;
6848            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6849                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6850                if (allowed) {
6851                    allowedSig = true;
6852                }
6853            } else {
6854                allowed = false;
6855            }
6856            if (DEBUG_INSTALL) {
6857                if (gp != ps) {
6858                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6859                }
6860            }
6861            if (allowed) {
6862                if (!isSystemApp(ps) && ps.permissionsFixed) {
6863                    // If this is an existing, non-system package, then
6864                    // we can't add any new permissions to it.
6865                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6866                        // Except...  if this is a permission that was added
6867                        // to the platform (note: need to only do this when
6868                        // updating the platform).
6869                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6870                    }
6871                }
6872                if (allowed) {
6873                    if (!gp.grantedPermissions.contains(perm)) {
6874                        changedPermission = true;
6875                        gp.grantedPermissions.add(perm);
6876                        gp.gids = appendInts(gp.gids, bp.gids);
6877                    } else if (!ps.haveGids) {
6878                        gp.gids = appendInts(gp.gids, bp.gids);
6879                    }
6880                } else {
6881                    Slog.w(TAG, "Not granting permission " + perm
6882                            + " to package " + pkg.packageName
6883                            + " because it was previously installed without");
6884                }
6885            } else {
6886                if (gp.grantedPermissions.remove(perm)) {
6887                    changedPermission = true;
6888                    gp.gids = removeInts(gp.gids, bp.gids);
6889                    Slog.i(TAG, "Un-granting permission " + perm
6890                            + " from package " + pkg.packageName
6891                            + " (protectionLevel=" + bp.protectionLevel
6892                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6893                            + ")");
6894                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6895                    // Don't print warning for app op permissions, since it is fine for them
6896                    // not to be granted, there is a UI for the user to decide.
6897                    Slog.w(TAG, "Not granting permission " + perm
6898                            + " to package " + pkg.packageName
6899                            + " (protectionLevel=" + bp.protectionLevel
6900                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6901                            + ")");
6902                }
6903            }
6904        }
6905
6906        if ((changedPermission || replace) && !ps.permissionsFixed &&
6907                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6908            // This is the first that we have heard about this package, so the
6909            // permissions we have now selected are fixed until explicitly
6910            // changed.
6911            ps.permissionsFixed = true;
6912        }
6913        ps.haveGids = true;
6914    }
6915
6916    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6917        boolean allowed = false;
6918        final int NP = PackageParser.NEW_PERMISSIONS.length;
6919        for (int ip=0; ip<NP; ip++) {
6920            final PackageParser.NewPermissionInfo npi
6921                    = PackageParser.NEW_PERMISSIONS[ip];
6922            if (npi.name.equals(perm)
6923                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6924                allowed = true;
6925                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6926                        + pkg.packageName);
6927                break;
6928            }
6929        }
6930        return allowed;
6931    }
6932
6933    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6934                                          BasePermission bp, HashSet<String> origPermissions) {
6935        boolean allowed;
6936        allowed = (compareSignatures(
6937                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6938                        == PackageManager.SIGNATURE_MATCH)
6939                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6940                        == PackageManager.SIGNATURE_MATCH);
6941        if (!allowed && (bp.protectionLevel
6942                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6943            if (isSystemApp(pkg)) {
6944                // For updated system applications, a system permission
6945                // is granted only if it had been defined by the original application.
6946                if (isUpdatedSystemApp(pkg)) {
6947                    final PackageSetting sysPs = mSettings
6948                            .getDisabledSystemPkgLPr(pkg.packageName);
6949                    final GrantedPermissions origGp = sysPs.sharedUser != null
6950                            ? sysPs.sharedUser : sysPs;
6951
6952                    if (origGp.grantedPermissions.contains(perm)) {
6953                        // If the original was granted this permission, we take
6954                        // that grant decision as read and propagate it to the
6955                        // update.
6956                        allowed = true;
6957                    } else {
6958                        // The system apk may have been updated with an older
6959                        // version of the one on the data partition, but which
6960                        // granted a new system permission that it didn't have
6961                        // before.  In this case we do want to allow the app to
6962                        // now get the new permission if the ancestral apk is
6963                        // privileged to get it.
6964                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6965                            for (int j=0;
6966                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6967                                if (perm.equals(
6968                                        sysPs.pkg.requestedPermissions.get(j))) {
6969                                    allowed = true;
6970                                    break;
6971                                }
6972                            }
6973                        }
6974                    }
6975                } else {
6976                    allowed = isPrivilegedApp(pkg);
6977                }
6978            }
6979        }
6980        if (!allowed && (bp.protectionLevel
6981                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6982            // For development permissions, a development permission
6983            // is granted only if it was already granted.
6984            allowed = origPermissions.contains(perm);
6985        }
6986        return allowed;
6987    }
6988
6989    final class ActivityIntentResolver
6990            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6991        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6992                boolean defaultOnly, int userId) {
6993            if (!sUserManager.exists(userId)) return null;
6994            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6995            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6996        }
6997
6998        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6999                int userId) {
7000            if (!sUserManager.exists(userId)) return null;
7001            mFlags = flags;
7002            return super.queryIntent(intent, resolvedType,
7003                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7004        }
7005
7006        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7007                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7008            if (!sUserManager.exists(userId)) return null;
7009            if (packageActivities == null) {
7010                return null;
7011            }
7012            mFlags = flags;
7013            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7014            final int N = packageActivities.size();
7015            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7016                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7017
7018            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7019            for (int i = 0; i < N; ++i) {
7020                intentFilters = packageActivities.get(i).intents;
7021                if (intentFilters != null && intentFilters.size() > 0) {
7022                    PackageParser.ActivityIntentInfo[] array =
7023                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7024                    intentFilters.toArray(array);
7025                    listCut.add(array);
7026                }
7027            }
7028            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7029        }
7030
7031        public final void addActivity(PackageParser.Activity a, String type) {
7032            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7033            mActivities.put(a.getComponentName(), a);
7034            if (DEBUG_SHOW_INFO)
7035                Log.v(
7036                TAG, "  " + type + " " +
7037                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7038            if (DEBUG_SHOW_INFO)
7039                Log.v(TAG, "    Class=" + a.info.name);
7040            final int NI = a.intents.size();
7041            for (int j=0; j<NI; j++) {
7042                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7043                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7044                    intent.setPriority(0);
7045                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7046                            + a.className + " with priority > 0, forcing to 0");
7047                }
7048                if (DEBUG_SHOW_INFO) {
7049                    Log.v(TAG, "    IntentFilter:");
7050                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7051                }
7052                if (!intent.debugCheck()) {
7053                    Log.w(TAG, "==> For Activity " + a.info.name);
7054                }
7055                addFilter(intent);
7056            }
7057        }
7058
7059        public final void removeActivity(PackageParser.Activity a, String type) {
7060            mActivities.remove(a.getComponentName());
7061            if (DEBUG_SHOW_INFO) {
7062                Log.v(TAG, "  " + type + " "
7063                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7064                                : a.info.name) + ":");
7065                Log.v(TAG, "    Class=" + a.info.name);
7066            }
7067            final int NI = a.intents.size();
7068            for (int j=0; j<NI; j++) {
7069                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7070                if (DEBUG_SHOW_INFO) {
7071                    Log.v(TAG, "    IntentFilter:");
7072                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7073                }
7074                removeFilter(intent);
7075            }
7076        }
7077
7078        @Override
7079        protected boolean allowFilterResult(
7080                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7081            ActivityInfo filterAi = filter.activity.info;
7082            for (int i=dest.size()-1; i>=0; i--) {
7083                ActivityInfo destAi = dest.get(i).activityInfo;
7084                if (destAi.name == filterAi.name
7085                        && destAi.packageName == filterAi.packageName) {
7086                    return false;
7087                }
7088            }
7089            return true;
7090        }
7091
7092        @Override
7093        protected ActivityIntentInfo[] newArray(int size) {
7094            return new ActivityIntentInfo[size];
7095        }
7096
7097        @Override
7098        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7099            if (!sUserManager.exists(userId)) return true;
7100            PackageParser.Package p = filter.activity.owner;
7101            if (p != null) {
7102                PackageSetting ps = (PackageSetting)p.mExtras;
7103                if (ps != null) {
7104                    // System apps are never considered stopped for purposes of
7105                    // filtering, because there may be no way for the user to
7106                    // actually re-launch them.
7107                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7108                            && ps.getStopped(userId);
7109                }
7110            }
7111            return false;
7112        }
7113
7114        @Override
7115        protected boolean isPackageForFilter(String packageName,
7116                PackageParser.ActivityIntentInfo info) {
7117            return packageName.equals(info.activity.owner.packageName);
7118        }
7119
7120        @Override
7121        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7122                int match, int userId) {
7123            if (!sUserManager.exists(userId)) return null;
7124            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7125                return null;
7126            }
7127            final PackageParser.Activity activity = info.activity;
7128            if (mSafeMode && (activity.info.applicationInfo.flags
7129                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7130                return null;
7131            }
7132            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7133            if (ps == null) {
7134                return null;
7135            }
7136            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7137                    ps.readUserState(userId), userId);
7138            if (ai == null) {
7139                return null;
7140            }
7141            final ResolveInfo res = new ResolveInfo();
7142            res.activityInfo = ai;
7143            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7144                res.filter = info;
7145            }
7146            res.priority = info.getPriority();
7147            res.preferredOrder = activity.owner.mPreferredOrder;
7148            //System.out.println("Result: " + res.activityInfo.className +
7149            //                   " = " + res.priority);
7150            res.match = match;
7151            res.isDefault = info.hasDefault;
7152            res.labelRes = info.labelRes;
7153            res.nonLocalizedLabel = info.nonLocalizedLabel;
7154            if (userNeedsBadging(userId)) {
7155                res.noResourceId = true;
7156            } else {
7157                res.icon = info.icon;
7158            }
7159            res.system = isSystemApp(res.activityInfo.applicationInfo);
7160            return res;
7161        }
7162
7163        @Override
7164        protected void sortResults(List<ResolveInfo> results) {
7165            Collections.sort(results, mResolvePrioritySorter);
7166        }
7167
7168        @Override
7169        protected void dumpFilter(PrintWriter out, String prefix,
7170                PackageParser.ActivityIntentInfo filter) {
7171            out.print(prefix); out.print(
7172                    Integer.toHexString(System.identityHashCode(filter.activity)));
7173                    out.print(' ');
7174                    filter.activity.printComponentShortName(out);
7175                    out.print(" filter ");
7176                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7177        }
7178
7179//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7180//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7181//            final List<ResolveInfo> retList = Lists.newArrayList();
7182//            while (i.hasNext()) {
7183//                final ResolveInfo resolveInfo = i.next();
7184//                if (isEnabledLP(resolveInfo.activityInfo)) {
7185//                    retList.add(resolveInfo);
7186//                }
7187//            }
7188//            return retList;
7189//        }
7190
7191        // Keys are String (activity class name), values are Activity.
7192        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7193                = new HashMap<ComponentName, PackageParser.Activity>();
7194        private int mFlags;
7195    }
7196
7197    private final class ServiceIntentResolver
7198            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7199        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7200                boolean defaultOnly, int userId) {
7201            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7202            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7203        }
7204
7205        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7206                int userId) {
7207            if (!sUserManager.exists(userId)) return null;
7208            mFlags = flags;
7209            return super.queryIntent(intent, resolvedType,
7210                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7211        }
7212
7213        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7214                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7215            if (!sUserManager.exists(userId)) return null;
7216            if (packageServices == null) {
7217                return null;
7218            }
7219            mFlags = flags;
7220            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7221            final int N = packageServices.size();
7222            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7223                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7224
7225            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7226            for (int i = 0; i < N; ++i) {
7227                intentFilters = packageServices.get(i).intents;
7228                if (intentFilters != null && intentFilters.size() > 0) {
7229                    PackageParser.ServiceIntentInfo[] array =
7230                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7231                    intentFilters.toArray(array);
7232                    listCut.add(array);
7233                }
7234            }
7235            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7236        }
7237
7238        public final void addService(PackageParser.Service s) {
7239            mServices.put(s.getComponentName(), s);
7240            if (DEBUG_SHOW_INFO) {
7241                Log.v(TAG, "  "
7242                        + (s.info.nonLocalizedLabel != null
7243                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7244                Log.v(TAG, "    Class=" + s.info.name);
7245            }
7246            final int NI = s.intents.size();
7247            int j;
7248            for (j=0; j<NI; j++) {
7249                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7250                if (DEBUG_SHOW_INFO) {
7251                    Log.v(TAG, "    IntentFilter:");
7252                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7253                }
7254                if (!intent.debugCheck()) {
7255                    Log.w(TAG, "==> For Service " + s.info.name);
7256                }
7257                addFilter(intent);
7258            }
7259        }
7260
7261        public final void removeService(PackageParser.Service s) {
7262            mServices.remove(s.getComponentName());
7263            if (DEBUG_SHOW_INFO) {
7264                Log.v(TAG, "  " + (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                removeFilter(intent);
7277            }
7278        }
7279
7280        @Override
7281        protected boolean allowFilterResult(
7282                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7283            ServiceInfo filterSi = filter.service.info;
7284            for (int i=dest.size()-1; i>=0; i--) {
7285                ServiceInfo destAi = dest.get(i).serviceInfo;
7286                if (destAi.name == filterSi.name
7287                        && destAi.packageName == filterSi.packageName) {
7288                    return false;
7289                }
7290            }
7291            return true;
7292        }
7293
7294        @Override
7295        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7296            return new PackageParser.ServiceIntentInfo[size];
7297        }
7298
7299        @Override
7300        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7301            if (!sUserManager.exists(userId)) return true;
7302            PackageParser.Package p = filter.service.owner;
7303            if (p != null) {
7304                PackageSetting ps = (PackageSetting)p.mExtras;
7305                if (ps != null) {
7306                    // System apps are never considered stopped for purposes of
7307                    // filtering, because there may be no way for the user to
7308                    // actually re-launch them.
7309                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7310                            && ps.getStopped(userId);
7311                }
7312            }
7313            return false;
7314        }
7315
7316        @Override
7317        protected boolean isPackageForFilter(String packageName,
7318                PackageParser.ServiceIntentInfo info) {
7319            return packageName.equals(info.service.owner.packageName);
7320        }
7321
7322        @Override
7323        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7324                int match, int userId) {
7325            if (!sUserManager.exists(userId)) return null;
7326            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7327            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7328                return null;
7329            }
7330            final PackageParser.Service service = info.service;
7331            if (mSafeMode && (service.info.applicationInfo.flags
7332                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7333                return null;
7334            }
7335            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7336            if (ps == null) {
7337                return null;
7338            }
7339            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7340                    ps.readUserState(userId), userId);
7341            if (si == null) {
7342                return null;
7343            }
7344            final ResolveInfo res = new ResolveInfo();
7345            res.serviceInfo = si;
7346            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7347                res.filter = filter;
7348            }
7349            res.priority = info.getPriority();
7350            res.preferredOrder = service.owner.mPreferredOrder;
7351            //System.out.println("Result: " + res.activityInfo.className +
7352            //                   " = " + res.priority);
7353            res.match = match;
7354            res.isDefault = info.hasDefault;
7355            res.labelRes = info.labelRes;
7356            res.nonLocalizedLabel = info.nonLocalizedLabel;
7357            res.icon = info.icon;
7358            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7359            return res;
7360        }
7361
7362        @Override
7363        protected void sortResults(List<ResolveInfo> results) {
7364            Collections.sort(results, mResolvePrioritySorter);
7365        }
7366
7367        @Override
7368        protected void dumpFilter(PrintWriter out, String prefix,
7369                PackageParser.ServiceIntentInfo filter) {
7370            out.print(prefix); out.print(
7371                    Integer.toHexString(System.identityHashCode(filter.service)));
7372                    out.print(' ');
7373                    filter.service.printComponentShortName(out);
7374                    out.print(" filter ");
7375                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7376        }
7377
7378//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7379//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7380//            final List<ResolveInfo> retList = Lists.newArrayList();
7381//            while (i.hasNext()) {
7382//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7383//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7384//                    retList.add(resolveInfo);
7385//                }
7386//            }
7387//            return retList;
7388//        }
7389
7390        // Keys are String (activity class name), values are Activity.
7391        private final HashMap<ComponentName, PackageParser.Service> mServices
7392                = new HashMap<ComponentName, PackageParser.Service>();
7393        private int mFlags;
7394    };
7395
7396    private final class ProviderIntentResolver
7397            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7398        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7399                boolean defaultOnly, int userId) {
7400            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7401            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7402        }
7403
7404        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7405                int userId) {
7406            if (!sUserManager.exists(userId))
7407                return null;
7408            mFlags = flags;
7409            return super.queryIntent(intent, resolvedType,
7410                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7411        }
7412
7413        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7414                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7415            if (!sUserManager.exists(userId))
7416                return null;
7417            if (packageProviders == null) {
7418                return null;
7419            }
7420            mFlags = flags;
7421            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7422            final int N = packageProviders.size();
7423            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7424                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7425
7426            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7427            for (int i = 0; i < N; ++i) {
7428                intentFilters = packageProviders.get(i).intents;
7429                if (intentFilters != null && intentFilters.size() > 0) {
7430                    PackageParser.ProviderIntentInfo[] array =
7431                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7432                    intentFilters.toArray(array);
7433                    listCut.add(array);
7434                }
7435            }
7436            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7437        }
7438
7439        public final void addProvider(PackageParser.Provider p) {
7440            if (mProviders.containsKey(p.getComponentName())) {
7441                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7442                return;
7443            }
7444
7445            mProviders.put(p.getComponentName(), p);
7446            if (DEBUG_SHOW_INFO) {
7447                Log.v(TAG, "  "
7448                        + (p.info.nonLocalizedLabel != null
7449                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7450                Log.v(TAG, "    Class=" + p.info.name);
7451            }
7452            final int NI = p.intents.size();
7453            int j;
7454            for (j = 0; j < NI; j++) {
7455                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7456                if (DEBUG_SHOW_INFO) {
7457                    Log.v(TAG, "    IntentFilter:");
7458                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7459                }
7460                if (!intent.debugCheck()) {
7461                    Log.w(TAG, "==> For Provider " + p.info.name);
7462                }
7463                addFilter(intent);
7464            }
7465        }
7466
7467        public final void removeProvider(PackageParser.Provider p) {
7468            mProviders.remove(p.getComponentName());
7469            if (DEBUG_SHOW_INFO) {
7470                Log.v(TAG, "  " + (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                removeFilter(intent);
7483            }
7484        }
7485
7486        @Override
7487        protected boolean allowFilterResult(
7488                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7489            ProviderInfo filterPi = filter.provider.info;
7490            for (int i = dest.size() - 1; i >= 0; i--) {
7491                ProviderInfo destPi = dest.get(i).providerInfo;
7492                if (destPi.name == filterPi.name
7493                        && destPi.packageName == filterPi.packageName) {
7494                    return false;
7495                }
7496            }
7497            return true;
7498        }
7499
7500        @Override
7501        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7502            return new PackageParser.ProviderIntentInfo[size];
7503        }
7504
7505        @Override
7506        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7507            if (!sUserManager.exists(userId))
7508                return true;
7509            PackageParser.Package p = filter.provider.owner;
7510            if (p != null) {
7511                PackageSetting ps = (PackageSetting) p.mExtras;
7512                if (ps != null) {
7513                    // System apps are never considered stopped for purposes of
7514                    // filtering, because there may be no way for the user to
7515                    // actually re-launch them.
7516                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7517                            && ps.getStopped(userId);
7518                }
7519            }
7520            return false;
7521        }
7522
7523        @Override
7524        protected boolean isPackageForFilter(String packageName,
7525                PackageParser.ProviderIntentInfo info) {
7526            return packageName.equals(info.provider.owner.packageName);
7527        }
7528
7529        @Override
7530        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7531                int match, int userId) {
7532            if (!sUserManager.exists(userId))
7533                return null;
7534            final PackageParser.ProviderIntentInfo info = filter;
7535            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7536                return null;
7537            }
7538            final PackageParser.Provider provider = info.provider;
7539            if (mSafeMode && (provider.info.applicationInfo.flags
7540                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7541                return null;
7542            }
7543            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7544            if (ps == null) {
7545                return null;
7546            }
7547            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7548                    ps.readUserState(userId), userId);
7549            if (pi == null) {
7550                return null;
7551            }
7552            final ResolveInfo res = new ResolveInfo();
7553            res.providerInfo = pi;
7554            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7555                res.filter = filter;
7556            }
7557            res.priority = info.getPriority();
7558            res.preferredOrder = provider.owner.mPreferredOrder;
7559            res.match = match;
7560            res.isDefault = info.hasDefault;
7561            res.labelRes = info.labelRes;
7562            res.nonLocalizedLabel = info.nonLocalizedLabel;
7563            res.icon = info.icon;
7564            res.system = isSystemApp(res.providerInfo.applicationInfo);
7565            return res;
7566        }
7567
7568        @Override
7569        protected void sortResults(List<ResolveInfo> results) {
7570            Collections.sort(results, mResolvePrioritySorter);
7571        }
7572
7573        @Override
7574        protected void dumpFilter(PrintWriter out, String prefix,
7575                PackageParser.ProviderIntentInfo filter) {
7576            out.print(prefix);
7577            out.print(
7578                    Integer.toHexString(System.identityHashCode(filter.provider)));
7579            out.print(' ');
7580            filter.provider.printComponentShortName(out);
7581            out.print(" filter ");
7582            out.println(Integer.toHexString(System.identityHashCode(filter)));
7583        }
7584
7585        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7586                = new HashMap<ComponentName, PackageParser.Provider>();
7587        private int mFlags;
7588    };
7589
7590    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7591            new Comparator<ResolveInfo>() {
7592        public int compare(ResolveInfo r1, ResolveInfo r2) {
7593            int v1 = r1.priority;
7594            int v2 = r2.priority;
7595            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7596            if (v1 != v2) {
7597                return (v1 > v2) ? -1 : 1;
7598            }
7599            v1 = r1.preferredOrder;
7600            v2 = r2.preferredOrder;
7601            if (v1 != v2) {
7602                return (v1 > v2) ? -1 : 1;
7603            }
7604            if (r1.isDefault != r2.isDefault) {
7605                return r1.isDefault ? -1 : 1;
7606            }
7607            v1 = r1.match;
7608            v2 = r2.match;
7609            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7610            if (v1 != v2) {
7611                return (v1 > v2) ? -1 : 1;
7612            }
7613            if (r1.system != r2.system) {
7614                return r1.system ? -1 : 1;
7615            }
7616            return 0;
7617        }
7618    };
7619
7620    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7621            new Comparator<ProviderInfo>() {
7622        public int compare(ProviderInfo p1, ProviderInfo p2) {
7623            final int v1 = p1.initOrder;
7624            final int v2 = p2.initOrder;
7625            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7626        }
7627    };
7628
7629    static final void sendPackageBroadcast(String action, String pkg,
7630            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7631            int[] userIds) {
7632        IActivityManager am = ActivityManagerNative.getDefault();
7633        if (am != null) {
7634            try {
7635                if (userIds == null) {
7636                    userIds = am.getRunningUserIds();
7637                }
7638                for (int id : userIds) {
7639                    final Intent intent = new Intent(action,
7640                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7641                    if (extras != null) {
7642                        intent.putExtras(extras);
7643                    }
7644                    if (targetPkg != null) {
7645                        intent.setPackage(targetPkg);
7646                    }
7647                    // Modify the UID when posting to other users
7648                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7649                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7650                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7651                        intent.putExtra(Intent.EXTRA_UID, uid);
7652                    }
7653                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7654                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7655                    if (DEBUG_BROADCASTS) {
7656                        RuntimeException here = new RuntimeException("here");
7657                        here.fillInStackTrace();
7658                        Slog.d(TAG, "Sending to user " + id + ": "
7659                                + intent.toShortString(false, true, false, false)
7660                                + " " + intent.getExtras(), here);
7661                    }
7662                    am.broadcastIntent(null, intent, null, finishedReceiver,
7663                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7664                            finishedReceiver != null, false, id);
7665                }
7666            } catch (RemoteException ex) {
7667            }
7668        }
7669    }
7670
7671    /**
7672     * Check if the external storage media is available. This is true if there
7673     * is a mounted external storage medium or if the external storage is
7674     * emulated.
7675     */
7676    private boolean isExternalMediaAvailable() {
7677        return mMediaMounted || Environment.isExternalStorageEmulated();
7678    }
7679
7680    @Override
7681    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7682        // writer
7683        synchronized (mPackages) {
7684            if (!isExternalMediaAvailable()) {
7685                // If the external storage is no longer mounted at this point,
7686                // the caller may not have been able to delete all of this
7687                // packages files and can not delete any more.  Bail.
7688                return null;
7689            }
7690            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7691            if (lastPackage != null) {
7692                pkgs.remove(lastPackage);
7693            }
7694            if (pkgs.size() > 0) {
7695                return pkgs.get(0);
7696            }
7697        }
7698        return null;
7699    }
7700
7701    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7702        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7703                userId, andCode ? 1 : 0, packageName);
7704        if (mSystemReady) {
7705            msg.sendToTarget();
7706        } else {
7707            if (mPostSystemReadyMessages == null) {
7708                mPostSystemReadyMessages = new ArrayList<>();
7709            }
7710            mPostSystemReadyMessages.add(msg);
7711        }
7712    }
7713
7714    void startCleaningPackages() {
7715        // reader
7716        synchronized (mPackages) {
7717            if (!isExternalMediaAvailable()) {
7718                return;
7719            }
7720            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7721                return;
7722            }
7723        }
7724        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7725        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7726        IActivityManager am = ActivityManagerNative.getDefault();
7727        if (am != null) {
7728            try {
7729                am.startService(null, intent, null, UserHandle.USER_OWNER);
7730            } catch (RemoteException e) {
7731            }
7732        }
7733    }
7734
7735    @Override
7736    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7737            int installFlags, String installerPackageName, VerificationParams verificationParams,
7738            String packageAbiOverride) {
7739        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7740                packageAbiOverride, UserHandle.getCallingUserId());
7741    }
7742
7743    @Override
7744    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7745            int installFlags, String installerPackageName, VerificationParams verificationParams,
7746            String packageAbiOverride, int userId) {
7747        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7748                null);
7749        if (UserHandle.getCallingUserId() != userId) {
7750            mContext.enforceCallingOrSelfPermission(
7751                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7752                    "installPackage " + userId);
7753        }
7754
7755        final File originFile = new File(originPath);
7756        final int uid = Binder.getCallingUid();
7757        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7758            try {
7759                if (observer != null) {
7760                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7761                }
7762            } catch (RemoteException re) {
7763            }
7764            return;
7765        }
7766
7767        UserHandle user;
7768        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7769            user = UserHandle.ALL;
7770        } else {
7771            user = new UserHandle(userId);
7772        }
7773
7774        final int filteredInstallFlags;
7775        if (uid == Process.SHELL_UID || uid == 0) {
7776            if (DEBUG_INSTALL) {
7777                Slog.v(TAG, "Install from ADB");
7778            }
7779            filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB;
7780        } else {
7781            filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB;
7782        }
7783
7784        verificationParams.setInstallerUid(uid);
7785
7786        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7787
7788        final Message msg = mHandler.obtainMessage(INIT_COPY);
7789        msg.obj = new InstallParams(origin, observer, filteredInstallFlags,
7790                installerPackageName, verificationParams, user, packageAbiOverride);
7791        mHandler.sendMessage(msg);
7792    }
7793
7794    void installStage(String packageName, File stagedDir, String stagedCid,
7795            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7796            String installerPackageName, int installerUid, UserHandle user) {
7797        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7798                params.referrerUri, installerUid, null);
7799
7800        final OriginInfo origin;
7801        if (stagedDir != null) {
7802            origin = OriginInfo.fromStagedFile(stagedDir);
7803        } else {
7804            origin = OriginInfo.fromStagedContainer(stagedCid);
7805        }
7806
7807        final Message msg = mHandler.obtainMessage(INIT_COPY);
7808        msg.obj = new InstallParams(origin, observer, params.installFlags,
7809                installerPackageName, verifParams, user, params.abiOverride);
7810        mHandler.sendMessage(msg);
7811    }
7812
7813    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7814        Bundle extras = new Bundle(1);
7815        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7816
7817        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7818                packageName, extras, null, null, new int[] {userId});
7819        try {
7820            IActivityManager am = ActivityManagerNative.getDefault();
7821            final boolean isSystem =
7822                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7823            if (isSystem && am.isUserRunning(userId, false)) {
7824                // The just-installed/enabled app is bundled on the system, so presumed
7825                // to be able to run automatically without needing an explicit launch.
7826                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7827                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7828                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7829                        .setPackage(packageName);
7830                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7831                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7832            }
7833        } catch (RemoteException e) {
7834            // shouldn't happen
7835            Slog.w(TAG, "Unable to bootstrap installed package", e);
7836        }
7837    }
7838
7839    @Override
7840    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7841            int userId) {
7842        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7843        PackageSetting pkgSetting;
7844        final int uid = Binder.getCallingUid();
7845        if (UserHandle.getUserId(uid) != userId) {
7846            mContext.enforceCallingOrSelfPermission(
7847                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7848                    "setApplicationHiddenSetting for user " + userId);
7849        }
7850
7851        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7852            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7853            return false;
7854        }
7855
7856        long callingId = Binder.clearCallingIdentity();
7857        try {
7858            boolean sendAdded = false;
7859            boolean sendRemoved = false;
7860            // writer
7861            synchronized (mPackages) {
7862                pkgSetting = mSettings.mPackages.get(packageName);
7863                if (pkgSetting == null) {
7864                    return false;
7865                }
7866                if (pkgSetting.getHidden(userId) != hidden) {
7867                    pkgSetting.setHidden(hidden, userId);
7868                    mSettings.writePackageRestrictionsLPr(userId);
7869                    if (hidden) {
7870                        sendRemoved = true;
7871                    } else {
7872                        sendAdded = true;
7873                    }
7874                }
7875            }
7876            if (sendAdded) {
7877                sendPackageAddedForUser(packageName, pkgSetting, userId);
7878                return true;
7879            }
7880            if (sendRemoved) {
7881                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7882                        "hiding pkg");
7883                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7884            }
7885        } finally {
7886            Binder.restoreCallingIdentity(callingId);
7887        }
7888        return false;
7889    }
7890
7891    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7892            int userId) {
7893        final PackageRemovedInfo info = new PackageRemovedInfo();
7894        info.removedPackage = packageName;
7895        info.removedUsers = new int[] {userId};
7896        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7897        info.sendBroadcast(false, false, false);
7898    }
7899
7900    /**
7901     * Returns true if application is not found or there was an error. Otherwise it returns
7902     * the hidden state of the package for the given user.
7903     */
7904    @Override
7905    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7906        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7907        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7908                "getApplicationHidden for user " + userId);
7909        PackageSetting pkgSetting;
7910        long callingId = Binder.clearCallingIdentity();
7911        try {
7912            // writer
7913            synchronized (mPackages) {
7914                pkgSetting = mSettings.mPackages.get(packageName);
7915                if (pkgSetting == null) {
7916                    return true;
7917                }
7918                return pkgSetting.getHidden(userId);
7919            }
7920        } finally {
7921            Binder.restoreCallingIdentity(callingId);
7922        }
7923    }
7924
7925    /**
7926     * @hide
7927     */
7928    @Override
7929    public int installExistingPackageAsUser(String packageName, int userId) {
7930        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7931                null);
7932        PackageSetting pkgSetting;
7933        final int uid = Binder.getCallingUid();
7934        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7935        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7936            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7937        }
7938
7939        long callingId = Binder.clearCallingIdentity();
7940        try {
7941            boolean sendAdded = false;
7942            Bundle extras = new Bundle(1);
7943
7944            // writer
7945            synchronized (mPackages) {
7946                pkgSetting = mSettings.mPackages.get(packageName);
7947                if (pkgSetting == null) {
7948                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7949                }
7950                if (!pkgSetting.getInstalled(userId)) {
7951                    pkgSetting.setInstalled(true, userId);
7952                    pkgSetting.setHidden(false, userId);
7953                    mSettings.writePackageRestrictionsLPr(userId);
7954                    sendAdded = true;
7955                }
7956            }
7957
7958            if (sendAdded) {
7959                sendPackageAddedForUser(packageName, pkgSetting, userId);
7960            }
7961        } finally {
7962            Binder.restoreCallingIdentity(callingId);
7963        }
7964
7965        return PackageManager.INSTALL_SUCCEEDED;
7966    }
7967
7968    boolean isUserRestricted(int userId, String restrictionKey) {
7969        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7970        if (restrictions.getBoolean(restrictionKey, false)) {
7971            Log.w(TAG, "User is restricted: " + restrictionKey);
7972            return true;
7973        }
7974        return false;
7975    }
7976
7977    @Override
7978    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7979        mContext.enforceCallingOrSelfPermission(
7980                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7981                "Only package verification agents can verify applications");
7982
7983        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7984        final PackageVerificationResponse response = new PackageVerificationResponse(
7985                verificationCode, Binder.getCallingUid());
7986        msg.arg1 = id;
7987        msg.obj = response;
7988        mHandler.sendMessage(msg);
7989    }
7990
7991    @Override
7992    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7993            long millisecondsToDelay) {
7994        mContext.enforceCallingOrSelfPermission(
7995                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7996                "Only package verification agents can extend verification timeouts");
7997
7998        final PackageVerificationState state = mPendingVerification.get(id);
7999        final PackageVerificationResponse response = new PackageVerificationResponse(
8000                verificationCodeAtTimeout, Binder.getCallingUid());
8001
8002        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8003            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8004        }
8005        if (millisecondsToDelay < 0) {
8006            millisecondsToDelay = 0;
8007        }
8008        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8009                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8010            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8011        }
8012
8013        if ((state != null) && !state.timeoutExtended()) {
8014            state.extendTimeout();
8015
8016            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8017            msg.arg1 = id;
8018            msg.obj = response;
8019            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8020        }
8021    }
8022
8023    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8024            int verificationCode, UserHandle user) {
8025        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8026        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8027        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8028        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8029        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8030
8031        mContext.sendBroadcastAsUser(intent, user,
8032                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8033    }
8034
8035    private ComponentName matchComponentForVerifier(String packageName,
8036            List<ResolveInfo> receivers) {
8037        ActivityInfo targetReceiver = null;
8038
8039        final int NR = receivers.size();
8040        for (int i = 0; i < NR; i++) {
8041            final ResolveInfo info = receivers.get(i);
8042            if (info.activityInfo == null) {
8043                continue;
8044            }
8045
8046            if (packageName.equals(info.activityInfo.packageName)) {
8047                targetReceiver = info.activityInfo;
8048                break;
8049            }
8050        }
8051
8052        if (targetReceiver == null) {
8053            return null;
8054        }
8055
8056        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8057    }
8058
8059    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8060            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8061        if (pkgInfo.verifiers.length == 0) {
8062            return null;
8063        }
8064
8065        final int N = pkgInfo.verifiers.length;
8066        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8067        for (int i = 0; i < N; i++) {
8068            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8069
8070            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8071                    receivers);
8072            if (comp == null) {
8073                continue;
8074            }
8075
8076            final int verifierUid = getUidForVerifier(verifierInfo);
8077            if (verifierUid == -1) {
8078                continue;
8079            }
8080
8081            if (DEBUG_VERIFY) {
8082                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8083                        + " with the correct signature");
8084            }
8085            sufficientVerifiers.add(comp);
8086            verificationState.addSufficientVerifier(verifierUid);
8087        }
8088
8089        return sufficientVerifiers;
8090    }
8091
8092    private int getUidForVerifier(VerifierInfo verifierInfo) {
8093        synchronized (mPackages) {
8094            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8095            if (pkg == null) {
8096                return -1;
8097            } else if (pkg.mSignatures.length != 1) {
8098                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8099                        + " has more than one signature; ignoring");
8100                return -1;
8101            }
8102
8103            /*
8104             * If the public key of the package's signature does not match
8105             * our expected public key, then this is a different package and
8106             * we should skip.
8107             */
8108
8109            final byte[] expectedPublicKey;
8110            try {
8111                final Signature verifierSig = pkg.mSignatures[0];
8112                final PublicKey publicKey = verifierSig.getPublicKey();
8113                expectedPublicKey = publicKey.getEncoded();
8114            } catch (CertificateException e) {
8115                return -1;
8116            }
8117
8118            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8119
8120            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8121                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8122                        + " does not have the expected public key; ignoring");
8123                return -1;
8124            }
8125
8126            return pkg.applicationInfo.uid;
8127        }
8128    }
8129
8130    @Override
8131    public void finishPackageInstall(int token) {
8132        enforceSystemOrRoot("Only the system is allowed to finish installs");
8133
8134        if (DEBUG_INSTALL) {
8135            Slog.v(TAG, "BM finishing package install for " + token);
8136        }
8137
8138        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8139        mHandler.sendMessage(msg);
8140    }
8141
8142    /**
8143     * Get the verification agent timeout.
8144     *
8145     * @return verification timeout in milliseconds
8146     */
8147    private long getVerificationTimeout() {
8148        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8149                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8150                DEFAULT_VERIFICATION_TIMEOUT);
8151    }
8152
8153    /**
8154     * Get the default verification agent response code.
8155     *
8156     * @return default verification response code
8157     */
8158    private int getDefaultVerificationResponse() {
8159        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8160                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8161                DEFAULT_VERIFICATION_RESPONSE);
8162    }
8163
8164    /**
8165     * Check whether or not package verification has been enabled.
8166     *
8167     * @return true if verification should be performed
8168     */
8169    private boolean isVerificationEnabled(int userId, int installFlags) {
8170        if (!DEFAULT_VERIFY_ENABLE) {
8171            return false;
8172        }
8173
8174        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8175
8176        // Check if installing from ADB
8177        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8178            // Do not run verification in a test harness environment
8179            if (ActivityManager.isRunningInTestHarness()) {
8180                return false;
8181            }
8182            if (ensureVerifyAppsEnabled) {
8183                return true;
8184            }
8185            // Check if the developer does not want package verification for ADB installs
8186            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8187                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8188                return false;
8189            }
8190        }
8191
8192        if (ensureVerifyAppsEnabled) {
8193            return true;
8194        }
8195
8196        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8197                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8198    }
8199
8200    /**
8201     * Get the "allow unknown sources" setting.
8202     *
8203     * @return the current "allow unknown sources" setting
8204     */
8205    private int getUnknownSourcesSettings() {
8206        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8207                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8208                -1);
8209    }
8210
8211    @Override
8212    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8213        final int uid = Binder.getCallingUid();
8214        // writer
8215        synchronized (mPackages) {
8216            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8217            if (targetPackageSetting == null) {
8218                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8219            }
8220
8221            PackageSetting installerPackageSetting;
8222            if (installerPackageName != null) {
8223                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8224                if (installerPackageSetting == null) {
8225                    throw new IllegalArgumentException("Unknown installer package: "
8226                            + installerPackageName);
8227                }
8228            } else {
8229                installerPackageSetting = null;
8230            }
8231
8232            Signature[] callerSignature;
8233            Object obj = mSettings.getUserIdLPr(uid);
8234            if (obj != null) {
8235                if (obj instanceof SharedUserSetting) {
8236                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8237                } else if (obj instanceof PackageSetting) {
8238                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8239                } else {
8240                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8241                }
8242            } else {
8243                throw new SecurityException("Unknown calling uid " + uid);
8244            }
8245
8246            // Verify: can't set installerPackageName to a package that is
8247            // not signed with the same cert as the caller.
8248            if (installerPackageSetting != null) {
8249                if (compareSignatures(callerSignature,
8250                        installerPackageSetting.signatures.mSignatures)
8251                        != PackageManager.SIGNATURE_MATCH) {
8252                    throw new SecurityException(
8253                            "Caller does not have same cert as new installer package "
8254                            + installerPackageName);
8255                }
8256            }
8257
8258            // Verify: if target already has an installer package, it must
8259            // be signed with the same cert as the caller.
8260            if (targetPackageSetting.installerPackageName != null) {
8261                PackageSetting setting = mSettings.mPackages.get(
8262                        targetPackageSetting.installerPackageName);
8263                // If the currently set package isn't valid, then it's always
8264                // okay to change it.
8265                if (setting != null) {
8266                    if (compareSignatures(callerSignature,
8267                            setting.signatures.mSignatures)
8268                            != PackageManager.SIGNATURE_MATCH) {
8269                        throw new SecurityException(
8270                                "Caller does not have same cert as old installer package "
8271                                + targetPackageSetting.installerPackageName);
8272                    }
8273                }
8274            }
8275
8276            // Okay!
8277            targetPackageSetting.installerPackageName = installerPackageName;
8278            scheduleWriteSettingsLocked();
8279        }
8280    }
8281
8282    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8283        // Queue up an async operation since the package installation may take a little while.
8284        mHandler.post(new Runnable() {
8285            public void run() {
8286                mHandler.removeCallbacks(this);
8287                 // Result object to be returned
8288                PackageInstalledInfo res = new PackageInstalledInfo();
8289                res.returnCode = currentStatus;
8290                res.uid = -1;
8291                res.pkg = null;
8292                res.removedInfo = new PackageRemovedInfo();
8293                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8294                    args.doPreInstall(res.returnCode);
8295                    synchronized (mInstallLock) {
8296                        installPackageLI(args, res);
8297                    }
8298                    args.doPostInstall(res.returnCode, res.uid);
8299                }
8300
8301                // A restore should be performed at this point if (a) the install
8302                // succeeded, (b) the operation is not an update, and (c) the new
8303                // package has not opted out of backup participation.
8304                final boolean update = res.removedInfo.removedPackage != null;
8305                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8306                boolean doRestore = !update
8307                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8308
8309                // Set up the post-install work request bookkeeping.  This will be used
8310                // and cleaned up by the post-install event handling regardless of whether
8311                // there's a restore pass performed.  Token values are >= 1.
8312                int token;
8313                if (mNextInstallToken < 0) mNextInstallToken = 1;
8314                token = mNextInstallToken++;
8315
8316                PostInstallData data = new PostInstallData(args, res);
8317                mRunningInstalls.put(token, data);
8318                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8319
8320                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8321                    // Pass responsibility to the Backup Manager.  It will perform a
8322                    // restore if appropriate, then pass responsibility back to the
8323                    // Package Manager to run the post-install observer callbacks
8324                    // and broadcasts.
8325                    IBackupManager bm = IBackupManager.Stub.asInterface(
8326                            ServiceManager.getService(Context.BACKUP_SERVICE));
8327                    if (bm != null) {
8328                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8329                                + " to BM for possible restore");
8330                        try {
8331                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8332                        } catch (RemoteException e) {
8333                            // can't happen; the backup manager is local
8334                        } catch (Exception e) {
8335                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8336                            doRestore = false;
8337                        }
8338                    } else {
8339                        Slog.e(TAG, "Backup Manager not found!");
8340                        doRestore = false;
8341                    }
8342                }
8343
8344                if (!doRestore) {
8345                    // No restore possible, or the Backup Manager was mysteriously not
8346                    // available -- just fire the post-install work request directly.
8347                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8348                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8349                    mHandler.sendMessage(msg);
8350                }
8351            }
8352        });
8353    }
8354
8355    private abstract class HandlerParams {
8356        private static final int MAX_RETRIES = 4;
8357
8358        /**
8359         * Number of times startCopy() has been attempted and had a non-fatal
8360         * error.
8361         */
8362        private int mRetries = 0;
8363
8364        /** User handle for the user requesting the information or installation. */
8365        private final UserHandle mUser;
8366
8367        HandlerParams(UserHandle user) {
8368            mUser = user;
8369        }
8370
8371        UserHandle getUser() {
8372            return mUser;
8373        }
8374
8375        final boolean startCopy() {
8376            boolean res;
8377            try {
8378                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8379
8380                if (++mRetries > MAX_RETRIES) {
8381                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8382                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8383                    handleServiceError();
8384                    return false;
8385                } else {
8386                    handleStartCopy();
8387                    res = true;
8388                }
8389            } catch (RemoteException e) {
8390                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8391                mHandler.sendEmptyMessage(MCS_RECONNECT);
8392                res = false;
8393            }
8394            handleReturnCode();
8395            return res;
8396        }
8397
8398        final void serviceError() {
8399            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8400            handleServiceError();
8401            handleReturnCode();
8402        }
8403
8404        abstract void handleStartCopy() throws RemoteException;
8405        abstract void handleServiceError();
8406        abstract void handleReturnCode();
8407    }
8408
8409    class MeasureParams extends HandlerParams {
8410        private final PackageStats mStats;
8411        private boolean mSuccess;
8412
8413        private final IPackageStatsObserver mObserver;
8414
8415        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8416            super(new UserHandle(stats.userHandle));
8417            mObserver = observer;
8418            mStats = stats;
8419        }
8420
8421        @Override
8422        public String toString() {
8423            return "MeasureParams{"
8424                + Integer.toHexString(System.identityHashCode(this))
8425                + " " + mStats.packageName + "}";
8426        }
8427
8428        @Override
8429        void handleStartCopy() throws RemoteException {
8430            synchronized (mInstallLock) {
8431                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8432            }
8433
8434            if (mSuccess) {
8435                final boolean mounted;
8436                if (Environment.isExternalStorageEmulated()) {
8437                    mounted = true;
8438                } else {
8439                    final String status = Environment.getExternalStorageState();
8440                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8441                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8442                }
8443
8444                if (mounted) {
8445                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8446
8447                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8448                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8449
8450                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8451                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8452
8453                    // Always subtract cache size, since it's a subdirectory
8454                    mStats.externalDataSize -= mStats.externalCacheSize;
8455
8456                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8457                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8458
8459                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8460                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8461                }
8462            }
8463        }
8464
8465        @Override
8466        void handleReturnCode() {
8467            if (mObserver != null) {
8468                try {
8469                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8470                } catch (RemoteException e) {
8471                    Slog.i(TAG, "Observer no longer exists.");
8472                }
8473            }
8474        }
8475
8476        @Override
8477        void handleServiceError() {
8478            Slog.e(TAG, "Could not measure application " + mStats.packageName
8479                            + " external storage");
8480        }
8481    }
8482
8483    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8484            throws RemoteException {
8485        long result = 0;
8486        for (File path : paths) {
8487            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8488        }
8489        return result;
8490    }
8491
8492    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8493        for (File path : paths) {
8494            try {
8495                mcs.clearDirectory(path.getAbsolutePath());
8496            } catch (RemoteException e) {
8497            }
8498        }
8499    }
8500
8501    static class OriginInfo {
8502        /**
8503         * Location where install is coming from, before it has been
8504         * copied/renamed into place. This could be a single monolithic APK
8505         * file, or a cluster directory. This location may be untrusted.
8506         */
8507        final File file;
8508        final String cid;
8509
8510        /**
8511         * Flag indicating that {@link #file} or {@link #cid} has already been
8512         * staged, meaning downstream users don't need to defensively copy the
8513         * contents.
8514         */
8515        final boolean staged;
8516
8517        /**
8518         * Flag indicating that {@link #file} or {@link #cid} is an already
8519         * installed app that is being moved.
8520         */
8521        final boolean existing;
8522
8523        final String resolvedPath;
8524        final File resolvedFile;
8525
8526        static OriginInfo fromNothing() {
8527            return new OriginInfo(null, null, false, false);
8528        }
8529
8530        static OriginInfo fromUntrustedFile(File file) {
8531            return new OriginInfo(file, null, false, false);
8532        }
8533
8534        static OriginInfo fromExistingFile(File file) {
8535            return new OriginInfo(file, null, false, true);
8536        }
8537
8538        static OriginInfo fromStagedFile(File file) {
8539            return new OriginInfo(file, null, true, false);
8540        }
8541
8542        static OriginInfo fromStagedContainer(String cid) {
8543            return new OriginInfo(null, cid, true, false);
8544        }
8545
8546        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8547            this.file = file;
8548            this.cid = cid;
8549            this.staged = staged;
8550            this.existing = existing;
8551
8552            if (cid != null) {
8553                resolvedPath = PackageHelper.getSdDir(cid);
8554                resolvedFile = new File(resolvedPath);
8555            } else if (file != null) {
8556                resolvedPath = file.getAbsolutePath();
8557                resolvedFile = file;
8558            } else {
8559                resolvedPath = null;
8560                resolvedFile = null;
8561            }
8562        }
8563    }
8564
8565    class InstallParams extends HandlerParams {
8566        final OriginInfo origin;
8567        final IPackageInstallObserver2 observer;
8568        int installFlags;
8569        final String installerPackageName;
8570        final VerificationParams verificationParams;
8571        private InstallArgs mArgs;
8572        private int mRet;
8573        final String packageAbiOverride;
8574
8575        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8576                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8577                String packageAbiOverride) {
8578            super(user);
8579            this.origin = origin;
8580            this.observer = observer;
8581            this.installFlags = installFlags;
8582            this.installerPackageName = installerPackageName;
8583            this.verificationParams = verificationParams;
8584            this.packageAbiOverride = packageAbiOverride;
8585        }
8586
8587        @Override
8588        public String toString() {
8589            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8590                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8591        }
8592
8593        public ManifestDigest getManifestDigest() {
8594            if (verificationParams == null) {
8595                return null;
8596            }
8597            return verificationParams.getManifestDigest();
8598        }
8599
8600        private int installLocationPolicy(PackageInfoLite pkgLite) {
8601            String packageName = pkgLite.packageName;
8602            int installLocation = pkgLite.installLocation;
8603            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8604            // reader
8605            synchronized (mPackages) {
8606                PackageParser.Package pkg = mPackages.get(packageName);
8607                if (pkg != null) {
8608                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8609                        // Check for downgrading.
8610                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8611                            if (pkgLite.versionCode < pkg.mVersionCode) {
8612                                Slog.w(TAG, "Can't install update of " + packageName
8613                                        + " update version " + pkgLite.versionCode
8614                                        + " is older than installed version "
8615                                        + pkg.mVersionCode);
8616                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8617                            }
8618                        }
8619                        // Check for updated system application.
8620                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8621                            if (onSd) {
8622                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8623                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8624                            }
8625                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8626                        } else {
8627                            if (onSd) {
8628                                // Install flag overrides everything.
8629                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8630                            }
8631                            // If current upgrade specifies particular preference
8632                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8633                                // Application explicitly specified internal.
8634                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8635                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8636                                // App explictly prefers external. Let policy decide
8637                            } else {
8638                                // Prefer previous location
8639                                if (isExternal(pkg)) {
8640                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8641                                }
8642                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8643                            }
8644                        }
8645                    } else {
8646                        // Invalid install. Return error code
8647                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8648                    }
8649                }
8650            }
8651            // All the special cases have been taken care of.
8652            // Return result based on recommended install location.
8653            if (onSd) {
8654                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8655            }
8656            return pkgLite.recommendedInstallLocation;
8657        }
8658
8659        /*
8660         * Invoke remote method to get package information and install
8661         * location values. Override install location based on default
8662         * policy if needed and then create install arguments based
8663         * on the install location.
8664         */
8665        public void handleStartCopy() throws RemoteException {
8666            int ret = PackageManager.INSTALL_SUCCEEDED;
8667
8668            // If we're already staged, we've firmly committed to an install location
8669            if (origin.staged) {
8670                if (origin.file != null) {
8671                    installFlags |= PackageManager.INSTALL_INTERNAL;
8672                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8673                } else if (origin.cid != null) {
8674                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8675                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8676                } else {
8677                    throw new IllegalStateException("Invalid stage location");
8678                }
8679            }
8680
8681            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8682            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8683
8684            PackageInfoLite pkgLite = null;
8685
8686            if (onInt && onSd) {
8687                // Check if both bits are set.
8688                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8689                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8690            } else {
8691                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8692                        packageAbiOverride);
8693
8694                /*
8695                 * If we have too little free space, try to free cache
8696                 * before giving up.
8697                 */
8698                if (!origin.staged && pkgLite.recommendedInstallLocation
8699                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8700                    // TODO: focus freeing disk space on the target device
8701                    final StorageManager storage = StorageManager.from(mContext);
8702                    final long lowThreshold = storage.getStorageLowBytes(
8703                            Environment.getDataDirectory());
8704
8705                    final long sizeBytes = mContainerService.calculateInstalledSize(
8706                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8707
8708                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8709                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8710                                installFlags, packageAbiOverride);
8711                    }
8712
8713                    /*
8714                     * The cache free must have deleted the file we
8715                     * downloaded to install.
8716                     *
8717                     * TODO: fix the "freeCache" call to not delete
8718                     *       the file we care about.
8719                     */
8720                    if (pkgLite.recommendedInstallLocation
8721                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8722                        pkgLite.recommendedInstallLocation
8723                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8724                    }
8725                }
8726            }
8727
8728            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8729                int loc = pkgLite.recommendedInstallLocation;
8730                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8731                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8732                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8733                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8734                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8735                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8736                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8737                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8738                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8739                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8740                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8741                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8742                } else {
8743                    // Override with defaults if needed.
8744                    loc = installLocationPolicy(pkgLite);
8745                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8746                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8747                    } else if (!onSd && !onInt) {
8748                        // Override install location with flags
8749                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8750                            // Set the flag to install on external media.
8751                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8752                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8753                        } else {
8754                            // Make sure the flag for installing on external
8755                            // media is unset
8756                            installFlags |= PackageManager.INSTALL_INTERNAL;
8757                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8758                        }
8759                    }
8760                }
8761            }
8762
8763            final InstallArgs args = createInstallArgs(this);
8764            mArgs = args;
8765
8766            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8767                 /*
8768                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8769                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8770                 */
8771                int userIdentifier = getUser().getIdentifier();
8772                if (userIdentifier == UserHandle.USER_ALL
8773                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8774                    userIdentifier = UserHandle.USER_OWNER;
8775                }
8776
8777                /*
8778                 * Determine if we have any installed package verifiers. If we
8779                 * do, then we'll defer to them to verify the packages.
8780                 */
8781                final int requiredUid = mRequiredVerifierPackage == null ? -1
8782                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8783                if (!origin.existing && requiredUid != -1
8784                        && isVerificationEnabled(userIdentifier, installFlags)) {
8785                    final Intent verification = new Intent(
8786                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8787                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8788                            PACKAGE_MIME_TYPE);
8789                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8790
8791                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8792                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8793                            0 /* TODO: Which userId? */);
8794
8795                    if (DEBUG_VERIFY) {
8796                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8797                                + verification.toString() + " with " + pkgLite.verifiers.length
8798                                + " optional verifiers");
8799                    }
8800
8801                    final int verificationId = mPendingVerificationToken++;
8802
8803                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8804
8805                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8806                            installerPackageName);
8807
8808                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8809                            installFlags);
8810
8811                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8812                            pkgLite.packageName);
8813
8814                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8815                            pkgLite.versionCode);
8816
8817                    if (verificationParams != null) {
8818                        if (verificationParams.getVerificationURI() != null) {
8819                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8820                                 verificationParams.getVerificationURI());
8821                        }
8822                        if (verificationParams.getOriginatingURI() != null) {
8823                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8824                                  verificationParams.getOriginatingURI());
8825                        }
8826                        if (verificationParams.getReferrer() != null) {
8827                            verification.putExtra(Intent.EXTRA_REFERRER,
8828                                  verificationParams.getReferrer());
8829                        }
8830                        if (verificationParams.getOriginatingUid() >= 0) {
8831                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8832                                  verificationParams.getOriginatingUid());
8833                        }
8834                        if (verificationParams.getInstallerUid() >= 0) {
8835                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8836                                  verificationParams.getInstallerUid());
8837                        }
8838                    }
8839
8840                    final PackageVerificationState verificationState = new PackageVerificationState(
8841                            requiredUid, args);
8842
8843                    mPendingVerification.append(verificationId, verificationState);
8844
8845                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8846                            receivers, verificationState);
8847
8848                    /*
8849                     * If any sufficient verifiers were listed in the package
8850                     * manifest, attempt to ask them.
8851                     */
8852                    if (sufficientVerifiers != null) {
8853                        final int N = sufficientVerifiers.size();
8854                        if (N == 0) {
8855                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8856                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8857                        } else {
8858                            for (int i = 0; i < N; i++) {
8859                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8860
8861                                final Intent sufficientIntent = new Intent(verification);
8862                                sufficientIntent.setComponent(verifierComponent);
8863
8864                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8865                            }
8866                        }
8867                    }
8868
8869                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8870                            mRequiredVerifierPackage, receivers);
8871                    if (ret == PackageManager.INSTALL_SUCCEEDED
8872                            && mRequiredVerifierPackage != null) {
8873                        /*
8874                         * Send the intent to the required verification agent,
8875                         * but only start the verification timeout after the
8876                         * target BroadcastReceivers have run.
8877                         */
8878                        verification.setComponent(requiredVerifierComponent);
8879                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8880                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8881                                new BroadcastReceiver() {
8882                                    @Override
8883                                    public void onReceive(Context context, Intent intent) {
8884                                        final Message msg = mHandler
8885                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8886                                        msg.arg1 = verificationId;
8887                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8888                                    }
8889                                }, null, 0, null, null);
8890
8891                        /*
8892                         * We don't want the copy to proceed until verification
8893                         * succeeds, so null out this field.
8894                         */
8895                        mArgs = null;
8896                    }
8897                } else {
8898                    /*
8899                     * No package verification is enabled, so immediately start
8900                     * the remote call to initiate copy using temporary file.
8901                     */
8902                    ret = args.copyApk(mContainerService, true);
8903                }
8904            }
8905
8906            mRet = ret;
8907        }
8908
8909        @Override
8910        void handleReturnCode() {
8911            // If mArgs is null, then MCS couldn't be reached. When it
8912            // reconnects, it will try again to install. At that point, this
8913            // will succeed.
8914            if (mArgs != null) {
8915                processPendingInstall(mArgs, mRet);
8916            }
8917        }
8918
8919        @Override
8920        void handleServiceError() {
8921            mArgs = createInstallArgs(this);
8922            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8923        }
8924
8925        public boolean isForwardLocked() {
8926            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8927        }
8928    }
8929
8930    /**
8931     * Used during creation of InstallArgs
8932     *
8933     * @param installFlags package installation flags
8934     * @return true if should be installed on external storage
8935     */
8936    private static boolean installOnSd(int installFlags) {
8937        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8938            return false;
8939        }
8940        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8941            return true;
8942        }
8943        return false;
8944    }
8945
8946    /**
8947     * Used during creation of InstallArgs
8948     *
8949     * @param installFlags package installation flags
8950     * @return true if should be installed as forward locked
8951     */
8952    private static boolean installForwardLocked(int installFlags) {
8953        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8954    }
8955
8956    private InstallArgs createInstallArgs(InstallParams params) {
8957        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8958            return new AsecInstallArgs(params);
8959        } else {
8960            return new FileInstallArgs(params);
8961        }
8962    }
8963
8964    /**
8965     * Create args that describe an existing installed package. Typically used
8966     * when cleaning up old installs, or used as a move source.
8967     */
8968    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8969            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8970        final boolean isInAsec;
8971        if (installOnSd(installFlags)) {
8972            /* Apps on SD card are always in ASEC containers. */
8973            isInAsec = true;
8974        } else if (installForwardLocked(installFlags)
8975                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8976            /*
8977             * Forward-locked apps are only in ASEC containers if they're the
8978             * new style
8979             */
8980            isInAsec = true;
8981        } else {
8982            isInAsec = false;
8983        }
8984
8985        if (isInAsec) {
8986            return new AsecInstallArgs(codePath, instructionSets,
8987                    installOnSd(installFlags), installForwardLocked(installFlags));
8988        } else {
8989            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8990                    instructionSets);
8991        }
8992    }
8993
8994    static abstract class InstallArgs {
8995        /** @see InstallParams#origin */
8996        final OriginInfo origin;
8997
8998        final IPackageInstallObserver2 observer;
8999        // Always refers to PackageManager flags only
9000        final int installFlags;
9001        final String installerPackageName;
9002        final ManifestDigest manifestDigest;
9003        final UserHandle user;
9004        final String abiOverride;
9005
9006        // The list of instruction sets supported by this app. This is currently
9007        // only used during the rmdex() phase to clean up resources. We can get rid of this
9008        // if we move dex files under the common app path.
9009        /* nullable */ String[] instructionSets;
9010
9011        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9012                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9013                String[] instructionSets, String abiOverride) {
9014            this.origin = origin;
9015            this.installFlags = installFlags;
9016            this.observer = observer;
9017            this.installerPackageName = installerPackageName;
9018            this.manifestDigest = manifestDigest;
9019            this.user = user;
9020            this.instructionSets = instructionSets;
9021            this.abiOverride = abiOverride;
9022        }
9023
9024        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9025        abstract int doPreInstall(int status);
9026
9027        /**
9028         * Rename package into final resting place. All paths on the given
9029         * scanned package should be updated to reflect the rename.
9030         */
9031        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9032        abstract int doPostInstall(int status, int uid);
9033
9034        /** @see PackageSettingBase#codePathString */
9035        abstract String getCodePath();
9036        /** @see PackageSettingBase#resourcePathString */
9037        abstract String getResourcePath();
9038        abstract String getLegacyNativeLibraryPath();
9039
9040        // Need installer lock especially for dex file removal.
9041        abstract void cleanUpResourcesLI();
9042        abstract boolean doPostDeleteLI(boolean delete);
9043        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9044
9045        /**
9046         * Called before the source arguments are copied. This is used mostly
9047         * for MoveParams when it needs to read the source file to put it in the
9048         * destination.
9049         */
9050        int doPreCopy() {
9051            return PackageManager.INSTALL_SUCCEEDED;
9052        }
9053
9054        /**
9055         * Called after the source arguments are copied. This is used mostly for
9056         * MoveParams when it needs to read the source file to put it in the
9057         * destination.
9058         *
9059         * @return
9060         */
9061        int doPostCopy(int uid) {
9062            return PackageManager.INSTALL_SUCCEEDED;
9063        }
9064
9065        protected boolean isFwdLocked() {
9066            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9067        }
9068
9069        protected boolean isExternal() {
9070            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9071        }
9072
9073        UserHandle getUser() {
9074            return user;
9075        }
9076    }
9077
9078    /**
9079     * Logic to handle installation of non-ASEC applications, including copying
9080     * and renaming logic.
9081     */
9082    class FileInstallArgs extends InstallArgs {
9083        private File codeFile;
9084        private File resourceFile;
9085        private File legacyNativeLibraryPath;
9086
9087        // Example topology:
9088        // /data/app/com.example/base.apk
9089        // /data/app/com.example/split_foo.apk
9090        // /data/app/com.example/lib/arm/libfoo.so
9091        // /data/app/com.example/lib/arm64/libfoo.so
9092        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9093
9094        /** New install */
9095        FileInstallArgs(InstallParams params) {
9096            super(params.origin, params.observer, params.installFlags,
9097                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9098                    null /* instruction sets */, params.packageAbiOverride);
9099            if (isFwdLocked()) {
9100                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9101            }
9102        }
9103
9104        /** Existing install */
9105        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9106                String[] instructionSets) {
9107            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9108            this.codeFile = (codePath != null) ? new File(codePath) : null;
9109            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9110            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9111                    new File(legacyNativeLibraryPath) : null;
9112        }
9113
9114        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9115            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9116                    isFwdLocked(), abiOverride);
9117
9118            final StorageManager storage = StorageManager.from(mContext);
9119            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9120        }
9121
9122        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9123            if (origin.staged) {
9124                Slog.d(TAG, origin.file + " already staged; skipping copy");
9125                codeFile = origin.file;
9126                resourceFile = origin.file;
9127                return PackageManager.INSTALL_SUCCEEDED;
9128            }
9129
9130            try {
9131                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9132                codeFile = tempDir;
9133                resourceFile = tempDir;
9134            } catch (IOException e) {
9135                Slog.w(TAG, "Failed to create copy file: " + e);
9136                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9137            }
9138
9139            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9140                @Override
9141                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9142                    if (!FileUtils.isValidExtFilename(name)) {
9143                        throw new IllegalArgumentException("Invalid filename: " + name);
9144                    }
9145                    try {
9146                        final File file = new File(codeFile, name);
9147                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9148                                O_RDWR | O_CREAT, 0644);
9149                        Os.chmod(file.getAbsolutePath(), 0644);
9150                        return new ParcelFileDescriptor(fd);
9151                    } catch (ErrnoException e) {
9152                        throw new RemoteException("Failed to open: " + e.getMessage());
9153                    }
9154                }
9155            };
9156
9157            int ret = PackageManager.INSTALL_SUCCEEDED;
9158            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9159            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9160                Slog.e(TAG, "Failed to copy package");
9161                return ret;
9162            }
9163
9164            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9165            NativeLibraryHelper.Handle handle = null;
9166            try {
9167                handle = NativeLibraryHelper.Handle.create(codeFile);
9168                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9169                        abiOverride);
9170            } catch (IOException e) {
9171                Slog.e(TAG, "Copying native libraries failed", e);
9172                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9173            } finally {
9174                IoUtils.closeQuietly(handle);
9175            }
9176
9177            return ret;
9178        }
9179
9180        int doPreInstall(int status) {
9181            if (status != PackageManager.INSTALL_SUCCEEDED) {
9182                cleanUp();
9183            }
9184            return status;
9185        }
9186
9187        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9188            if (status != PackageManager.INSTALL_SUCCEEDED) {
9189                cleanUp();
9190                return false;
9191            } else {
9192                final File beforeCodeFile = codeFile;
9193                final File afterCodeFile = getNextCodePath(pkg.packageName);
9194
9195                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9196                try {
9197                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9198                } catch (ErrnoException e) {
9199                    Slog.d(TAG, "Failed to rename", e);
9200                    return false;
9201                }
9202
9203                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9204                    Slog.d(TAG, "Failed to restorecon");
9205                    return false;
9206                }
9207
9208                // Reflect the rename internally
9209                codeFile = afterCodeFile;
9210                resourceFile = afterCodeFile;
9211
9212                // Reflect the rename in scanned details
9213                pkg.codePath = afterCodeFile.getAbsolutePath();
9214                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9215                        pkg.baseCodePath);
9216                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9217                        pkg.splitCodePaths);
9218
9219                // Reflect the rename in app info
9220                pkg.applicationInfo.setCodePath(pkg.codePath);
9221                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9222                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9223                pkg.applicationInfo.setResourcePath(pkg.codePath);
9224                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9225                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9226
9227                return true;
9228            }
9229        }
9230
9231        int doPostInstall(int status, int uid) {
9232            if (status != PackageManager.INSTALL_SUCCEEDED) {
9233                cleanUp();
9234            }
9235            return status;
9236        }
9237
9238        @Override
9239        String getCodePath() {
9240            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9241        }
9242
9243        @Override
9244        String getResourcePath() {
9245            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9246        }
9247
9248        @Override
9249        String getLegacyNativeLibraryPath() {
9250            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9251        }
9252
9253        private boolean cleanUp() {
9254            if (codeFile == null || !codeFile.exists()) {
9255                return false;
9256            }
9257
9258            if (codeFile.isDirectory()) {
9259                FileUtils.deleteContents(codeFile);
9260            }
9261            codeFile.delete();
9262
9263            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9264                resourceFile.delete();
9265            }
9266
9267            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9268                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9269                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9270                }
9271                legacyNativeLibraryPath.delete();
9272            }
9273
9274            return true;
9275        }
9276
9277        void cleanUpResourcesLI() {
9278            // Try enumerating all code paths before deleting
9279            List<String> allCodePaths = Collections.EMPTY_LIST;
9280            if (codeFile != null && codeFile.exists()) {
9281                try {
9282                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9283                    allCodePaths = pkg.getAllCodePaths();
9284                } catch (PackageParserException e) {
9285                    // Ignored; we tried our best
9286                }
9287            }
9288
9289            cleanUp();
9290
9291            if (!allCodePaths.isEmpty()) {
9292                if (instructionSets == null) {
9293                    throw new IllegalStateException("instructionSet == null");
9294                }
9295                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9296                for (String codePath : allCodePaths) {
9297                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9298                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9299                        if (retCode < 0) {
9300                            Slog.w(TAG, "Couldn't remove dex file for package: "
9301                                    + " at location " + codePath + ", retcode=" + retCode);
9302                            // we don't consider this to be a failure of the core package deletion
9303                        }
9304                    }
9305                }
9306            }
9307        }
9308
9309        boolean doPostDeleteLI(boolean delete) {
9310            // XXX err, shouldn't we respect the delete flag?
9311            cleanUpResourcesLI();
9312            return true;
9313        }
9314    }
9315
9316    private boolean isAsecExternal(String cid) {
9317        final String asecPath = PackageHelper.getSdFilesystem(cid);
9318        return !asecPath.startsWith(mAsecInternalPath);
9319    }
9320
9321    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9322            PackageManagerException {
9323        if (copyRet < 0) {
9324            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9325                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9326                throw new PackageManagerException(copyRet, message);
9327            }
9328        }
9329    }
9330
9331    /**
9332     * Extract the MountService "container ID" from the full code path of an
9333     * .apk.
9334     */
9335    static String cidFromCodePath(String fullCodePath) {
9336        int eidx = fullCodePath.lastIndexOf("/");
9337        String subStr1 = fullCodePath.substring(0, eidx);
9338        int sidx = subStr1.lastIndexOf("/");
9339        return subStr1.substring(sidx+1, eidx);
9340    }
9341
9342    /**
9343     * Logic to handle installation of ASEC applications, including copying and
9344     * renaming logic.
9345     */
9346    class AsecInstallArgs extends InstallArgs {
9347        static final String RES_FILE_NAME = "pkg.apk";
9348        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9349
9350        String cid;
9351        String packagePath;
9352        String resourcePath;
9353        String legacyNativeLibraryDir;
9354
9355        /** New install */
9356        AsecInstallArgs(InstallParams params) {
9357            super(params.origin, params.observer, params.installFlags,
9358                    params.installerPackageName, params.getManifestDigest(),
9359                    params.getUser(), null /* instruction sets */,
9360                    params.packageAbiOverride);
9361        }
9362
9363        /** Existing install */
9364        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9365                        boolean isExternal, boolean isForwardLocked) {
9366            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9367                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9368                    instructionSets, null);
9369            // Hackily pretend we're still looking at a full code path
9370            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9371                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9372            }
9373
9374            // Extract cid from fullCodePath
9375            int eidx = fullCodePath.lastIndexOf("/");
9376            String subStr1 = fullCodePath.substring(0, eidx);
9377            int sidx = subStr1.lastIndexOf("/");
9378            cid = subStr1.substring(sidx+1, eidx);
9379            setMountPath(subStr1);
9380        }
9381
9382        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9383            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9384                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9385                    instructionSets, null);
9386            this.cid = cid;
9387            setMountPath(PackageHelper.getSdDir(cid));
9388        }
9389
9390        void createCopyFile() {
9391            cid = mInstallerService.allocateExternalStageCidLegacy();
9392        }
9393
9394        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9395            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9396                    abiOverride);
9397
9398            final File target;
9399            if (isExternal()) {
9400                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9401            } else {
9402                target = Environment.getDataDirectory();
9403            }
9404
9405            final StorageManager storage = StorageManager.from(mContext);
9406            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9407        }
9408
9409        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9410            if (origin.staged) {
9411                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9412                cid = origin.cid;
9413                setMountPath(PackageHelper.getSdDir(cid));
9414                return PackageManager.INSTALL_SUCCEEDED;
9415            }
9416
9417            if (temp) {
9418                createCopyFile();
9419            } else {
9420                /*
9421                 * Pre-emptively destroy the container since it's destroyed if
9422                 * copying fails due to it existing anyway.
9423                 */
9424                PackageHelper.destroySdDir(cid);
9425            }
9426
9427            final String newMountPath = imcs.copyPackageToContainer(
9428                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9429                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9430
9431            if (newMountPath != null) {
9432                setMountPath(newMountPath);
9433                return PackageManager.INSTALL_SUCCEEDED;
9434            } else {
9435                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9436            }
9437        }
9438
9439        @Override
9440        String getCodePath() {
9441            return packagePath;
9442        }
9443
9444        @Override
9445        String getResourcePath() {
9446            return resourcePath;
9447        }
9448
9449        @Override
9450        String getLegacyNativeLibraryPath() {
9451            return legacyNativeLibraryDir;
9452        }
9453
9454        int doPreInstall(int status) {
9455            if (status != PackageManager.INSTALL_SUCCEEDED) {
9456                // Destroy container
9457                PackageHelper.destroySdDir(cid);
9458            } else {
9459                boolean mounted = PackageHelper.isContainerMounted(cid);
9460                if (!mounted) {
9461                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9462                            Process.SYSTEM_UID);
9463                    if (newMountPath != null) {
9464                        setMountPath(newMountPath);
9465                    } else {
9466                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9467                    }
9468                }
9469            }
9470            return status;
9471        }
9472
9473        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9474            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9475            String newMountPath = null;
9476            if (PackageHelper.isContainerMounted(cid)) {
9477                // Unmount the container
9478                if (!PackageHelper.unMountSdDir(cid)) {
9479                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9480                    return false;
9481                }
9482            }
9483            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9484                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9485                        " which might be stale. Will try to clean up.");
9486                // Clean up the stale container and proceed to recreate.
9487                if (!PackageHelper.destroySdDir(newCacheId)) {
9488                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9489                    return false;
9490                }
9491                // Successfully cleaned up stale container. Try to rename again.
9492                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9493                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9494                            + " inspite of cleaning it up.");
9495                    return false;
9496                }
9497            }
9498            if (!PackageHelper.isContainerMounted(newCacheId)) {
9499                Slog.w(TAG, "Mounting container " + newCacheId);
9500                newMountPath = PackageHelper.mountSdDir(newCacheId,
9501                        getEncryptKey(), Process.SYSTEM_UID);
9502            } else {
9503                newMountPath = PackageHelper.getSdDir(newCacheId);
9504            }
9505            if (newMountPath == null) {
9506                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9507                return false;
9508            }
9509            Log.i(TAG, "Succesfully renamed " + cid +
9510                    " to " + newCacheId +
9511                    " at new path: " + newMountPath);
9512            cid = newCacheId;
9513
9514            final File beforeCodeFile = new File(packagePath);
9515            setMountPath(newMountPath);
9516            final File afterCodeFile = new File(packagePath);
9517
9518            // Reflect the rename in scanned details
9519            pkg.codePath = afterCodeFile.getAbsolutePath();
9520            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9521                    pkg.baseCodePath);
9522            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9523                    pkg.splitCodePaths);
9524
9525            // Reflect the rename in app info
9526            pkg.applicationInfo.setCodePath(pkg.codePath);
9527            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9528            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9529            pkg.applicationInfo.setResourcePath(pkg.codePath);
9530            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9531            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9532
9533            return true;
9534        }
9535
9536        private void setMountPath(String mountPath) {
9537            final File mountFile = new File(mountPath);
9538
9539            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9540            if (monolithicFile.exists()) {
9541                packagePath = monolithicFile.getAbsolutePath();
9542                if (isFwdLocked()) {
9543                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9544                } else {
9545                    resourcePath = packagePath;
9546                }
9547            } else {
9548                packagePath = mountFile.getAbsolutePath();
9549                resourcePath = packagePath;
9550            }
9551
9552            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9553        }
9554
9555        int doPostInstall(int status, int uid) {
9556            if (status != PackageManager.INSTALL_SUCCEEDED) {
9557                cleanUp();
9558            } else {
9559                final int groupOwner;
9560                final String protectedFile;
9561                if (isFwdLocked()) {
9562                    groupOwner = UserHandle.getSharedAppGid(uid);
9563                    protectedFile = RES_FILE_NAME;
9564                } else {
9565                    groupOwner = -1;
9566                    protectedFile = null;
9567                }
9568
9569                if (uid < Process.FIRST_APPLICATION_UID
9570                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9571                    Slog.e(TAG, "Failed to finalize " + cid);
9572                    PackageHelper.destroySdDir(cid);
9573                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9574                }
9575
9576                boolean mounted = PackageHelper.isContainerMounted(cid);
9577                if (!mounted) {
9578                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9579                }
9580            }
9581            return status;
9582        }
9583
9584        private void cleanUp() {
9585            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9586
9587            // Destroy secure container
9588            PackageHelper.destroySdDir(cid);
9589        }
9590
9591        private List<String> getAllCodePaths() {
9592            final File codeFile = new File(getCodePath());
9593            if (codeFile != null && codeFile.exists()) {
9594                try {
9595                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9596                    return pkg.getAllCodePaths();
9597                } catch (PackageParserException e) {
9598                    // Ignored; we tried our best
9599                }
9600            }
9601            return Collections.EMPTY_LIST;
9602        }
9603
9604        void cleanUpResourcesLI() {
9605            // Enumerate all code paths before deleting
9606            cleanUpResourcesLI(getAllCodePaths());
9607        }
9608
9609        private void cleanUpResourcesLI(List<String> allCodePaths) {
9610            cleanUp();
9611
9612            if (!allCodePaths.isEmpty()) {
9613                if (instructionSets == null) {
9614                    throw new IllegalStateException("instructionSet == null");
9615                }
9616                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9617                for (String codePath : allCodePaths) {
9618                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9619                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9620                        if (retCode < 0) {
9621                            Slog.w(TAG, "Couldn't remove dex file for package: "
9622                                    + " at location " + codePath + ", retcode=" + retCode);
9623                            // we don't consider this to be a failure of the core package deletion
9624                        }
9625                    }
9626                }
9627            }
9628        }
9629
9630        boolean matchContainer(String app) {
9631            if (cid.startsWith(app)) {
9632                return true;
9633            }
9634            return false;
9635        }
9636
9637        String getPackageName() {
9638            return getAsecPackageName(cid);
9639        }
9640
9641        boolean doPostDeleteLI(boolean delete) {
9642            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9643            final List<String> allCodePaths = getAllCodePaths();
9644            boolean mounted = PackageHelper.isContainerMounted(cid);
9645            if (mounted) {
9646                // Unmount first
9647                if (PackageHelper.unMountSdDir(cid)) {
9648                    mounted = false;
9649                }
9650            }
9651            if (!mounted && delete) {
9652                cleanUpResourcesLI(allCodePaths);
9653            }
9654            return !mounted;
9655        }
9656
9657        @Override
9658        int doPreCopy() {
9659            if (isFwdLocked()) {
9660                if (!PackageHelper.fixSdPermissions(cid,
9661                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9662                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9663                }
9664            }
9665
9666            return PackageManager.INSTALL_SUCCEEDED;
9667        }
9668
9669        @Override
9670        int doPostCopy(int uid) {
9671            if (isFwdLocked()) {
9672                if (uid < Process.FIRST_APPLICATION_UID
9673                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9674                                RES_FILE_NAME)) {
9675                    Slog.e(TAG, "Failed to finalize " + cid);
9676                    PackageHelper.destroySdDir(cid);
9677                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9678                }
9679            }
9680
9681            return PackageManager.INSTALL_SUCCEEDED;
9682        }
9683    }
9684
9685    static String getAsecPackageName(String packageCid) {
9686        int idx = packageCid.lastIndexOf("-");
9687        if (idx == -1) {
9688            return packageCid;
9689        }
9690        return packageCid.substring(0, idx);
9691    }
9692
9693    // Utility method used to create code paths based on package name and available index.
9694    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9695        String idxStr = "";
9696        int idx = 1;
9697        // Fall back to default value of idx=1 if prefix is not
9698        // part of oldCodePath
9699        if (oldCodePath != null) {
9700            String subStr = oldCodePath;
9701            // Drop the suffix right away
9702            if (suffix != null && subStr.endsWith(suffix)) {
9703                subStr = subStr.substring(0, subStr.length() - suffix.length());
9704            }
9705            // If oldCodePath already contains prefix find out the
9706            // ending index to either increment or decrement.
9707            int sidx = subStr.lastIndexOf(prefix);
9708            if (sidx != -1) {
9709                subStr = subStr.substring(sidx + prefix.length());
9710                if (subStr != null) {
9711                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9712                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9713                    }
9714                    try {
9715                        idx = Integer.parseInt(subStr);
9716                        if (idx <= 1) {
9717                            idx++;
9718                        } else {
9719                            idx--;
9720                        }
9721                    } catch(NumberFormatException e) {
9722                    }
9723                }
9724            }
9725        }
9726        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9727        return prefix + idxStr;
9728    }
9729
9730    private File getNextCodePath(String packageName) {
9731        int suffix = 1;
9732        File result;
9733        do {
9734            result = new File(mAppInstallDir, packageName + "-" + suffix);
9735            suffix++;
9736        } while (result.exists());
9737        return result;
9738    }
9739
9740    // Utility method used to ignore ADD/REMOVE events
9741    // by directory observer.
9742    private static boolean ignoreCodePath(String fullPathStr) {
9743        String apkName = deriveCodePathName(fullPathStr);
9744        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9745        if (idx != -1 && ((idx+1) < apkName.length())) {
9746            // Make sure the package ends with a numeral
9747            String version = apkName.substring(idx+1);
9748            try {
9749                Integer.parseInt(version);
9750                return true;
9751            } catch (NumberFormatException e) {}
9752        }
9753        return false;
9754    }
9755
9756    // Utility method that returns the relative package path with respect
9757    // to the installation directory. Like say for /data/data/com.test-1.apk
9758    // string com.test-1 is returned.
9759    static String deriveCodePathName(String codePath) {
9760        if (codePath == null) {
9761            return null;
9762        }
9763        final File codeFile = new File(codePath);
9764        final String name = codeFile.getName();
9765        if (codeFile.isDirectory()) {
9766            return name;
9767        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9768            final int lastDot = name.lastIndexOf('.');
9769            return name.substring(0, lastDot);
9770        } else {
9771            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9772            return null;
9773        }
9774    }
9775
9776    class PackageInstalledInfo {
9777        String name;
9778        int uid;
9779        // The set of users that originally had this package installed.
9780        int[] origUsers;
9781        // The set of users that now have this package installed.
9782        int[] newUsers;
9783        PackageParser.Package pkg;
9784        int returnCode;
9785        String returnMsg;
9786        PackageRemovedInfo removedInfo;
9787
9788        public void setError(int code, String msg) {
9789            returnCode = code;
9790            returnMsg = msg;
9791            Slog.w(TAG, msg);
9792        }
9793
9794        public void setError(String msg, PackageParserException e) {
9795            returnCode = e.error;
9796            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9797            Slog.w(TAG, msg, e);
9798        }
9799
9800        public void setError(String msg, PackageManagerException e) {
9801            returnCode = e.error;
9802            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9803            Slog.w(TAG, msg, e);
9804        }
9805
9806        // In some error cases we want to convey more info back to the observer
9807        String origPackage;
9808        String origPermission;
9809    }
9810
9811    /*
9812     * Install a non-existing package.
9813     */
9814    private void installNewPackageLI(PackageParser.Package pkg,
9815            int parseFlags, int scanFlags, UserHandle user,
9816            String installerPackageName, PackageInstalledInfo res) {
9817        // Remember this for later, in case we need to rollback this install
9818        String pkgName = pkg.packageName;
9819
9820        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9821        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9822        synchronized(mPackages) {
9823            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9824                // A package with the same name is already installed, though
9825                // it has been renamed to an older name.  The package we
9826                // are trying to install should be installed as an update to
9827                // the existing one, but that has not been requested, so bail.
9828                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9829                        + " without first uninstalling package running as "
9830                        + mSettings.mRenamedPackages.get(pkgName));
9831                return;
9832            }
9833            if (mPackages.containsKey(pkgName)) {
9834                // Don't allow installation over an existing package with the same name.
9835                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9836                        + " without first uninstalling.");
9837                return;
9838            }
9839        }
9840
9841        try {
9842            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9843                    System.currentTimeMillis(), user);
9844
9845            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9846            // delete the partially installed application. the data directory will have to be
9847            // restored if it was already existing
9848            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9849                // remove package from internal structures.  Note that we want deletePackageX to
9850                // delete the package data and cache directories that it created in
9851                // scanPackageLocked, unless those directories existed before we even tried to
9852                // install.
9853                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9854                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9855                                res.removedInfo, true);
9856            }
9857
9858        } catch (PackageManagerException e) {
9859            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9860        }
9861    }
9862
9863    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9864        // Upgrade keysets are being used.  Determine if new package has a superset of the
9865        // required keys.
9866        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9867        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9868        for (int i = 0; i < upgradeKeySets.length; i++) {
9869            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9870            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9871                return true;
9872            }
9873        }
9874        return false;
9875    }
9876
9877    private void replacePackageLI(PackageParser.Package pkg,
9878            int parseFlags, int scanFlags, UserHandle user,
9879            String installerPackageName, PackageInstalledInfo res) {
9880        PackageParser.Package oldPackage;
9881        String pkgName = pkg.packageName;
9882        int[] allUsers;
9883        boolean[] perUserInstalled;
9884
9885        // First find the old package info and check signatures
9886        synchronized(mPackages) {
9887            oldPackage = mPackages.get(pkgName);
9888            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9889            PackageSetting ps = mSettings.mPackages.get(pkgName);
9890            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9891                // default to original signature matching
9892                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9893                    != PackageManager.SIGNATURE_MATCH) {
9894                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9895                            "New package has a different signature: " + pkgName);
9896                    return;
9897                }
9898            } else {
9899                if(!checkUpgradeKeySetLP(ps, pkg)) {
9900                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9901                            "New package not signed by keys specified by upgrade-keysets: "
9902                            + pkgName);
9903                    return;
9904                }
9905            }
9906
9907            // In case of rollback, remember per-user/profile install state
9908            allUsers = sUserManager.getUserIds();
9909            perUserInstalled = new boolean[allUsers.length];
9910            for (int i = 0; i < allUsers.length; i++) {
9911                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9912            }
9913        }
9914
9915        boolean sysPkg = (isSystemApp(oldPackage));
9916        if (sysPkg) {
9917            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9918                    user, allUsers, perUserInstalled, installerPackageName, res);
9919        } else {
9920            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9921                    user, allUsers, perUserInstalled, installerPackageName, res);
9922        }
9923    }
9924
9925    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9926            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9927            int[] allUsers, boolean[] perUserInstalled,
9928            String installerPackageName, PackageInstalledInfo res) {
9929        String pkgName = deletedPackage.packageName;
9930        boolean deletedPkg = true;
9931        boolean updatedSettings = false;
9932
9933        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9934                + deletedPackage);
9935        long origUpdateTime;
9936        if (pkg.mExtras != null) {
9937            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9938        } else {
9939            origUpdateTime = 0;
9940        }
9941
9942        // First delete the existing package while retaining the data directory
9943        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9944                res.removedInfo, true)) {
9945            // If the existing package wasn't successfully deleted
9946            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9947            deletedPkg = false;
9948        } else {
9949            // Successfully deleted the old package; proceed with replace.
9950
9951            // If deleted package lived in a container, give users a chance to
9952            // relinquish resources before killing.
9953            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9954                if (DEBUG_INSTALL) {
9955                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9956                }
9957                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9958                final ArrayList<String> pkgList = new ArrayList<String>(1);
9959                pkgList.add(deletedPackage.applicationInfo.packageName);
9960                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9961            }
9962
9963            deleteCodeCacheDirsLI(pkgName);
9964            try {
9965                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9966                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9967                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9968                updatedSettings = true;
9969            } catch (PackageManagerException e) {
9970                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9971            }
9972        }
9973
9974        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9975            // remove package from internal structures.  Note that we want deletePackageX to
9976            // delete the package data and cache directories that it created in
9977            // scanPackageLocked, unless those directories existed before we even tried to
9978            // install.
9979            if(updatedSettings) {
9980                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9981                deletePackageLI(
9982                        pkgName, null, true, allUsers, perUserInstalled,
9983                        PackageManager.DELETE_KEEP_DATA,
9984                                res.removedInfo, true);
9985            }
9986            // Since we failed to install the new package we need to restore the old
9987            // package that we deleted.
9988            if (deletedPkg) {
9989                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9990                File restoreFile = new File(deletedPackage.codePath);
9991                // Parse old package
9992                boolean oldOnSd = isExternal(deletedPackage);
9993                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9994                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9995                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9996                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9997                try {
9998                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9999                } catch (PackageManagerException e) {
10000                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10001                            + e.getMessage());
10002                    return;
10003                }
10004                // Restore of old package succeeded. Update permissions.
10005                // writer
10006                synchronized (mPackages) {
10007                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10008                            UPDATE_PERMISSIONS_ALL);
10009                    // can downgrade to reader
10010                    mSettings.writeLPr();
10011                }
10012                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10013            }
10014        }
10015    }
10016
10017    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10018            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10019            int[] allUsers, boolean[] perUserInstalled,
10020            String installerPackageName, PackageInstalledInfo res) {
10021        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10022                + ", old=" + deletedPackage);
10023        boolean updatedSettings = false;
10024        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10025        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10026            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10027        }
10028        String packageName = deletedPackage.packageName;
10029        if (packageName == null) {
10030            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10031                    "Attempt to delete null packageName.");
10032            return;
10033        }
10034        PackageParser.Package oldPkg;
10035        PackageSetting oldPkgSetting;
10036        // reader
10037        synchronized (mPackages) {
10038            oldPkg = mPackages.get(packageName);
10039            oldPkgSetting = mSettings.mPackages.get(packageName);
10040            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10041                    (oldPkgSetting == null)) {
10042                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10043                        "Couldn't find package:" + packageName + " information");
10044                return;
10045            }
10046        }
10047
10048        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10049
10050        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10051        res.removedInfo.removedPackage = packageName;
10052        // Remove existing system package
10053        removePackageLI(oldPkgSetting, true);
10054        // writer
10055        synchronized (mPackages) {
10056            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10057                // We didn't need to disable the .apk as a current system package,
10058                // which means we are replacing another update that is already
10059                // installed.  We need to make sure to delete the older one's .apk.
10060                res.removedInfo.args = createInstallArgsForExisting(0,
10061                        deletedPackage.applicationInfo.getCodePath(),
10062                        deletedPackage.applicationInfo.getResourcePath(),
10063                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10064                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10065            } else {
10066                res.removedInfo.args = null;
10067            }
10068        }
10069
10070        // Successfully disabled the old package. Now proceed with re-installation
10071        deleteCodeCacheDirsLI(packageName);
10072
10073        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10074        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10075
10076        PackageParser.Package newPackage = null;
10077        try {
10078            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10079            if (newPackage.mExtras != null) {
10080                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10081                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10082                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10083
10084                // is the update attempting to change shared user? that isn't going to work...
10085                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10086                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10087                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10088                            + " to " + newPkgSetting.sharedUser);
10089                    updatedSettings = true;
10090                }
10091            }
10092
10093            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10094                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10095                updatedSettings = true;
10096            }
10097
10098        } catch (PackageManagerException e) {
10099            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10100        }
10101
10102        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10103            // Re installation failed. Restore old information
10104            // Remove new pkg information
10105            if (newPackage != null) {
10106                removeInstalledPackageLI(newPackage, true);
10107            }
10108            // Add back the old system package
10109            try {
10110                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10111            } catch (PackageManagerException e) {
10112                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10113            }
10114            // Restore the old system information in Settings
10115            synchronized(mPackages) {
10116                if (updatedSettings) {
10117                    mSettings.enableSystemPackageLPw(packageName);
10118                    mSettings.setInstallerPackageName(packageName,
10119                            oldPkgSetting.installerPackageName);
10120                }
10121                mSettings.writeLPr();
10122            }
10123        }
10124    }
10125
10126    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10127            int[] allUsers, boolean[] perUserInstalled,
10128            PackageInstalledInfo res) {
10129        String pkgName = newPackage.packageName;
10130        synchronized (mPackages) {
10131            //write settings. the installStatus will be incomplete at this stage.
10132            //note that the new package setting would have already been
10133            //added to mPackages. It hasn't been persisted yet.
10134            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10135            mSettings.writeLPr();
10136        }
10137
10138        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10139
10140        synchronized (mPackages) {
10141            updatePermissionsLPw(newPackage.packageName, newPackage,
10142                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10143                            ? UPDATE_PERMISSIONS_ALL : 0));
10144            // For system-bundled packages, we assume that installing an upgraded version
10145            // of the package implies that the user actually wants to run that new code,
10146            // so we enable the package.
10147            if (isSystemApp(newPackage)) {
10148                // NB: implicit assumption that system package upgrades apply to all users
10149                if (DEBUG_INSTALL) {
10150                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10151                }
10152                PackageSetting ps = mSettings.mPackages.get(pkgName);
10153                if (ps != null) {
10154                    if (res.origUsers != null) {
10155                        for (int userHandle : res.origUsers) {
10156                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10157                                    userHandle, installerPackageName);
10158                        }
10159                    }
10160                    // Also convey the prior install/uninstall state
10161                    if (allUsers != null && perUserInstalled != null) {
10162                        for (int i = 0; i < allUsers.length; i++) {
10163                            if (DEBUG_INSTALL) {
10164                                Slog.d(TAG, "    user " + allUsers[i]
10165                                        + " => " + perUserInstalled[i]);
10166                            }
10167                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10168                        }
10169                        // these install state changes will be persisted in the
10170                        // upcoming call to mSettings.writeLPr().
10171                    }
10172                }
10173            }
10174            res.name = pkgName;
10175            res.uid = newPackage.applicationInfo.uid;
10176            res.pkg = newPackage;
10177            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10178            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10179            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10180            //to update install status
10181            mSettings.writeLPr();
10182        }
10183    }
10184
10185    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10186        final int installFlags = args.installFlags;
10187        String installerPackageName = args.installerPackageName;
10188        File tmpPackageFile = new File(args.getCodePath());
10189        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10190        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10191        boolean replace = false;
10192        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10193        // Result object to be returned
10194        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10195
10196        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10197        // Retrieve PackageSettings and parse package
10198        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10199                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10200                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10201        PackageParser pp = new PackageParser();
10202        pp.setSeparateProcesses(mSeparateProcesses);
10203        pp.setDisplayMetrics(mMetrics);
10204
10205        final PackageParser.Package pkg;
10206        try {
10207            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10208        } catch (PackageParserException e) {
10209            res.setError("Failed parse during installPackageLI", e);
10210            return;
10211        }
10212
10213        // Mark that we have an install time CPU ABI override.
10214        pkg.cpuAbiOverride = args.abiOverride;
10215
10216        String pkgName = res.name = pkg.packageName;
10217        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10218            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10219                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10220                return;
10221            }
10222        }
10223
10224        try {
10225            pp.collectCertificates(pkg, parseFlags);
10226            pp.collectManifestDigest(pkg);
10227        } catch (PackageParserException e) {
10228            res.setError("Failed collect during installPackageLI", e);
10229            return;
10230        }
10231
10232        /* If the installer passed in a manifest digest, compare it now. */
10233        if (args.manifestDigest != null) {
10234            if (DEBUG_INSTALL) {
10235                final String parsedManifest = pkg.manifestDigest == null ? "null"
10236                        : pkg.manifestDigest.toString();
10237                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10238                        + parsedManifest);
10239            }
10240
10241            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10242                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10243                return;
10244            }
10245        } else if (DEBUG_INSTALL) {
10246            final String parsedManifest = pkg.manifestDigest == null
10247                    ? "null" : pkg.manifestDigest.toString();
10248            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10249        }
10250
10251        // Get rid of all references to package scan path via parser.
10252        pp = null;
10253        String oldCodePath = null;
10254        boolean systemApp = false;
10255        synchronized (mPackages) {
10256            // Check whether the newly-scanned package wants to define an already-defined perm
10257            int N = pkg.permissions.size();
10258            for (int i = N-1; i >= 0; i--) {
10259                PackageParser.Permission perm = pkg.permissions.get(i);
10260                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10261                if (bp != null) {
10262                    // If the defining package is signed with our cert, it's okay.  This
10263                    // also includes the "updating the same package" case, of course.
10264                    // "updating same package" could also involve key-rotation.
10265                    final boolean sigsOk;
10266                    if (!bp.sourcePackage.equals(pkg.packageName)
10267                            || !(bp.packageSetting instanceof PackageSetting)
10268                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10269                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10270                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10271                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10272                    } else {
10273                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10274                    }
10275                    if (!sigsOk) {
10276                        // If the owning package is the system itself, we log but allow
10277                        // install to proceed; we fail the install on all other permission
10278                        // redefinitions.
10279                        if (!bp.sourcePackage.equals("android")) {
10280                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10281                                    + pkg.packageName + " attempting to redeclare permission "
10282                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10283                            res.origPermission = perm.info.name;
10284                            res.origPackage = bp.sourcePackage;
10285                            return;
10286                        } else {
10287                            Slog.w(TAG, "Package " + pkg.packageName
10288                                    + " attempting to redeclare system permission "
10289                                    + perm.info.name + "; ignoring new declaration");
10290                            pkg.permissions.remove(i);
10291                        }
10292                    }
10293                }
10294            }
10295
10296            // Check if installing already existing package
10297            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10298                String oldName = mSettings.mRenamedPackages.get(pkgName);
10299                if (pkg.mOriginalPackages != null
10300                        && pkg.mOriginalPackages.contains(oldName)
10301                        && mPackages.containsKey(oldName)) {
10302                    // This package is derived from an original package,
10303                    // and this device has been updating from that original
10304                    // name.  We must continue using the original name, so
10305                    // rename the new package here.
10306                    pkg.setPackageName(oldName);
10307                    pkgName = pkg.packageName;
10308                    replace = true;
10309                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10310                            + oldName + " pkgName=" + pkgName);
10311                } else if (mPackages.containsKey(pkgName)) {
10312                    // This package, under its official name, already exists
10313                    // on the device; we should replace it.
10314                    replace = true;
10315                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10316                }
10317            }
10318            PackageSetting ps = mSettings.mPackages.get(pkgName);
10319            if (ps != null) {
10320                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10321                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10322                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10323                    systemApp = (ps.pkg.applicationInfo.flags &
10324                            ApplicationInfo.FLAG_SYSTEM) != 0;
10325                }
10326                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10327            }
10328        }
10329
10330        if (systemApp && onSd) {
10331            // Disable updates to system apps on sdcard
10332            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10333                    "Cannot install updates to system apps on sdcard");
10334            return;
10335        }
10336
10337        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10338            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10339            return;
10340        }
10341
10342        if (replace) {
10343            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10344                    installerPackageName, res);
10345        } else {
10346            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10347                    args.user, installerPackageName, res);
10348        }
10349        synchronized (mPackages) {
10350            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10351            if (ps != null) {
10352                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10353            }
10354        }
10355    }
10356
10357    private static boolean isForwardLocked(PackageParser.Package pkg) {
10358        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10359    }
10360
10361    private static boolean isForwardLocked(ApplicationInfo info) {
10362        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10363    }
10364
10365    private boolean isForwardLocked(PackageSetting ps) {
10366        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10367    }
10368
10369    private static boolean isMultiArch(PackageSetting ps) {
10370        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10371    }
10372
10373    private static boolean isMultiArch(ApplicationInfo info) {
10374        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10375    }
10376
10377    private static boolean isExternal(PackageParser.Package pkg) {
10378        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10379    }
10380
10381    private static boolean isExternal(PackageSetting ps) {
10382        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10383    }
10384
10385    private static boolean isExternal(ApplicationInfo info) {
10386        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10387    }
10388
10389    private static boolean isSystemApp(PackageParser.Package pkg) {
10390        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10391    }
10392
10393    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10394        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10395    }
10396
10397    private static boolean isSystemApp(ApplicationInfo info) {
10398        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10399    }
10400
10401    private static boolean isSystemApp(PackageSetting ps) {
10402        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10403    }
10404
10405    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10406        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10407    }
10408
10409    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10410        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10411    }
10412
10413    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10414        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10415    }
10416
10417    private int packageFlagsToInstallFlags(PackageSetting ps) {
10418        int installFlags = 0;
10419        if (isExternal(ps)) {
10420            installFlags |= PackageManager.INSTALL_EXTERNAL;
10421        }
10422        if (isForwardLocked(ps)) {
10423            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10424        }
10425        return installFlags;
10426    }
10427
10428    private void deleteTempPackageFiles() {
10429        final FilenameFilter filter = new FilenameFilter() {
10430            public boolean accept(File dir, String name) {
10431                return name.startsWith("vmdl") && name.endsWith(".tmp");
10432            }
10433        };
10434        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10435            file.delete();
10436        }
10437    }
10438
10439    @Override
10440    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10441            int flags) {
10442        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10443                flags);
10444    }
10445
10446    @Override
10447    public void deletePackage(final String packageName,
10448            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10449        mContext.enforceCallingOrSelfPermission(
10450                android.Manifest.permission.DELETE_PACKAGES, null);
10451        final int uid = Binder.getCallingUid();
10452        if (UserHandle.getUserId(uid) != userId) {
10453            mContext.enforceCallingPermission(
10454                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10455                    "deletePackage for user " + userId);
10456        }
10457        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10458            try {
10459                observer.onPackageDeleted(packageName,
10460                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10461            } catch (RemoteException re) {
10462            }
10463            return;
10464        }
10465
10466        boolean uninstallBlocked = false;
10467        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10468            int[] users = sUserManager.getUserIds();
10469            for (int i = 0; i < users.length; ++i) {
10470                if (getBlockUninstallForUser(packageName, users[i])) {
10471                    uninstallBlocked = true;
10472                    break;
10473                }
10474            }
10475        } else {
10476            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10477        }
10478        if (uninstallBlocked) {
10479            try {
10480                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10481                        null);
10482            } catch (RemoteException re) {
10483            }
10484            return;
10485        }
10486
10487        if (DEBUG_REMOVE) {
10488            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10489        }
10490        // Queue up an async operation since the package deletion may take a little while.
10491        mHandler.post(new Runnable() {
10492            public void run() {
10493                mHandler.removeCallbacks(this);
10494                final int returnCode = deletePackageX(packageName, userId, flags);
10495                if (observer != null) {
10496                    try {
10497                        observer.onPackageDeleted(packageName, returnCode, null);
10498                    } catch (RemoteException e) {
10499                        Log.i(TAG, "Observer no longer exists.");
10500                    } //end catch
10501                } //end if
10502            } //end run
10503        });
10504    }
10505
10506    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10507        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10508                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10509        try {
10510            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10511                    || dpm.isDeviceOwner(packageName))) {
10512                return true;
10513            }
10514        } catch (RemoteException e) {
10515        }
10516        return false;
10517    }
10518
10519    /**
10520     *  This method is an internal method that could be get invoked either
10521     *  to delete an installed package or to clean up a failed installation.
10522     *  After deleting an installed package, a broadcast is sent to notify any
10523     *  listeners that the package has been installed. For cleaning up a failed
10524     *  installation, the broadcast is not necessary since the package's
10525     *  installation wouldn't have sent the initial broadcast either
10526     *  The key steps in deleting a package are
10527     *  deleting the package information in internal structures like mPackages,
10528     *  deleting the packages base directories through installd
10529     *  updating mSettings to reflect current status
10530     *  persisting settings for later use
10531     *  sending a broadcast if necessary
10532     */
10533    private int deletePackageX(String packageName, int userId, int flags) {
10534        final PackageRemovedInfo info = new PackageRemovedInfo();
10535        final boolean res;
10536
10537        if (isPackageDeviceAdmin(packageName, userId)) {
10538            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10539            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10540        }
10541
10542        boolean removedForAllUsers = false;
10543        boolean systemUpdate = false;
10544
10545        // for the uninstall-updates case and restricted profiles, remember the per-
10546        // userhandle installed state
10547        int[] allUsers;
10548        boolean[] perUserInstalled;
10549        synchronized (mPackages) {
10550            PackageSetting ps = mSettings.mPackages.get(packageName);
10551            allUsers = sUserManager.getUserIds();
10552            perUserInstalled = new boolean[allUsers.length];
10553            for (int i = 0; i < allUsers.length; i++) {
10554                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10555            }
10556        }
10557
10558        synchronized (mInstallLock) {
10559            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10560            res = deletePackageLI(packageName,
10561                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10562                            ? UserHandle.ALL : new UserHandle(userId),
10563                    true, allUsers, perUserInstalled,
10564                    flags | REMOVE_CHATTY, info, true);
10565            systemUpdate = info.isRemovedPackageSystemUpdate;
10566            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10567                removedForAllUsers = true;
10568            }
10569            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10570                    + " removedForAllUsers=" + removedForAllUsers);
10571        }
10572
10573        if (res) {
10574            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10575
10576            // If the removed package was a system update, the old system package
10577            // was re-enabled; we need to broadcast this information
10578            if (systemUpdate) {
10579                Bundle extras = new Bundle(1);
10580                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10581                        ? info.removedAppId : info.uid);
10582                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10583
10584                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10585                        extras, null, null, null);
10586                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10587                        extras, null, null, null);
10588                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10589                        null, packageName, null, null);
10590            }
10591        }
10592        // Force a gc here.
10593        Runtime.getRuntime().gc();
10594        // Delete the resources here after sending the broadcast to let
10595        // other processes clean up before deleting resources.
10596        if (info.args != null) {
10597            synchronized (mInstallLock) {
10598                info.args.doPostDeleteLI(true);
10599            }
10600        }
10601
10602        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10603    }
10604
10605    static class PackageRemovedInfo {
10606        String removedPackage;
10607        int uid = -1;
10608        int removedAppId = -1;
10609        int[] removedUsers = null;
10610        boolean isRemovedPackageSystemUpdate = false;
10611        // Clean up resources deleted packages.
10612        InstallArgs args = null;
10613
10614        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10615            Bundle extras = new Bundle(1);
10616            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10617            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10618            if (replacing) {
10619                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10620            }
10621            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10622            if (removedPackage != null) {
10623                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10624                        extras, null, null, removedUsers);
10625                if (fullRemove && !replacing) {
10626                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10627                            extras, null, null, removedUsers);
10628                }
10629            }
10630            if (removedAppId >= 0) {
10631                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10632                        removedUsers);
10633            }
10634        }
10635    }
10636
10637    /*
10638     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10639     * flag is not set, the data directory is removed as well.
10640     * make sure this flag is set for partially installed apps. If not its meaningless to
10641     * delete a partially installed application.
10642     */
10643    private void removePackageDataLI(PackageSetting ps,
10644            int[] allUserHandles, boolean[] perUserInstalled,
10645            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10646        String packageName = ps.name;
10647        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10648        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10649        // Retrieve object to delete permissions for shared user later on
10650        final PackageSetting deletedPs;
10651        // reader
10652        synchronized (mPackages) {
10653            deletedPs = mSettings.mPackages.get(packageName);
10654            if (outInfo != null) {
10655                outInfo.removedPackage = packageName;
10656                outInfo.removedUsers = deletedPs != null
10657                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10658                        : null;
10659            }
10660        }
10661        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10662            removeDataDirsLI(packageName);
10663            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10664        }
10665        // writer
10666        synchronized (mPackages) {
10667            if (deletedPs != null) {
10668                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10669                    if (outInfo != null) {
10670                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10671                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10672                    }
10673                    if (deletedPs != null) {
10674                        updatePermissionsLPw(deletedPs.name, null, 0);
10675                        if (deletedPs.sharedUser != null) {
10676                            // remove permissions associated with package
10677                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10678                        }
10679                    }
10680                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10681                }
10682                // make sure to preserve per-user disabled state if this removal was just
10683                // a downgrade of a system app to the factory package
10684                if (allUserHandles != null && perUserInstalled != null) {
10685                    if (DEBUG_REMOVE) {
10686                        Slog.d(TAG, "Propagating install state across downgrade");
10687                    }
10688                    for (int i = 0; i < allUserHandles.length; i++) {
10689                        if (DEBUG_REMOVE) {
10690                            Slog.d(TAG, "    user " + allUserHandles[i]
10691                                    + " => " + perUserInstalled[i]);
10692                        }
10693                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10694                    }
10695                }
10696            }
10697            // can downgrade to reader
10698            if (writeSettings) {
10699                // Save settings now
10700                mSettings.writeLPr();
10701            }
10702        }
10703        if (outInfo != null) {
10704            // A user ID was deleted here. Go through all users and remove it
10705            // from KeyStore.
10706            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10707        }
10708    }
10709
10710    static boolean locationIsPrivileged(File path) {
10711        try {
10712            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10713                    .getCanonicalPath();
10714            return path.getCanonicalPath().startsWith(privilegedAppDir);
10715        } catch (IOException e) {
10716            Slog.e(TAG, "Unable to access code path " + path);
10717        }
10718        return false;
10719    }
10720
10721    /*
10722     * Tries to delete system package.
10723     */
10724    private boolean deleteSystemPackageLI(PackageSetting newPs,
10725            int[] allUserHandles, boolean[] perUserInstalled,
10726            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10727        final boolean applyUserRestrictions
10728                = (allUserHandles != null) && (perUserInstalled != null);
10729        PackageSetting disabledPs = null;
10730        // Confirm if the system package has been updated
10731        // An updated system app can be deleted. This will also have to restore
10732        // the system pkg from system partition
10733        // reader
10734        synchronized (mPackages) {
10735            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10736        }
10737        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10738                + " disabledPs=" + disabledPs);
10739        if (disabledPs == null) {
10740            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10741            return false;
10742        } else if (DEBUG_REMOVE) {
10743            Slog.d(TAG, "Deleting system pkg from data partition");
10744        }
10745        if (DEBUG_REMOVE) {
10746            if (applyUserRestrictions) {
10747                Slog.d(TAG, "Remembering install states:");
10748                for (int i = 0; i < allUserHandles.length; i++) {
10749                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10750                }
10751            }
10752        }
10753        // Delete the updated package
10754        outInfo.isRemovedPackageSystemUpdate = true;
10755        if (disabledPs.versionCode < newPs.versionCode) {
10756            // Delete data for downgrades
10757            flags &= ~PackageManager.DELETE_KEEP_DATA;
10758        } else {
10759            // Preserve data by setting flag
10760            flags |= PackageManager.DELETE_KEEP_DATA;
10761        }
10762        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10763                allUserHandles, perUserInstalled, outInfo, writeSettings);
10764        if (!ret) {
10765            return false;
10766        }
10767        // writer
10768        synchronized (mPackages) {
10769            // Reinstate the old system package
10770            mSettings.enableSystemPackageLPw(newPs.name);
10771            // Remove any native libraries from the upgraded package.
10772            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10773        }
10774        // Install the system package
10775        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10776        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10777        if (locationIsPrivileged(disabledPs.codePath)) {
10778            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10779        }
10780
10781        final PackageParser.Package newPkg;
10782        try {
10783            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10784        } catch (PackageManagerException e) {
10785            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10786            return false;
10787        }
10788
10789        // writer
10790        synchronized (mPackages) {
10791            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10792            updatePermissionsLPw(newPkg.packageName, newPkg,
10793                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10794            if (applyUserRestrictions) {
10795                if (DEBUG_REMOVE) {
10796                    Slog.d(TAG, "Propagating install state across reinstall");
10797                }
10798                for (int i = 0; i < allUserHandles.length; i++) {
10799                    if (DEBUG_REMOVE) {
10800                        Slog.d(TAG, "    user " + allUserHandles[i]
10801                                + " => " + perUserInstalled[i]);
10802                    }
10803                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10804                }
10805                // Regardless of writeSettings we need to ensure that this restriction
10806                // state propagation is persisted
10807                mSettings.writeAllUsersPackageRestrictionsLPr();
10808            }
10809            // can downgrade to reader here
10810            if (writeSettings) {
10811                mSettings.writeLPr();
10812            }
10813        }
10814        return true;
10815    }
10816
10817    private boolean deleteInstalledPackageLI(PackageSetting ps,
10818            boolean deleteCodeAndResources, int flags,
10819            int[] allUserHandles, boolean[] perUserInstalled,
10820            PackageRemovedInfo outInfo, boolean writeSettings) {
10821        if (outInfo != null) {
10822            outInfo.uid = ps.appId;
10823        }
10824
10825        // Delete package data from internal structures and also remove data if flag is set
10826        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10827
10828        // Delete application code and resources
10829        if (deleteCodeAndResources && (outInfo != null)) {
10830            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10831                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10832                    getAppDexInstructionSets(ps));
10833            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10834        }
10835        return true;
10836    }
10837
10838    @Override
10839    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10840            int userId) {
10841        mContext.enforceCallingOrSelfPermission(
10842                android.Manifest.permission.DELETE_PACKAGES, null);
10843        synchronized (mPackages) {
10844            PackageSetting ps = mSettings.mPackages.get(packageName);
10845            if (ps == null) {
10846                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10847                return false;
10848            }
10849            if (!ps.getInstalled(userId)) {
10850                // Can't block uninstall for an app that is not installed or enabled.
10851                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10852                return false;
10853            }
10854            ps.setBlockUninstall(blockUninstall, userId);
10855            mSettings.writePackageRestrictionsLPr(userId);
10856        }
10857        return true;
10858    }
10859
10860    @Override
10861    public boolean getBlockUninstallForUser(String packageName, int userId) {
10862        synchronized (mPackages) {
10863            PackageSetting ps = mSettings.mPackages.get(packageName);
10864            if (ps == null) {
10865                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10866                return false;
10867            }
10868            return ps.getBlockUninstall(userId);
10869        }
10870    }
10871
10872    /*
10873     * This method handles package deletion in general
10874     */
10875    private boolean deletePackageLI(String packageName, UserHandle user,
10876            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10877            int flags, PackageRemovedInfo outInfo,
10878            boolean writeSettings) {
10879        if (packageName == null) {
10880            Slog.w(TAG, "Attempt to delete null packageName.");
10881            return false;
10882        }
10883        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10884        PackageSetting ps;
10885        boolean dataOnly = false;
10886        int removeUser = -1;
10887        int appId = -1;
10888        synchronized (mPackages) {
10889            ps = mSettings.mPackages.get(packageName);
10890            if (ps == null) {
10891                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10892                return false;
10893            }
10894            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10895                    && user.getIdentifier() != UserHandle.USER_ALL) {
10896                // The caller is asking that the package only be deleted for a single
10897                // user.  To do this, we just mark its uninstalled state and delete
10898                // its data.  If this is a system app, we only allow this to happen if
10899                // they have set the special DELETE_SYSTEM_APP which requests different
10900                // semantics than normal for uninstalling system apps.
10901                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10902                ps.setUserState(user.getIdentifier(),
10903                        COMPONENT_ENABLED_STATE_DEFAULT,
10904                        false, //installed
10905                        true,  //stopped
10906                        true,  //notLaunched
10907                        false, //hidden
10908                        null, null, null,
10909                        false // blockUninstall
10910                        );
10911                if (!isSystemApp(ps)) {
10912                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10913                        // Other user still have this package installed, so all
10914                        // we need to do is clear this user's data and save that
10915                        // it is uninstalled.
10916                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10917                        removeUser = user.getIdentifier();
10918                        appId = ps.appId;
10919                        mSettings.writePackageRestrictionsLPr(removeUser);
10920                    } else {
10921                        // We need to set it back to 'installed' so the uninstall
10922                        // broadcasts will be sent correctly.
10923                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10924                        ps.setInstalled(true, user.getIdentifier());
10925                    }
10926                } else {
10927                    // This is a system app, so we assume that the
10928                    // other users still have this package installed, so all
10929                    // we need to do is clear this user's data and save that
10930                    // it is uninstalled.
10931                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10932                    removeUser = user.getIdentifier();
10933                    appId = ps.appId;
10934                    mSettings.writePackageRestrictionsLPr(removeUser);
10935                }
10936            }
10937        }
10938
10939        if (removeUser >= 0) {
10940            // From above, we determined that we are deleting this only
10941            // for a single user.  Continue the work here.
10942            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10943            if (outInfo != null) {
10944                outInfo.removedPackage = packageName;
10945                outInfo.removedAppId = appId;
10946                outInfo.removedUsers = new int[] {removeUser};
10947            }
10948            mInstaller.clearUserData(packageName, removeUser);
10949            removeKeystoreDataIfNeeded(removeUser, appId);
10950            schedulePackageCleaning(packageName, removeUser, false);
10951            return true;
10952        }
10953
10954        if (dataOnly) {
10955            // Delete application data first
10956            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10957            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10958            return true;
10959        }
10960
10961        boolean ret = false;
10962        if (isSystemApp(ps)) {
10963            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10964            // When an updated system application is deleted we delete the existing resources as well and
10965            // fall back to existing code in system partition
10966            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10967                    flags, outInfo, writeSettings);
10968        } else {
10969            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10970            // Kill application pre-emptively especially for apps on sd.
10971            killApplication(packageName, ps.appId, "uninstall pkg");
10972            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10973                    allUserHandles, perUserInstalled,
10974                    outInfo, writeSettings);
10975        }
10976
10977        return ret;
10978    }
10979
10980    private final class ClearStorageConnection implements ServiceConnection {
10981        IMediaContainerService mContainerService;
10982
10983        @Override
10984        public void onServiceConnected(ComponentName name, IBinder service) {
10985            synchronized (this) {
10986                mContainerService = IMediaContainerService.Stub.asInterface(service);
10987                notifyAll();
10988            }
10989        }
10990
10991        @Override
10992        public void onServiceDisconnected(ComponentName name) {
10993        }
10994    }
10995
10996    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10997        final boolean mounted;
10998        if (Environment.isExternalStorageEmulated()) {
10999            mounted = true;
11000        } else {
11001            final String status = Environment.getExternalStorageState();
11002
11003            mounted = status.equals(Environment.MEDIA_MOUNTED)
11004                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11005        }
11006
11007        if (!mounted) {
11008            return;
11009        }
11010
11011        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11012        int[] users;
11013        if (userId == UserHandle.USER_ALL) {
11014            users = sUserManager.getUserIds();
11015        } else {
11016            users = new int[] { userId };
11017        }
11018        final ClearStorageConnection conn = new ClearStorageConnection();
11019        if (mContext.bindServiceAsUser(
11020                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11021            try {
11022                for (int curUser : users) {
11023                    long timeout = SystemClock.uptimeMillis() + 5000;
11024                    synchronized (conn) {
11025                        long now = SystemClock.uptimeMillis();
11026                        while (conn.mContainerService == null && now < timeout) {
11027                            try {
11028                                conn.wait(timeout - now);
11029                            } catch (InterruptedException e) {
11030                            }
11031                        }
11032                    }
11033                    if (conn.mContainerService == null) {
11034                        return;
11035                    }
11036
11037                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11038                    clearDirectory(conn.mContainerService,
11039                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11040                    if (allData) {
11041                        clearDirectory(conn.mContainerService,
11042                                userEnv.buildExternalStorageAppDataDirs(packageName));
11043                        clearDirectory(conn.mContainerService,
11044                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11045                    }
11046                }
11047            } finally {
11048                mContext.unbindService(conn);
11049            }
11050        }
11051    }
11052
11053    @Override
11054    public void clearApplicationUserData(final String packageName,
11055            final IPackageDataObserver observer, final int userId) {
11056        mContext.enforceCallingOrSelfPermission(
11057                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11058        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11059        // Queue up an async operation since the package deletion may take a little while.
11060        mHandler.post(new Runnable() {
11061            public void run() {
11062                mHandler.removeCallbacks(this);
11063                final boolean succeeded;
11064                synchronized (mInstallLock) {
11065                    succeeded = clearApplicationUserDataLI(packageName, userId);
11066                }
11067                clearExternalStorageDataSync(packageName, userId, true);
11068                if (succeeded) {
11069                    // invoke DeviceStorageMonitor's update method to clear any notifications
11070                    DeviceStorageMonitorInternal
11071                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11072                    if (dsm != null) {
11073                        dsm.checkMemory();
11074                    }
11075                }
11076                if(observer != null) {
11077                    try {
11078                        observer.onRemoveCompleted(packageName, succeeded);
11079                    } catch (RemoteException e) {
11080                        Log.i(TAG, "Observer no longer exists.");
11081                    }
11082                } //end if observer
11083            } //end run
11084        });
11085    }
11086
11087    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11088        if (packageName == null) {
11089            Slog.w(TAG, "Attempt to delete null packageName.");
11090            return false;
11091        }
11092
11093        // Try finding details about the requested package
11094        PackageParser.Package pkg;
11095        synchronized (mPackages) {
11096            pkg = mPackages.get(packageName);
11097            if (pkg == null) {
11098                final PackageSetting ps = mSettings.mPackages.get(packageName);
11099                if (ps != null) {
11100                    pkg = ps.pkg;
11101                }
11102            }
11103        }
11104
11105        if (pkg == null) {
11106            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11107        }
11108
11109        // Always delete data directories for package, even if we found no other
11110        // record of app. This helps users recover from UID mismatches without
11111        // resorting to a full data wipe.
11112        int retCode = mInstaller.clearUserData(packageName, userId);
11113        if (retCode < 0) {
11114            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11115            return false;
11116        }
11117
11118        if (pkg == null) {
11119            return false;
11120        }
11121
11122        if (pkg != null && pkg.applicationInfo != null) {
11123            final int appId = pkg.applicationInfo.uid;
11124            removeKeystoreDataIfNeeded(userId, appId);
11125        }
11126
11127        // Create a native library symlink only if we have native libraries
11128        // and if the native libraries are 32 bit libraries. We do not provide
11129        // this symlink for 64 bit libraries.
11130        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11131                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11132            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11133            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11134                Slog.w(TAG, "Failed linking native library dir");
11135                return false;
11136            }
11137        }
11138
11139        return true;
11140    }
11141
11142    /**
11143     * Remove entries from the keystore daemon. Will only remove it if the
11144     * {@code appId} is valid.
11145     */
11146    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11147        if (appId < 0) {
11148            return;
11149        }
11150
11151        final KeyStore keyStore = KeyStore.getInstance();
11152        if (keyStore != null) {
11153            if (userId == UserHandle.USER_ALL) {
11154                for (final int individual : sUserManager.getUserIds()) {
11155                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11156                }
11157            } else {
11158                keyStore.clearUid(UserHandle.getUid(userId, appId));
11159            }
11160        } else {
11161            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11162        }
11163    }
11164
11165    @Override
11166    public void deleteApplicationCacheFiles(final String packageName,
11167            final IPackageDataObserver observer) {
11168        mContext.enforceCallingOrSelfPermission(
11169                android.Manifest.permission.DELETE_CACHE_FILES, null);
11170        // Queue up an async operation since the package deletion may take a little while.
11171        final int userId = UserHandle.getCallingUserId();
11172        mHandler.post(new Runnable() {
11173            public void run() {
11174                mHandler.removeCallbacks(this);
11175                final boolean succeded;
11176                synchronized (mInstallLock) {
11177                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11178                }
11179                clearExternalStorageDataSync(packageName, userId, false);
11180                if(observer != null) {
11181                    try {
11182                        observer.onRemoveCompleted(packageName, succeded);
11183                    } catch (RemoteException e) {
11184                        Log.i(TAG, "Observer no longer exists.");
11185                    }
11186                } //end if observer
11187            } //end run
11188        });
11189    }
11190
11191    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11192        if (packageName == null) {
11193            Slog.w(TAG, "Attempt to delete null packageName.");
11194            return false;
11195        }
11196        PackageParser.Package p;
11197        synchronized (mPackages) {
11198            p = mPackages.get(packageName);
11199        }
11200        if (p == null) {
11201            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11202            return false;
11203        }
11204        final ApplicationInfo applicationInfo = p.applicationInfo;
11205        if (applicationInfo == null) {
11206            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11207            return false;
11208        }
11209        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11210        if (retCode < 0) {
11211            Slog.w(TAG, "Couldn't remove cache files for package: "
11212                       + packageName + " u" + userId);
11213            return false;
11214        }
11215        return true;
11216    }
11217
11218    @Override
11219    public void getPackageSizeInfo(final String packageName, int userHandle,
11220            final IPackageStatsObserver observer) {
11221        mContext.enforceCallingOrSelfPermission(
11222                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11223        if (packageName == null) {
11224            throw new IllegalArgumentException("Attempt to get size of null packageName");
11225        }
11226
11227        PackageStats stats = new PackageStats(packageName, userHandle);
11228
11229        /*
11230         * Queue up an async operation since the package measurement may take a
11231         * little while.
11232         */
11233        Message msg = mHandler.obtainMessage(INIT_COPY);
11234        msg.obj = new MeasureParams(stats, observer);
11235        mHandler.sendMessage(msg);
11236    }
11237
11238    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11239            PackageStats pStats) {
11240        if (packageName == null) {
11241            Slog.w(TAG, "Attempt to get size of null packageName.");
11242            return false;
11243        }
11244        PackageParser.Package p;
11245        boolean dataOnly = false;
11246        String libDirRoot = null;
11247        String asecPath = null;
11248        PackageSetting ps = null;
11249        synchronized (mPackages) {
11250            p = mPackages.get(packageName);
11251            ps = mSettings.mPackages.get(packageName);
11252            if(p == null) {
11253                dataOnly = true;
11254                if((ps == null) || (ps.pkg == null)) {
11255                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11256                    return false;
11257                }
11258                p = ps.pkg;
11259            }
11260            if (ps != null) {
11261                libDirRoot = ps.legacyNativeLibraryPathString;
11262            }
11263            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11264                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11265                if (secureContainerId != null) {
11266                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11267                }
11268            }
11269        }
11270        String publicSrcDir = null;
11271        if(!dataOnly) {
11272            final ApplicationInfo applicationInfo = p.applicationInfo;
11273            if (applicationInfo == null) {
11274                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11275                return false;
11276            }
11277            if (isForwardLocked(p)) {
11278                publicSrcDir = applicationInfo.getBaseResourcePath();
11279            }
11280        }
11281        // TODO: extend to measure size of split APKs
11282        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11283        // not just the first level.
11284        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11285        // just the primary.
11286        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11287        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11288                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11289        if (res < 0) {
11290            return false;
11291        }
11292
11293        // Fix-up for forward-locked applications in ASEC containers.
11294        if (!isExternal(p)) {
11295            pStats.codeSize += pStats.externalCodeSize;
11296            pStats.externalCodeSize = 0L;
11297        }
11298
11299        return true;
11300    }
11301
11302
11303    @Override
11304    public void addPackageToPreferred(String packageName) {
11305        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11306    }
11307
11308    @Override
11309    public void removePackageFromPreferred(String packageName) {
11310        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11311    }
11312
11313    @Override
11314    public List<PackageInfo> getPreferredPackages(int flags) {
11315        return new ArrayList<PackageInfo>();
11316    }
11317
11318    private int getUidTargetSdkVersionLockedLPr(int uid) {
11319        Object obj = mSettings.getUserIdLPr(uid);
11320        if (obj instanceof SharedUserSetting) {
11321            final SharedUserSetting sus = (SharedUserSetting) obj;
11322            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11323            final Iterator<PackageSetting> it = sus.packages.iterator();
11324            while (it.hasNext()) {
11325                final PackageSetting ps = it.next();
11326                if (ps.pkg != null) {
11327                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11328                    if (v < vers) vers = v;
11329                }
11330            }
11331            return vers;
11332        } else if (obj instanceof PackageSetting) {
11333            final PackageSetting ps = (PackageSetting) obj;
11334            if (ps.pkg != null) {
11335                return ps.pkg.applicationInfo.targetSdkVersion;
11336            }
11337        }
11338        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11339    }
11340
11341    @Override
11342    public void addPreferredActivity(IntentFilter filter, int match,
11343            ComponentName[] set, ComponentName activity, int userId) {
11344        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11345                "Adding preferred");
11346    }
11347
11348    private void addPreferredActivityInternal(IntentFilter filter, int match,
11349            ComponentName[] set, ComponentName activity, boolean always, int userId,
11350            String opname) {
11351        // writer
11352        int callingUid = Binder.getCallingUid();
11353        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11354        if (filter.countActions() == 0) {
11355            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11356            return;
11357        }
11358        synchronized (mPackages) {
11359            if (mContext.checkCallingOrSelfPermission(
11360                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11361                    != PackageManager.PERMISSION_GRANTED) {
11362                if (getUidTargetSdkVersionLockedLPr(callingUid)
11363                        < Build.VERSION_CODES.FROYO) {
11364                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11365                            + callingUid);
11366                    return;
11367                }
11368                mContext.enforceCallingOrSelfPermission(
11369                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11370            }
11371
11372            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11373            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11374                    + userId + ":");
11375            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11376            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11377            mSettings.writePackageRestrictionsLPr(userId);
11378        }
11379    }
11380
11381    @Override
11382    public void replacePreferredActivity(IntentFilter filter, int match,
11383            ComponentName[] set, ComponentName activity, int userId) {
11384        if (filter.countActions() != 1) {
11385            throw new IllegalArgumentException(
11386                    "replacePreferredActivity expects filter to have only 1 action.");
11387        }
11388        if (filter.countDataAuthorities() != 0
11389                || filter.countDataPaths() != 0
11390                || filter.countDataSchemes() > 1
11391                || filter.countDataTypes() != 0) {
11392            throw new IllegalArgumentException(
11393                    "replacePreferredActivity expects filter to have no data authorities, " +
11394                    "paths, or types; and at most one scheme.");
11395        }
11396
11397        final int callingUid = Binder.getCallingUid();
11398        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11399        synchronized (mPackages) {
11400            if (mContext.checkCallingOrSelfPermission(
11401                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11402                    != PackageManager.PERMISSION_GRANTED) {
11403                if (getUidTargetSdkVersionLockedLPr(callingUid)
11404                        < Build.VERSION_CODES.FROYO) {
11405                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11406                            + Binder.getCallingUid());
11407                    return;
11408                }
11409                mContext.enforceCallingOrSelfPermission(
11410                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11411            }
11412
11413            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11414            if (pir != null) {
11415                // Get all of the existing entries that exactly match this filter.
11416                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11417                if (existing != null && existing.size() == 1) {
11418                    PreferredActivity cur = existing.get(0);
11419                    if (DEBUG_PREFERRED) {
11420                        Slog.i(TAG, "Checking replace of preferred:");
11421                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11422                        if (!cur.mPref.mAlways) {
11423                            Slog.i(TAG, "  -- CUR; not mAlways!");
11424                        } else {
11425                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11426                            Slog.i(TAG, "  -- CUR: mSet="
11427                                    + Arrays.toString(cur.mPref.mSetComponents));
11428                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11429                            Slog.i(TAG, "  -- NEW: mMatch="
11430                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11431                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11432                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11433                        }
11434                    }
11435                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11436                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11437                            && cur.mPref.sameSet(set)) {
11438                        if (DEBUG_PREFERRED) {
11439                            Slog.i(TAG, "Replacing with same preferred activity "
11440                                    + cur.mPref.mShortComponent + " for user "
11441                                    + userId + ":");
11442                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11443                        } else {
11444                            Slog.i(TAG, "Replacing with same preferred activity "
11445                                    + cur.mPref.mShortComponent + " for user "
11446                                    + userId);
11447                        }
11448                        return;
11449                    }
11450                }
11451
11452                if (existing != null) {
11453                    if (DEBUG_PREFERRED) {
11454                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11455                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11456                    }
11457                    for (int i = 0; i < existing.size(); i++) {
11458                        PreferredActivity pa = existing.get(i);
11459                        if (DEBUG_PREFERRED) {
11460                            Slog.i(TAG, "Removing existing preferred activity "
11461                                    + pa.mPref.mComponent + ":");
11462                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11463                        }
11464                        pir.removeFilter(pa);
11465                    }
11466                }
11467            }
11468            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11469                    "Replacing preferred");
11470        }
11471    }
11472
11473    @Override
11474    public void clearPackagePreferredActivities(String packageName) {
11475        final int uid = Binder.getCallingUid();
11476        // writer
11477        synchronized (mPackages) {
11478            PackageParser.Package pkg = mPackages.get(packageName);
11479            if (pkg == null || pkg.applicationInfo.uid != uid) {
11480                if (mContext.checkCallingOrSelfPermission(
11481                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11482                        != PackageManager.PERMISSION_GRANTED) {
11483                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11484                            < Build.VERSION_CODES.FROYO) {
11485                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11486                                + Binder.getCallingUid());
11487                        return;
11488                    }
11489                    mContext.enforceCallingOrSelfPermission(
11490                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11491                }
11492            }
11493
11494            int user = UserHandle.getCallingUserId();
11495            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11496                mSettings.writePackageRestrictionsLPr(user);
11497                scheduleWriteSettingsLocked();
11498            }
11499        }
11500    }
11501
11502    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11503    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11504        ArrayList<PreferredActivity> removed = null;
11505        boolean changed = false;
11506        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11507            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11508            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11509            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11510                continue;
11511            }
11512            Iterator<PreferredActivity> it = pir.filterIterator();
11513            while (it.hasNext()) {
11514                PreferredActivity pa = it.next();
11515                // Mark entry for removal only if it matches the package name
11516                // and the entry is of type "always".
11517                if (packageName == null ||
11518                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11519                                && pa.mPref.mAlways)) {
11520                    if (removed == null) {
11521                        removed = new ArrayList<PreferredActivity>();
11522                    }
11523                    removed.add(pa);
11524                }
11525            }
11526            if (removed != null) {
11527                for (int j=0; j<removed.size(); j++) {
11528                    PreferredActivity pa = removed.get(j);
11529                    pir.removeFilter(pa);
11530                }
11531                changed = true;
11532            }
11533        }
11534        return changed;
11535    }
11536
11537    @Override
11538    public void resetPreferredActivities(int userId) {
11539        mContext.enforceCallingOrSelfPermission(
11540                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11541        // writer
11542        synchronized (mPackages) {
11543            int user = UserHandle.getCallingUserId();
11544            clearPackagePreferredActivitiesLPw(null, user);
11545            mSettings.readDefaultPreferredAppsLPw(this, user);
11546            mSettings.writePackageRestrictionsLPr(user);
11547            scheduleWriteSettingsLocked();
11548        }
11549    }
11550
11551    @Override
11552    public int getPreferredActivities(List<IntentFilter> outFilters,
11553            List<ComponentName> outActivities, String packageName) {
11554
11555        int num = 0;
11556        final int userId = UserHandle.getCallingUserId();
11557        // reader
11558        synchronized (mPackages) {
11559            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11560            if (pir != null) {
11561                final Iterator<PreferredActivity> it = pir.filterIterator();
11562                while (it.hasNext()) {
11563                    final PreferredActivity pa = it.next();
11564                    if (packageName == null
11565                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11566                                    && pa.mPref.mAlways)) {
11567                        if (outFilters != null) {
11568                            outFilters.add(new IntentFilter(pa));
11569                        }
11570                        if (outActivities != null) {
11571                            outActivities.add(pa.mPref.mComponent);
11572                        }
11573                    }
11574                }
11575            }
11576        }
11577
11578        return num;
11579    }
11580
11581    @Override
11582    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11583            int userId) {
11584        int callingUid = Binder.getCallingUid();
11585        if (callingUid != Process.SYSTEM_UID) {
11586            throw new SecurityException(
11587                    "addPersistentPreferredActivity can only be run by the system");
11588        }
11589        if (filter.countActions() == 0) {
11590            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11591            return;
11592        }
11593        synchronized (mPackages) {
11594            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11595                    " :");
11596            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11597            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11598                    new PersistentPreferredActivity(filter, activity));
11599            mSettings.writePackageRestrictionsLPr(userId);
11600        }
11601    }
11602
11603    @Override
11604    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11605        int callingUid = Binder.getCallingUid();
11606        if (callingUid != Process.SYSTEM_UID) {
11607            throw new SecurityException(
11608                    "clearPackagePersistentPreferredActivities can only be run by the system");
11609        }
11610        ArrayList<PersistentPreferredActivity> removed = null;
11611        boolean changed = false;
11612        synchronized (mPackages) {
11613            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11614                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11615                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11616                        .valueAt(i);
11617                if (userId != thisUserId) {
11618                    continue;
11619                }
11620                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11621                while (it.hasNext()) {
11622                    PersistentPreferredActivity ppa = it.next();
11623                    // Mark entry for removal only if it matches the package name.
11624                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11625                        if (removed == null) {
11626                            removed = new ArrayList<PersistentPreferredActivity>();
11627                        }
11628                        removed.add(ppa);
11629                    }
11630                }
11631                if (removed != null) {
11632                    for (int j=0; j<removed.size(); j++) {
11633                        PersistentPreferredActivity ppa = removed.get(j);
11634                        ppir.removeFilter(ppa);
11635                    }
11636                    changed = true;
11637                }
11638            }
11639
11640            if (changed) {
11641                mSettings.writePackageRestrictionsLPr(userId);
11642            }
11643        }
11644    }
11645
11646    @Override
11647    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11648            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11649        mContext.enforceCallingOrSelfPermission(
11650                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11651        int callingUid = Binder.getCallingUid();
11652        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11653        if (intentFilter.countActions() == 0) {
11654            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11655            return;
11656        }
11657        synchronized (mPackages) {
11658            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11659                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11660            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11661            mSettings.writePackageRestrictionsLPr(sourceUserId);
11662        }
11663    }
11664
11665    @Override
11666    public void addCrossProfileIntentsForPackage(String packageName,
11667            int sourceUserId, int targetUserId) {
11668        mContext.enforceCallingOrSelfPermission(
11669                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11670        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11671        mSettings.writePackageRestrictionsLPr(sourceUserId);
11672    }
11673
11674    @Override
11675    public void removeCrossProfileIntentsForPackage(String packageName,
11676            int sourceUserId, int targetUserId) {
11677        mContext.enforceCallingOrSelfPermission(
11678                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11679        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11680        mSettings.writePackageRestrictionsLPr(sourceUserId);
11681    }
11682
11683    @Override
11684    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11685            int ownerUserId) {
11686        mContext.enforceCallingOrSelfPermission(
11687                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11688        int callingUid = Binder.getCallingUid();
11689        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11690        int callingUserId = UserHandle.getUserId(callingUid);
11691        synchronized (mPackages) {
11692            CrossProfileIntentResolver resolver =
11693                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11694            HashSet<CrossProfileIntentFilter> set =
11695                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11696            for (CrossProfileIntentFilter filter : set) {
11697                if (filter.getOwnerPackage().equals(ownerPackage)
11698                        && filter.getOwnerUserId() == callingUserId) {
11699                    resolver.removeFilter(filter);
11700                }
11701            }
11702            mSettings.writePackageRestrictionsLPr(sourceUserId);
11703        }
11704    }
11705
11706    // Enforcing that callingUid is owning pkg on userId
11707    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11708        // The system owns everything.
11709        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11710            return;
11711        }
11712        int callingUserId = UserHandle.getUserId(callingUid);
11713        if (callingUserId != userId) {
11714            throw new SecurityException("calling uid " + callingUid
11715                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11716                    + callingUserId);
11717        }
11718        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11719        if (pi == null) {
11720            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11721                    + callingUserId);
11722        }
11723        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11724            throw new SecurityException("Calling uid " + callingUid
11725                    + " does not own package " + pkg);
11726        }
11727    }
11728
11729    @Override
11730    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11731        Intent intent = new Intent(Intent.ACTION_MAIN);
11732        intent.addCategory(Intent.CATEGORY_HOME);
11733
11734        final int callingUserId = UserHandle.getCallingUserId();
11735        List<ResolveInfo> list = queryIntentActivities(intent, null,
11736                PackageManager.GET_META_DATA, callingUserId);
11737        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11738                true, false, false, callingUserId);
11739
11740        allHomeCandidates.clear();
11741        if (list != null) {
11742            for (ResolveInfo ri : list) {
11743                allHomeCandidates.add(ri);
11744            }
11745        }
11746        return (preferred == null || preferred.activityInfo == null)
11747                ? null
11748                : new ComponentName(preferred.activityInfo.packageName,
11749                        preferred.activityInfo.name);
11750    }
11751
11752    @Override
11753    public void setApplicationEnabledSetting(String appPackageName,
11754            int newState, int flags, int userId, String callingPackage) {
11755        if (!sUserManager.exists(userId)) return;
11756        if (callingPackage == null) {
11757            callingPackage = Integer.toString(Binder.getCallingUid());
11758        }
11759        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11760    }
11761
11762    @Override
11763    public void setComponentEnabledSetting(ComponentName componentName,
11764            int newState, int flags, int userId) {
11765        if (!sUserManager.exists(userId)) return;
11766        setEnabledSetting(componentName.getPackageName(),
11767                componentName.getClassName(), newState, flags, userId, null);
11768    }
11769
11770    private void setEnabledSetting(final String packageName, String className, int newState,
11771            final int flags, int userId, String callingPackage) {
11772        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11773              || newState == COMPONENT_ENABLED_STATE_ENABLED
11774              || newState == COMPONENT_ENABLED_STATE_DISABLED
11775              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11776              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11777            throw new IllegalArgumentException("Invalid new component state: "
11778                    + newState);
11779        }
11780        PackageSetting pkgSetting;
11781        final int uid = Binder.getCallingUid();
11782        final int permission = mContext.checkCallingOrSelfPermission(
11783                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11784        enforceCrossUserPermission(uid, userId, false, "set enabled");
11785        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11786        boolean sendNow = false;
11787        boolean isApp = (className == null);
11788        String componentName = isApp ? packageName : className;
11789        int packageUid = -1;
11790        ArrayList<String> components;
11791
11792        // writer
11793        synchronized (mPackages) {
11794            pkgSetting = mSettings.mPackages.get(packageName);
11795            if (pkgSetting == null) {
11796                if (className == null) {
11797                    throw new IllegalArgumentException(
11798                            "Unknown package: " + packageName);
11799                }
11800                throw new IllegalArgumentException(
11801                        "Unknown component: " + packageName
11802                        + "/" + className);
11803            }
11804            // Allow root and verify that userId is not being specified by a different user
11805            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11806                throw new SecurityException(
11807                        "Permission Denial: attempt to change component state from pid="
11808                        + Binder.getCallingPid()
11809                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11810            }
11811            if (className == null) {
11812                // We're dealing with an application/package level state change
11813                if (pkgSetting.getEnabled(userId) == newState) {
11814                    // Nothing to do
11815                    return;
11816                }
11817                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11818                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11819                    // Don't care about who enables an app.
11820                    callingPackage = null;
11821                }
11822                pkgSetting.setEnabled(newState, userId, callingPackage);
11823                // pkgSetting.pkg.mSetEnabled = newState;
11824            } else {
11825                // We're dealing with a component level state change
11826                // First, verify that this is a valid class name.
11827                PackageParser.Package pkg = pkgSetting.pkg;
11828                if (pkg == null || !pkg.hasComponentClassName(className)) {
11829                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11830                        throw new IllegalArgumentException("Component class " + className
11831                                + " does not exist in " + packageName);
11832                    } else {
11833                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11834                                + className + " does not exist in " + packageName);
11835                    }
11836                }
11837                switch (newState) {
11838                case COMPONENT_ENABLED_STATE_ENABLED:
11839                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11840                        return;
11841                    }
11842                    break;
11843                case COMPONENT_ENABLED_STATE_DISABLED:
11844                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11845                        return;
11846                    }
11847                    break;
11848                case COMPONENT_ENABLED_STATE_DEFAULT:
11849                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11850                        return;
11851                    }
11852                    break;
11853                default:
11854                    Slog.e(TAG, "Invalid new component state: " + newState);
11855                    return;
11856                }
11857            }
11858            mSettings.writePackageRestrictionsLPr(userId);
11859            components = mPendingBroadcasts.get(userId, packageName);
11860            final boolean newPackage = components == null;
11861            if (newPackage) {
11862                components = new ArrayList<String>();
11863            }
11864            if (!components.contains(componentName)) {
11865                components.add(componentName);
11866            }
11867            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11868                sendNow = true;
11869                // Purge entry from pending broadcast list if another one exists already
11870                // since we are sending one right away.
11871                mPendingBroadcasts.remove(userId, packageName);
11872            } else {
11873                if (newPackage) {
11874                    mPendingBroadcasts.put(userId, packageName, components);
11875                }
11876                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11877                    // Schedule a message
11878                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11879                }
11880            }
11881        }
11882
11883        long callingId = Binder.clearCallingIdentity();
11884        try {
11885            if (sendNow) {
11886                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11887                sendPackageChangedBroadcast(packageName,
11888                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11889            }
11890        } finally {
11891            Binder.restoreCallingIdentity(callingId);
11892        }
11893    }
11894
11895    private void sendPackageChangedBroadcast(String packageName,
11896            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11897        if (DEBUG_INSTALL)
11898            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11899                    + componentNames);
11900        Bundle extras = new Bundle(4);
11901        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11902        String nameList[] = new String[componentNames.size()];
11903        componentNames.toArray(nameList);
11904        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11905        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11906        extras.putInt(Intent.EXTRA_UID, packageUid);
11907        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11908                new int[] {UserHandle.getUserId(packageUid)});
11909    }
11910
11911    @Override
11912    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11913        if (!sUserManager.exists(userId)) return;
11914        final int uid = Binder.getCallingUid();
11915        final int permission = mContext.checkCallingOrSelfPermission(
11916                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11917        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11918        enforceCrossUserPermission(uid, userId, true, "stop package");
11919        // writer
11920        synchronized (mPackages) {
11921            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11922                    uid, userId)) {
11923                scheduleWritePackageRestrictionsLocked(userId);
11924            }
11925        }
11926    }
11927
11928    @Override
11929    public String getInstallerPackageName(String packageName) {
11930        // reader
11931        synchronized (mPackages) {
11932            return mSettings.getInstallerPackageNameLPr(packageName);
11933        }
11934    }
11935
11936    @Override
11937    public int getApplicationEnabledSetting(String packageName, int userId) {
11938        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11939        int uid = Binder.getCallingUid();
11940        enforceCrossUserPermission(uid, userId, false, "get enabled");
11941        // reader
11942        synchronized (mPackages) {
11943            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11944        }
11945    }
11946
11947    @Override
11948    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11949        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11950        int uid = Binder.getCallingUid();
11951        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11952        // reader
11953        synchronized (mPackages) {
11954            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11955        }
11956    }
11957
11958    @Override
11959    public void enterSafeMode() {
11960        enforceSystemOrRoot("Only the system can request entering safe mode");
11961
11962        if (!mSystemReady) {
11963            mSafeMode = true;
11964        }
11965    }
11966
11967    @Override
11968    public void systemReady() {
11969        mSystemReady = true;
11970
11971        // Read the compatibilty setting when the system is ready.
11972        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11973                mContext.getContentResolver(),
11974                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11975        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11976        if (DEBUG_SETTINGS) {
11977            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11978        }
11979
11980        synchronized (mPackages) {
11981            // Verify that all of the preferred activity components actually
11982            // exist.  It is possible for applications to be updated and at
11983            // that point remove a previously declared activity component that
11984            // had been set as a preferred activity.  We try to clean this up
11985            // the next time we encounter that preferred activity, but it is
11986            // possible for the user flow to never be able to return to that
11987            // situation so here we do a sanity check to make sure we haven't
11988            // left any junk around.
11989            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11990            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11991                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11992                removed.clear();
11993                for (PreferredActivity pa : pir.filterSet()) {
11994                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11995                        removed.add(pa);
11996                    }
11997                }
11998                if (removed.size() > 0) {
11999                    for (int r=0; r<removed.size(); r++) {
12000                        PreferredActivity pa = removed.get(r);
12001                        Slog.w(TAG, "Removing dangling preferred activity: "
12002                                + pa.mPref.mComponent);
12003                        pir.removeFilter(pa);
12004                    }
12005                    mSettings.writePackageRestrictionsLPr(
12006                            mSettings.mPreferredActivities.keyAt(i));
12007                }
12008            }
12009        }
12010        sUserManager.systemReady();
12011
12012        // Kick off any messages waiting for system ready
12013        if (mPostSystemReadyMessages != null) {
12014            for (Message msg : mPostSystemReadyMessages) {
12015                msg.sendToTarget();
12016            }
12017            mPostSystemReadyMessages = null;
12018        }
12019    }
12020
12021    @Override
12022    public boolean isSafeMode() {
12023        return mSafeMode;
12024    }
12025
12026    @Override
12027    public boolean hasSystemUidErrors() {
12028        return mHasSystemUidErrors;
12029    }
12030
12031    static String arrayToString(int[] array) {
12032        StringBuffer buf = new StringBuffer(128);
12033        buf.append('[');
12034        if (array != null) {
12035            for (int i=0; i<array.length; i++) {
12036                if (i > 0) buf.append(", ");
12037                buf.append(array[i]);
12038            }
12039        }
12040        buf.append(']');
12041        return buf.toString();
12042    }
12043
12044    static class DumpState {
12045        public static final int DUMP_LIBS = 1 << 0;
12046        public static final int DUMP_FEATURES = 1 << 1;
12047        public static final int DUMP_RESOLVERS = 1 << 2;
12048        public static final int DUMP_PERMISSIONS = 1 << 3;
12049        public static final int DUMP_PACKAGES = 1 << 4;
12050        public static final int DUMP_SHARED_USERS = 1 << 5;
12051        public static final int DUMP_MESSAGES = 1 << 6;
12052        public static final int DUMP_PROVIDERS = 1 << 7;
12053        public static final int DUMP_VERIFIERS = 1 << 8;
12054        public static final int DUMP_PREFERRED = 1 << 9;
12055        public static final int DUMP_PREFERRED_XML = 1 << 10;
12056        public static final int DUMP_KEYSETS = 1 << 11;
12057        public static final int DUMP_VERSION = 1 << 12;
12058        public static final int DUMP_INSTALLS = 1 << 13;
12059
12060        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12061
12062        private int mTypes;
12063
12064        private int mOptions;
12065
12066        private boolean mTitlePrinted;
12067
12068        private SharedUserSetting mSharedUser;
12069
12070        public boolean isDumping(int type) {
12071            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12072                return true;
12073            }
12074
12075            return (mTypes & type) != 0;
12076        }
12077
12078        public void setDump(int type) {
12079            mTypes |= type;
12080        }
12081
12082        public boolean isOptionEnabled(int option) {
12083            return (mOptions & option) != 0;
12084        }
12085
12086        public void setOptionEnabled(int option) {
12087            mOptions |= option;
12088        }
12089
12090        public boolean onTitlePrinted() {
12091            final boolean printed = mTitlePrinted;
12092            mTitlePrinted = true;
12093            return printed;
12094        }
12095
12096        public boolean getTitlePrinted() {
12097            return mTitlePrinted;
12098        }
12099
12100        public void setTitlePrinted(boolean enabled) {
12101            mTitlePrinted = enabled;
12102        }
12103
12104        public SharedUserSetting getSharedUser() {
12105            return mSharedUser;
12106        }
12107
12108        public void setSharedUser(SharedUserSetting user) {
12109            mSharedUser = user;
12110        }
12111    }
12112
12113    @Override
12114    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12115        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12116                != PackageManager.PERMISSION_GRANTED) {
12117            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12118                    + Binder.getCallingPid()
12119                    + ", uid=" + Binder.getCallingUid()
12120                    + " without permission "
12121                    + android.Manifest.permission.DUMP);
12122            return;
12123        }
12124
12125        DumpState dumpState = new DumpState();
12126        boolean fullPreferred = false;
12127        boolean checkin = false;
12128
12129        String packageName = null;
12130
12131        int opti = 0;
12132        while (opti < args.length) {
12133            String opt = args[opti];
12134            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12135                break;
12136            }
12137            opti++;
12138            if ("-a".equals(opt)) {
12139                // Right now we only know how to print all.
12140            } else if ("-h".equals(opt)) {
12141                pw.println("Package manager dump options:");
12142                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12143                pw.println("    --checkin: dump for a checkin");
12144                pw.println("    -f: print details of intent filters");
12145                pw.println("    -h: print this help");
12146                pw.println("  cmd may be one of:");
12147                pw.println("    l[ibraries]: list known shared libraries");
12148                pw.println("    f[ibraries]: list device features");
12149                pw.println("    k[eysets]: print known keysets");
12150                pw.println("    r[esolvers]: dump intent resolvers");
12151                pw.println("    perm[issions]: dump permissions");
12152                pw.println("    pref[erred]: print preferred package settings");
12153                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12154                pw.println("    prov[iders]: dump content providers");
12155                pw.println("    p[ackages]: dump installed packages");
12156                pw.println("    s[hared-users]: dump shared user IDs");
12157                pw.println("    m[essages]: print collected runtime messages");
12158                pw.println("    v[erifiers]: print package verifier info");
12159                pw.println("    version: print database version info");
12160                pw.println("    write: write current settings now");
12161                pw.println("    <package.name>: info about given package");
12162                pw.println("    installs: details about install sessions");
12163                return;
12164            } else if ("--checkin".equals(opt)) {
12165                checkin = true;
12166            } else if ("-f".equals(opt)) {
12167                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12168            } else {
12169                pw.println("Unknown argument: " + opt + "; use -h for help");
12170            }
12171        }
12172
12173        // Is the caller requesting to dump a particular piece of data?
12174        if (opti < args.length) {
12175            String cmd = args[opti];
12176            opti++;
12177            // Is this a package name?
12178            if ("android".equals(cmd) || cmd.contains(".")) {
12179                packageName = cmd;
12180                // When dumping a single package, we always dump all of its
12181                // filter information since the amount of data will be reasonable.
12182                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12183            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_LIBS);
12185            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12186                dumpState.setDump(DumpState.DUMP_FEATURES);
12187            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12188                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12189            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12190                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12191            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12192                dumpState.setDump(DumpState.DUMP_PREFERRED);
12193            } else if ("preferred-xml".equals(cmd)) {
12194                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12195                if (opti < args.length && "--full".equals(args[opti])) {
12196                    fullPreferred = true;
12197                    opti++;
12198                }
12199            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12200                dumpState.setDump(DumpState.DUMP_PACKAGES);
12201            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12202                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12203            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12204                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12205            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12206                dumpState.setDump(DumpState.DUMP_MESSAGES);
12207            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12208                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12209            } else if ("version".equals(cmd)) {
12210                dumpState.setDump(DumpState.DUMP_VERSION);
12211            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12212                dumpState.setDump(DumpState.DUMP_KEYSETS);
12213            } else if ("write".equals(cmd)) {
12214                synchronized (mPackages) {
12215                    mSettings.writeLPr();
12216                    pw.println("Settings written.");
12217                    return;
12218                }
12219            } else if ("installs".equals(cmd)) {
12220                dumpState.setDump(DumpState.DUMP_INSTALLS);
12221            }
12222        }
12223
12224        if (checkin) {
12225            pw.println("vers,1");
12226        }
12227
12228        // reader
12229        synchronized (mPackages) {
12230            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12231                if (!checkin) {
12232                    if (dumpState.onTitlePrinted())
12233                        pw.println();
12234                    pw.println("Database versions:");
12235                    pw.print("  SDK Version:");
12236                    pw.print(" internal=");
12237                    pw.print(mSettings.mInternalSdkPlatform);
12238                    pw.print(" external=");
12239                    pw.println(mSettings.mExternalSdkPlatform);
12240                    pw.print("  DB Version:");
12241                    pw.print(" internal=");
12242                    pw.print(mSettings.mInternalDatabaseVersion);
12243                    pw.print(" external=");
12244                    pw.println(mSettings.mExternalDatabaseVersion);
12245                }
12246            }
12247
12248            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12249                if (!checkin) {
12250                    if (dumpState.onTitlePrinted())
12251                        pw.println();
12252                    pw.println("Verifiers:");
12253                    pw.print("  Required: ");
12254                    pw.print(mRequiredVerifierPackage);
12255                    pw.print(" (uid=");
12256                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12257                    pw.println(")");
12258                } else if (mRequiredVerifierPackage != null) {
12259                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12260                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12261                }
12262            }
12263
12264            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12265                boolean printedHeader = false;
12266                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12267                while (it.hasNext()) {
12268                    String name = it.next();
12269                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12270                    if (!checkin) {
12271                        if (!printedHeader) {
12272                            if (dumpState.onTitlePrinted())
12273                                pw.println();
12274                            pw.println("Libraries:");
12275                            printedHeader = true;
12276                        }
12277                        pw.print("  ");
12278                    } else {
12279                        pw.print("lib,");
12280                    }
12281                    pw.print(name);
12282                    if (!checkin) {
12283                        pw.print(" -> ");
12284                    }
12285                    if (ent.path != null) {
12286                        if (!checkin) {
12287                            pw.print("(jar) ");
12288                            pw.print(ent.path);
12289                        } else {
12290                            pw.print(",jar,");
12291                            pw.print(ent.path);
12292                        }
12293                    } else {
12294                        if (!checkin) {
12295                            pw.print("(apk) ");
12296                            pw.print(ent.apk);
12297                        } else {
12298                            pw.print(",apk,");
12299                            pw.print(ent.apk);
12300                        }
12301                    }
12302                    pw.println();
12303                }
12304            }
12305
12306            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12307                if (dumpState.onTitlePrinted())
12308                    pw.println();
12309                if (!checkin) {
12310                    pw.println("Features:");
12311                }
12312                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12313                while (it.hasNext()) {
12314                    String name = it.next();
12315                    if (!checkin) {
12316                        pw.print("  ");
12317                    } else {
12318                        pw.print("feat,");
12319                    }
12320                    pw.println(name);
12321                }
12322            }
12323
12324            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12325                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12326                        : "Activity Resolver Table:", "  ", packageName,
12327                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12328                    dumpState.setTitlePrinted(true);
12329                }
12330                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12331                        : "Receiver Resolver Table:", "  ", packageName,
12332                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12333                    dumpState.setTitlePrinted(true);
12334                }
12335                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12336                        : "Service Resolver Table:", "  ", packageName,
12337                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12338                    dumpState.setTitlePrinted(true);
12339                }
12340                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12341                        : "Provider Resolver Table:", "  ", packageName,
12342                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12343                    dumpState.setTitlePrinted(true);
12344                }
12345            }
12346
12347            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12348                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12349                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12350                    int user = mSettings.mPreferredActivities.keyAt(i);
12351                    if (pir.dump(pw,
12352                            dumpState.getTitlePrinted()
12353                                ? "\nPreferred Activities User " + user + ":"
12354                                : "Preferred Activities User " + user + ":", "  ",
12355                            packageName, true)) {
12356                        dumpState.setTitlePrinted(true);
12357                    }
12358                }
12359            }
12360
12361            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12362                pw.flush();
12363                FileOutputStream fout = new FileOutputStream(fd);
12364                BufferedOutputStream str = new BufferedOutputStream(fout);
12365                XmlSerializer serializer = new FastXmlSerializer();
12366                try {
12367                    serializer.setOutput(str, "utf-8");
12368                    serializer.startDocument(null, true);
12369                    serializer.setFeature(
12370                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12371                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12372                    serializer.endDocument();
12373                    serializer.flush();
12374                } catch (IllegalArgumentException e) {
12375                    pw.println("Failed writing: " + e);
12376                } catch (IllegalStateException e) {
12377                    pw.println("Failed writing: " + e);
12378                } catch (IOException e) {
12379                    pw.println("Failed writing: " + e);
12380                }
12381            }
12382
12383            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12384                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12385                if (packageName == null) {
12386                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12387                        if (iperm == 0) {
12388                            if (dumpState.onTitlePrinted())
12389                                pw.println();
12390                            pw.println("AppOp Permissions:");
12391                        }
12392                        pw.print("  AppOp Permission ");
12393                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12394                        pw.println(":");
12395                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12396                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12397                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12398                        }
12399                    }
12400                }
12401            }
12402
12403            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12404                boolean printedSomething = false;
12405                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12406                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12407                        continue;
12408                    }
12409                    if (!printedSomething) {
12410                        if (dumpState.onTitlePrinted())
12411                            pw.println();
12412                        pw.println("Registered ContentProviders:");
12413                        printedSomething = true;
12414                    }
12415                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12416                    pw.print("    "); pw.println(p.toString());
12417                }
12418                printedSomething = false;
12419                for (Map.Entry<String, PackageParser.Provider> entry :
12420                        mProvidersByAuthority.entrySet()) {
12421                    PackageParser.Provider p = entry.getValue();
12422                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12423                        continue;
12424                    }
12425                    if (!printedSomething) {
12426                        if (dumpState.onTitlePrinted())
12427                            pw.println();
12428                        pw.println("ContentProvider Authorities:");
12429                        printedSomething = true;
12430                    }
12431                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12432                    pw.print("    "); pw.println(p.toString());
12433                    if (p.info != null && p.info.applicationInfo != null) {
12434                        final String appInfo = p.info.applicationInfo.toString();
12435                        pw.print("      applicationInfo="); pw.println(appInfo);
12436                    }
12437                }
12438            }
12439
12440            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12441                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12442            }
12443
12444            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12445                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12446            }
12447
12448            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12449                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12450            }
12451
12452            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12453                if (dumpState.onTitlePrinted()) pw.println();
12454                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12455            }
12456
12457            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12458                if (dumpState.onTitlePrinted()) pw.println();
12459                mSettings.dumpReadMessagesLPr(pw, dumpState);
12460
12461                pw.println();
12462                pw.println("Package warning messages:");
12463                final File fname = getSettingsProblemFile();
12464                FileInputStream in = null;
12465                try {
12466                    in = new FileInputStream(fname);
12467                    final int avail = in.available();
12468                    final byte[] data = new byte[avail];
12469                    in.read(data);
12470                    pw.print(new String(data));
12471                } catch (FileNotFoundException e) {
12472                } catch (IOException e) {
12473                } finally {
12474                    if (in != null) {
12475                        try {
12476                            in.close();
12477                        } catch (IOException e) {
12478                        }
12479                    }
12480                }
12481            }
12482        }
12483    }
12484
12485    // ------- apps on sdcard specific code -------
12486    static final boolean DEBUG_SD_INSTALL = false;
12487
12488    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12489
12490    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12491
12492    private boolean mMediaMounted = false;
12493
12494    static String getEncryptKey() {
12495        try {
12496            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12497                    SD_ENCRYPTION_KEYSTORE_NAME);
12498            if (sdEncKey == null) {
12499                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12500                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12501                if (sdEncKey == null) {
12502                    Slog.e(TAG, "Failed to create encryption keys");
12503                    return null;
12504                }
12505            }
12506            return sdEncKey;
12507        } catch (NoSuchAlgorithmException nsae) {
12508            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12509            return null;
12510        } catch (IOException ioe) {
12511            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12512            return null;
12513        }
12514    }
12515
12516    /*
12517     * Update media status on PackageManager.
12518     */
12519    @Override
12520    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12521        int callingUid = Binder.getCallingUid();
12522        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12523            throw new SecurityException("Media status can only be updated by the system");
12524        }
12525        // reader; this apparently protects mMediaMounted, but should probably
12526        // be a different lock in that case.
12527        synchronized (mPackages) {
12528            Log.i(TAG, "Updating external media status from "
12529                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12530                    + (mediaStatus ? "mounted" : "unmounted"));
12531            if (DEBUG_SD_INSTALL)
12532                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12533                        + ", mMediaMounted=" + mMediaMounted);
12534            if (mediaStatus == mMediaMounted) {
12535                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12536                        : 0, -1);
12537                mHandler.sendMessage(msg);
12538                return;
12539            }
12540            mMediaMounted = mediaStatus;
12541        }
12542        // Queue up an async operation since the package installation may take a
12543        // little while.
12544        mHandler.post(new Runnable() {
12545            public void run() {
12546                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12547            }
12548        });
12549    }
12550
12551    /**
12552     * Called by MountService when the initial ASECs to scan are available.
12553     * Should block until all the ASEC containers are finished being scanned.
12554     */
12555    public void scanAvailableAsecs() {
12556        updateExternalMediaStatusInner(true, false, false);
12557        if (mShouldRestoreconData) {
12558            SELinuxMMAC.setRestoreconDone();
12559            mShouldRestoreconData = false;
12560        }
12561    }
12562
12563    /*
12564     * Collect information of applications on external media, map them against
12565     * existing containers and update information based on current mount status.
12566     * Please note that we always have to report status if reportStatus has been
12567     * set to true especially when unloading packages.
12568     */
12569    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12570            boolean externalStorage) {
12571        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12572        int[] uidArr = EmptyArray.INT;
12573
12574        final String[] list = PackageHelper.getSecureContainerList();
12575        if (ArrayUtils.isEmpty(list)) {
12576            Log.i(TAG, "No secure containers found");
12577        } else {
12578            // Process list of secure containers and categorize them
12579            // as active or stale based on their package internal state.
12580
12581            // reader
12582            synchronized (mPackages) {
12583                for (String cid : list) {
12584                    // Leave stages untouched for now; installer service owns them
12585                    if (PackageInstallerService.isStageName(cid)) continue;
12586
12587                    if (DEBUG_SD_INSTALL)
12588                        Log.i(TAG, "Processing container " + cid);
12589                    String pkgName = getAsecPackageName(cid);
12590                    if (pkgName == null) {
12591                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12592                        continue;
12593                    }
12594                    if (DEBUG_SD_INSTALL)
12595                        Log.i(TAG, "Looking for pkg : " + pkgName);
12596
12597                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12598                    if (ps == null) {
12599                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12600                        continue;
12601                    }
12602
12603                    /*
12604                     * Skip packages that are not external if we're unmounting
12605                     * external storage.
12606                     */
12607                    if (externalStorage && !isMounted && !isExternal(ps)) {
12608                        continue;
12609                    }
12610
12611                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12612                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12613                    // The package status is changed only if the code path
12614                    // matches between settings and the container id.
12615                    if (ps.codePathString != null
12616                            && ps.codePathString.startsWith(args.getCodePath())) {
12617                        if (DEBUG_SD_INSTALL) {
12618                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12619                                    + " at code path: " + ps.codePathString);
12620                        }
12621
12622                        // We do have a valid package installed on sdcard
12623                        processCids.put(args, ps.codePathString);
12624                        final int uid = ps.appId;
12625                        if (uid != -1) {
12626                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12627                        }
12628                    } else {
12629                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12630                                + ps.codePathString);
12631                    }
12632                }
12633            }
12634
12635            Arrays.sort(uidArr);
12636        }
12637
12638        // Process packages with valid entries.
12639        if (isMounted) {
12640            if (DEBUG_SD_INSTALL)
12641                Log.i(TAG, "Loading packages");
12642            loadMediaPackages(processCids, uidArr);
12643            startCleaningPackages();
12644            mInstallerService.onSecureContainersAvailable();
12645        } else {
12646            if (DEBUG_SD_INSTALL)
12647                Log.i(TAG, "Unloading packages");
12648            unloadMediaPackages(processCids, uidArr, reportStatus);
12649        }
12650    }
12651
12652    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12653            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12654        int size = pkgList.size();
12655        if (size > 0) {
12656            // Send broadcasts here
12657            Bundle extras = new Bundle();
12658            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12659                    .toArray(new String[size]));
12660            if (uidArr != null) {
12661                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12662            }
12663            if (replacing) {
12664                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12665            }
12666            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12667                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12668            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12669        }
12670    }
12671
12672   /*
12673     * Look at potentially valid container ids from processCids If package
12674     * information doesn't match the one on record or package scanning fails,
12675     * the cid is added to list of removeCids. We currently don't delete stale
12676     * containers.
12677     */
12678    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12679        ArrayList<String> pkgList = new ArrayList<String>();
12680        Set<AsecInstallArgs> keys = processCids.keySet();
12681
12682        for (AsecInstallArgs args : keys) {
12683            String codePath = processCids.get(args);
12684            if (DEBUG_SD_INSTALL)
12685                Log.i(TAG, "Loading container : " + args.cid);
12686            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12687            try {
12688                // Make sure there are no container errors first.
12689                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12690                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12691                            + " when installing from sdcard");
12692                    continue;
12693                }
12694                // Check code path here.
12695                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12696                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12697                            + " does not match one in settings " + codePath);
12698                    continue;
12699                }
12700                // Parse package
12701                int parseFlags = mDefParseFlags;
12702                if (args.isExternal()) {
12703                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12704                }
12705                if (args.isFwdLocked()) {
12706                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12707                }
12708
12709                synchronized (mInstallLock) {
12710                    PackageParser.Package pkg = null;
12711                    try {
12712                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12713                    } catch (PackageManagerException e) {
12714                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12715                    }
12716                    // Scan the package
12717                    if (pkg != null) {
12718                        /*
12719                         * TODO why is the lock being held? doPostInstall is
12720                         * called in other places without the lock. This needs
12721                         * to be straightened out.
12722                         */
12723                        // writer
12724                        synchronized (mPackages) {
12725                            retCode = PackageManager.INSTALL_SUCCEEDED;
12726                            pkgList.add(pkg.packageName);
12727                            // Post process args
12728                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12729                                    pkg.applicationInfo.uid);
12730                        }
12731                    } else {
12732                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12733                    }
12734                }
12735
12736            } finally {
12737                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12738                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12739                }
12740            }
12741        }
12742        // writer
12743        synchronized (mPackages) {
12744            // If the platform SDK has changed since the last time we booted,
12745            // we need to re-grant app permission to catch any new ones that
12746            // appear. This is really a hack, and means that apps can in some
12747            // cases get permissions that the user didn't initially explicitly
12748            // allow... it would be nice to have some better way to handle
12749            // this situation.
12750            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12751            if (regrantPermissions)
12752                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12753                        + mSdkVersion + "; regranting permissions for external storage");
12754            mSettings.mExternalSdkPlatform = mSdkVersion;
12755
12756            // Make sure group IDs have been assigned, and any permission
12757            // changes in other apps are accounted for
12758            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12759                    | (regrantPermissions
12760                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12761                            : 0));
12762
12763            mSettings.updateExternalDatabaseVersion();
12764
12765            // can downgrade to reader
12766            // Persist settings
12767            mSettings.writeLPr();
12768        }
12769        // Send a broadcast to let everyone know we are done processing
12770        if (pkgList.size() > 0) {
12771            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12772        }
12773    }
12774
12775   /*
12776     * Utility method to unload a list of specified containers
12777     */
12778    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12779        // Just unmount all valid containers.
12780        for (AsecInstallArgs arg : cidArgs) {
12781            synchronized (mInstallLock) {
12782                arg.doPostDeleteLI(false);
12783           }
12784       }
12785   }
12786
12787    /*
12788     * Unload packages mounted on external media. This involves deleting package
12789     * data from internal structures, sending broadcasts about diabled packages,
12790     * gc'ing to free up references, unmounting all secure containers
12791     * corresponding to packages on external media, and posting a
12792     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12793     * that we always have to post this message if status has been requested no
12794     * matter what.
12795     */
12796    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12797            final boolean reportStatus) {
12798        if (DEBUG_SD_INSTALL)
12799            Log.i(TAG, "unloading media packages");
12800        ArrayList<String> pkgList = new ArrayList<String>();
12801        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12802        final Set<AsecInstallArgs> keys = processCids.keySet();
12803        for (AsecInstallArgs args : keys) {
12804            String pkgName = args.getPackageName();
12805            if (DEBUG_SD_INSTALL)
12806                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12807            // Delete package internally
12808            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12809            synchronized (mInstallLock) {
12810                boolean res = deletePackageLI(pkgName, null, false, null, null,
12811                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12812                if (res) {
12813                    pkgList.add(pkgName);
12814                } else {
12815                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12816                    failedList.add(args);
12817                }
12818            }
12819        }
12820
12821        // reader
12822        synchronized (mPackages) {
12823            // We didn't update the settings after removing each package;
12824            // write them now for all packages.
12825            mSettings.writeLPr();
12826        }
12827
12828        // We have to absolutely send UPDATED_MEDIA_STATUS only
12829        // after confirming that all the receivers processed the ordered
12830        // broadcast when packages get disabled, force a gc to clean things up.
12831        // and unload all the containers.
12832        if (pkgList.size() > 0) {
12833            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12834                    new IIntentReceiver.Stub() {
12835                public void performReceive(Intent intent, int resultCode, String data,
12836                        Bundle extras, boolean ordered, boolean sticky,
12837                        int sendingUser) throws RemoteException {
12838                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12839                            reportStatus ? 1 : 0, 1, keys);
12840                    mHandler.sendMessage(msg);
12841                }
12842            });
12843        } else {
12844            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12845                    keys);
12846            mHandler.sendMessage(msg);
12847        }
12848    }
12849
12850    /** Binder call */
12851    @Override
12852    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12853            final int flags) {
12854        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12855        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12856        int returnCode = PackageManager.MOVE_SUCCEEDED;
12857        int currInstallFlags = 0;
12858        int newInstallFlags = 0;
12859
12860        File codeFile = null;
12861        String installerPackageName = null;
12862        String packageAbiOverride = null;
12863
12864        // reader
12865        synchronized (mPackages) {
12866            final PackageParser.Package pkg = mPackages.get(packageName);
12867            final PackageSetting ps = mSettings.mPackages.get(packageName);
12868            if (pkg == null || ps == null) {
12869                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12870            } else {
12871                // Disable moving fwd locked apps and system packages
12872                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12873                    Slog.w(TAG, "Cannot move system application");
12874                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12875                } else if (pkg.mOperationPending) {
12876                    Slog.w(TAG, "Attempt to move package which has pending operations");
12877                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12878                } else {
12879                    // Find install location first
12880                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12881                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12882                        Slog.w(TAG, "Ambigous flags specified for move location.");
12883                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12884                    } else {
12885                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12886                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12887                        currInstallFlags = isExternal(pkg)
12888                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12889
12890                        if (newInstallFlags == currInstallFlags) {
12891                            Slog.w(TAG, "No move required. Trying to move to same location");
12892                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12893                        } else {
12894                            if (isForwardLocked(pkg)) {
12895                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12896                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12897                            }
12898                        }
12899                    }
12900                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12901                        pkg.mOperationPending = true;
12902                    }
12903                }
12904
12905                codeFile = new File(pkg.codePath);
12906                installerPackageName = ps.installerPackageName;
12907                packageAbiOverride = ps.cpuAbiOverrideString;
12908            }
12909        }
12910
12911        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12912            try {
12913                observer.packageMoved(packageName, returnCode);
12914            } catch (RemoteException ignored) {
12915            }
12916            return;
12917        }
12918
12919        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12920            @Override
12921            public void onUserActionRequired(Intent intent) throws RemoteException {
12922                throw new IllegalStateException();
12923            }
12924
12925            @Override
12926            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12927                    Bundle extras) throws RemoteException {
12928                Slog.d(TAG, "Install result for move: "
12929                        + PackageManager.installStatusToString(returnCode, msg));
12930
12931                // We usually have a new package now after the install, but if
12932                // we failed we need to clear the pending flag on the original
12933                // package object.
12934                synchronized (mPackages) {
12935                    final PackageParser.Package pkg = mPackages.get(packageName);
12936                    if (pkg != null) {
12937                        pkg.mOperationPending = false;
12938                    }
12939                }
12940
12941                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12942                switch (status) {
12943                    case PackageInstaller.STATUS_SUCCESS:
12944                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12945                        break;
12946                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12947                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12948                        break;
12949                    default:
12950                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12951                        break;
12952                }
12953            }
12954        };
12955
12956        // Treat a move like reinstalling an existing app, which ensures that we
12957        // process everythign uniformly, like unpacking native libraries.
12958        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12959
12960        final Message msg = mHandler.obtainMessage(INIT_COPY);
12961        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12962        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12963                installerPackageName, null, user, packageAbiOverride);
12964        mHandler.sendMessage(msg);
12965    }
12966
12967    @Override
12968    public boolean setInstallLocation(int loc) {
12969        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12970                null);
12971        if (getInstallLocation() == loc) {
12972            return true;
12973        }
12974        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12975                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12976            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12977                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12978            return true;
12979        }
12980        return false;
12981   }
12982
12983    @Override
12984    public int getInstallLocation() {
12985        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12986                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12987                PackageHelper.APP_INSTALL_AUTO);
12988    }
12989
12990    /** Called by UserManagerService */
12991    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12992        mDirtyUsers.remove(userHandle);
12993        mSettings.removeUserLPw(userHandle);
12994        mPendingBroadcasts.remove(userHandle);
12995        if (mInstaller != null) {
12996            // Technically, we shouldn't be doing this with the package lock
12997            // held.  However, this is very rare, and there is already so much
12998            // other disk I/O going on, that we'll let it slide for now.
12999            mInstaller.removeUserDataDirs(userHandle);
13000        }
13001        mUserNeedsBadging.delete(userHandle);
13002        removeUnusedPackagesLILPw(userManager, userHandle);
13003    }
13004
13005    /**
13006     * We're removing userHandle and would like to remove any downloaded packages
13007     * that are no longer in use by any other user.
13008     * @param userHandle the user being removed
13009     */
13010    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13011        final boolean DEBUG_CLEAN_APKS = false;
13012        int [] users = userManager.getUserIdsLPr();
13013        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13014        while (psit.hasNext()) {
13015            PackageSetting ps = psit.next();
13016            if (ps.pkg == null) {
13017                continue;
13018            }
13019            final String packageName = ps.pkg.packageName;
13020            // Skip over if system app
13021            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13022                continue;
13023            }
13024            if (DEBUG_CLEAN_APKS) {
13025                Slog.i(TAG, "Checking package " + packageName);
13026            }
13027            boolean keep = false;
13028            for (int i = 0; i < users.length; i++) {
13029                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13030                    keep = true;
13031                    if (DEBUG_CLEAN_APKS) {
13032                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13033                                + users[i]);
13034                    }
13035                    break;
13036                }
13037            }
13038            if (!keep) {
13039                if (DEBUG_CLEAN_APKS) {
13040                    Slog.i(TAG, "  Removing package " + packageName);
13041                }
13042                mHandler.post(new Runnable() {
13043                    public void run() {
13044                        deletePackageX(packageName, userHandle, 0);
13045                    } //end run
13046                });
13047            }
13048        }
13049    }
13050
13051    /** Called by UserManagerService */
13052    void createNewUserLILPw(int userHandle, File path) {
13053        if (mInstaller != null) {
13054            mInstaller.createUserConfig(userHandle);
13055            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13056        }
13057    }
13058
13059    @Override
13060    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13061        mContext.enforceCallingOrSelfPermission(
13062                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13063                "Only package verification agents can read the verifier device identity");
13064
13065        synchronized (mPackages) {
13066            return mSettings.getVerifierDeviceIdentityLPw();
13067        }
13068    }
13069
13070    @Override
13071    public void setPermissionEnforced(String permission, boolean enforced) {
13072        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13073        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13074            synchronized (mPackages) {
13075                if (mSettings.mReadExternalStorageEnforced == null
13076                        || mSettings.mReadExternalStorageEnforced != enforced) {
13077                    mSettings.mReadExternalStorageEnforced = enforced;
13078                    mSettings.writeLPr();
13079                }
13080            }
13081            // kill any non-foreground processes so we restart them and
13082            // grant/revoke the GID.
13083            final IActivityManager am = ActivityManagerNative.getDefault();
13084            if (am != null) {
13085                final long token = Binder.clearCallingIdentity();
13086                try {
13087                    am.killProcessesBelowForeground("setPermissionEnforcement");
13088                } catch (RemoteException e) {
13089                } finally {
13090                    Binder.restoreCallingIdentity(token);
13091                }
13092            }
13093        } else {
13094            throw new IllegalArgumentException("No selective enforcement for " + permission);
13095        }
13096    }
13097
13098    @Override
13099    @Deprecated
13100    public boolean isPermissionEnforced(String permission) {
13101        return true;
13102    }
13103
13104    @Override
13105    public boolean isStorageLow() {
13106        final long token = Binder.clearCallingIdentity();
13107        try {
13108            final DeviceStorageMonitorInternal
13109                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13110            if (dsm != null) {
13111                return dsm.isMemoryLow();
13112            } else {
13113                return false;
13114            }
13115        } finally {
13116            Binder.restoreCallingIdentity(token);
13117        }
13118    }
13119
13120    @Override
13121    public IPackageInstaller getPackageInstaller() {
13122        return mInstallerService;
13123    }
13124
13125    private boolean userNeedsBadging(int userId) {
13126        int index = mUserNeedsBadging.indexOfKey(userId);
13127        if (index < 0) {
13128            final UserInfo userInfo;
13129            final long token = Binder.clearCallingIdentity();
13130            try {
13131                userInfo = sUserManager.getUserInfo(userId);
13132            } finally {
13133                Binder.restoreCallingIdentity(token);
13134            }
13135            final boolean b;
13136            if (userInfo != null && userInfo.isManagedProfile()) {
13137                b = true;
13138            } else {
13139                b = false;
13140            }
13141            mUserNeedsBadging.put(userId, b);
13142            return b;
13143        }
13144        return mUserNeedsBadging.valueAt(index);
13145    }
13146
13147    @Override
13148    public KeySet getKeySetByAlias(String packageName, String alias) {
13149        if (packageName == null || alias == null) {
13150            return null;
13151        }
13152        synchronized(mPackages) {
13153            final PackageParser.Package pkg = mPackages.get(packageName);
13154            if (pkg == null) {
13155                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13156                throw new IllegalArgumentException("Unknown package: " + packageName);
13157            }
13158            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13159            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13160        }
13161    }
13162
13163    @Override
13164    public KeySet getSigningKeySet(String packageName) {
13165        if (packageName == null) {
13166            return null;
13167        }
13168        synchronized(mPackages) {
13169            final PackageParser.Package pkg = mPackages.get(packageName);
13170            if (pkg == null) {
13171                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13172                throw new IllegalArgumentException("Unknown package: " + packageName);
13173            }
13174            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13175                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13176                throw new SecurityException("May not access signing KeySet of other apps.");
13177            }
13178            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13179            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13180        }
13181    }
13182
13183    @Override
13184    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13185        if (packageName == null || ks == null) {
13186            return false;
13187        }
13188        synchronized(mPackages) {
13189            final PackageParser.Package pkg = mPackages.get(packageName);
13190            if (pkg == null) {
13191                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13192                throw new IllegalArgumentException("Unknown package: " + packageName);
13193            }
13194            IBinder ksh = ks.getToken();
13195            if (ksh instanceof KeySetHandle) {
13196                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13197                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13198            }
13199            return false;
13200        }
13201    }
13202
13203    @Override
13204    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13205        if (packageName == null || ks == null) {
13206            return false;
13207        }
13208        synchronized(mPackages) {
13209            final PackageParser.Package pkg = mPackages.get(packageName);
13210            if (pkg == null) {
13211                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13212                throw new IllegalArgumentException("Unknown package: " + packageName);
13213            }
13214            IBinder ksh = ks.getToken();
13215            if (ksh instanceof KeySetHandle) {
13216                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13217                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13218            }
13219            return false;
13220        }
13221    }
13222}
13223