PackageManagerService.java revision c788487ae5b28bb6f84410fcdb101f0bdfcd467e
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
1796        // TODO: try cleaning up codePath directory contents first, since it
1797        // might be a cluster
1798
1799        if (ps.codePath != null) {
1800            if (!ps.codePath.delete()) {
1801                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1802            }
1803        }
1804        if (ps.resourcePath != null) {
1805            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1806                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1807            }
1808        }
1809        mSettings.removePackageLPw(ps.name);
1810    }
1811
1812    static int[] appendInts(int[] cur, int[] add) {
1813        if (add == null) return cur;
1814        if (cur == null) return add;
1815        final int N = add.length;
1816        for (int i=0; i<N; i++) {
1817            cur = appendInt(cur, add[i]);
1818        }
1819        return cur;
1820    }
1821
1822    static int[] removeInts(int[] cur, int[] rem) {
1823        if (rem == null) return cur;
1824        if (cur == null) return cur;
1825        final int N = rem.length;
1826        for (int i=0; i<N; i++) {
1827            cur = removeInt(cur, rem[i]);
1828        }
1829        return cur;
1830    }
1831
1832    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1833        if (!sUserManager.exists(userId)) return null;
1834        final PackageSetting ps = (PackageSetting) p.mExtras;
1835        if (ps == null) {
1836            return null;
1837        }
1838        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1839        final PackageUserState state = ps.readUserState(userId);
1840        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1841                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1842                state, userId);
1843    }
1844
1845    @Override
1846    public boolean isPackageAvailable(String packageName, int userId) {
1847        if (!sUserManager.exists(userId)) return false;
1848        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1849        synchronized (mPackages) {
1850            PackageParser.Package p = mPackages.get(packageName);
1851            if (p != null) {
1852                final PackageSetting ps = (PackageSetting) p.mExtras;
1853                if (ps != null) {
1854                    final PackageUserState state = ps.readUserState(userId);
1855                    if (state != null) {
1856                        return PackageParser.isAvailable(state);
1857                    }
1858                }
1859            }
1860        }
1861        return false;
1862    }
1863
1864    @Override
1865    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1866        if (!sUserManager.exists(userId)) return null;
1867        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1868        // reader
1869        synchronized (mPackages) {
1870            PackageParser.Package p = mPackages.get(packageName);
1871            if (DEBUG_PACKAGE_INFO)
1872                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1873            if (p != null) {
1874                return generatePackageInfo(p, flags, userId);
1875            }
1876            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1877                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1878            }
1879        }
1880        return null;
1881    }
1882
1883    @Override
1884    public String[] currentToCanonicalPackageNames(String[] names) {
1885        String[] out = new String[names.length];
1886        // reader
1887        synchronized (mPackages) {
1888            for (int i=names.length-1; i>=0; i--) {
1889                PackageSetting ps = mSettings.mPackages.get(names[i]);
1890                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1891            }
1892        }
1893        return out;
1894    }
1895
1896    @Override
1897    public String[] canonicalToCurrentPackageNames(String[] names) {
1898        String[] out = new String[names.length];
1899        // reader
1900        synchronized (mPackages) {
1901            for (int i=names.length-1; i>=0; i--) {
1902                String cur = mSettings.mRenamedPackages.get(names[i]);
1903                out[i] = cur != null ? cur : names[i];
1904            }
1905        }
1906        return out;
1907    }
1908
1909    @Override
1910    public int getPackageUid(String packageName, int userId) {
1911        if (!sUserManager.exists(userId)) return -1;
1912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1913        // reader
1914        synchronized (mPackages) {
1915            PackageParser.Package p = mPackages.get(packageName);
1916            if(p != null) {
1917                return UserHandle.getUid(userId, p.applicationInfo.uid);
1918            }
1919            PackageSetting ps = mSettings.mPackages.get(packageName);
1920            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1921                return -1;
1922            }
1923            p = ps.pkg;
1924            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1925        }
1926    }
1927
1928    @Override
1929    public int[] getPackageGids(String packageName) {
1930        // reader
1931        synchronized (mPackages) {
1932            PackageParser.Package p = mPackages.get(packageName);
1933            if (DEBUG_PACKAGE_INFO)
1934                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1935            if (p != null) {
1936                final PackageSetting ps = (PackageSetting)p.mExtras;
1937                return ps.getGids();
1938            }
1939        }
1940        // stupid thing to indicate an error.
1941        return new int[0];
1942    }
1943
1944    static final PermissionInfo generatePermissionInfo(
1945            BasePermission bp, int flags) {
1946        if (bp.perm != null) {
1947            return PackageParser.generatePermissionInfo(bp.perm, flags);
1948        }
1949        PermissionInfo pi = new PermissionInfo();
1950        pi.name = bp.name;
1951        pi.packageName = bp.sourcePackage;
1952        pi.nonLocalizedLabel = bp.name;
1953        pi.protectionLevel = bp.protectionLevel;
1954        return pi;
1955    }
1956
1957    @Override
1958    public PermissionInfo getPermissionInfo(String name, int flags) {
1959        // reader
1960        synchronized (mPackages) {
1961            final BasePermission p = mSettings.mPermissions.get(name);
1962            if (p != null) {
1963                return generatePermissionInfo(p, flags);
1964            }
1965            return null;
1966        }
1967    }
1968
1969    @Override
1970    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1971        // reader
1972        synchronized (mPackages) {
1973            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1974            for (BasePermission p : mSettings.mPermissions.values()) {
1975                if (group == null) {
1976                    if (p.perm == null || p.perm.info.group == null) {
1977                        out.add(generatePermissionInfo(p, flags));
1978                    }
1979                } else {
1980                    if (p.perm != null && group.equals(p.perm.info.group)) {
1981                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1982                    }
1983                }
1984            }
1985
1986            if (out.size() > 0) {
1987                return out;
1988            }
1989            return mPermissionGroups.containsKey(group) ? out : null;
1990        }
1991    }
1992
1993    @Override
1994    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1995        // reader
1996        synchronized (mPackages) {
1997            return PackageParser.generatePermissionGroupInfo(
1998                    mPermissionGroups.get(name), flags);
1999        }
2000    }
2001
2002    @Override
2003    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2004        // reader
2005        synchronized (mPackages) {
2006            final int N = mPermissionGroups.size();
2007            ArrayList<PermissionGroupInfo> out
2008                    = new ArrayList<PermissionGroupInfo>(N);
2009            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2010                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2011            }
2012            return out;
2013        }
2014    }
2015
2016    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2017            int userId) {
2018        if (!sUserManager.exists(userId)) return null;
2019        PackageSetting ps = mSettings.mPackages.get(packageName);
2020        if (ps != null) {
2021            if (ps.pkg == null) {
2022                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2023                        flags, userId);
2024                if (pInfo != null) {
2025                    return pInfo.applicationInfo;
2026                }
2027                return null;
2028            }
2029            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2030                    ps.readUserState(userId), userId);
2031        }
2032        return null;
2033    }
2034
2035    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2036            int userId) {
2037        if (!sUserManager.exists(userId)) return null;
2038        PackageSetting ps = mSettings.mPackages.get(packageName);
2039        if (ps != null) {
2040            PackageParser.Package pkg = ps.pkg;
2041            if (pkg == null) {
2042                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2043                    return null;
2044                }
2045                // Only data remains, so we aren't worried about code paths
2046                pkg = new PackageParser.Package(packageName);
2047                pkg.applicationInfo.packageName = packageName;
2048                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2049                pkg.applicationInfo.dataDir =
2050                        getDataPathForPackage(packageName, 0).getPath();
2051                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2052                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2053            }
2054            return generatePackageInfo(pkg, flags, userId);
2055        }
2056        return null;
2057    }
2058
2059    @Override
2060    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2061        if (!sUserManager.exists(userId)) return null;
2062        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2063        // writer
2064        synchronized (mPackages) {
2065            PackageParser.Package p = mPackages.get(packageName);
2066            if (DEBUG_PACKAGE_INFO) Log.v(
2067                    TAG, "getApplicationInfo " + packageName
2068                    + ": " + p);
2069            if (p != null) {
2070                PackageSetting ps = mSettings.mPackages.get(packageName);
2071                if (ps == null) return null;
2072                // Note: isEnabledLP() does not apply here - always return info
2073                return PackageParser.generateApplicationInfo(
2074                        p, flags, ps.readUserState(userId), userId);
2075            }
2076            if ("android".equals(packageName)||"system".equals(packageName)) {
2077                return mAndroidApplication;
2078            }
2079            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2080                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2081            }
2082        }
2083        return null;
2084    }
2085
2086
2087    @Override
2088    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2089        mContext.enforceCallingOrSelfPermission(
2090                android.Manifest.permission.CLEAR_APP_CACHE, null);
2091        // Queue up an async operation since clearing cache may take a little while.
2092        mHandler.post(new Runnable() {
2093            public void run() {
2094                mHandler.removeCallbacks(this);
2095                int retCode = -1;
2096                synchronized (mInstallLock) {
2097                    retCode = mInstaller.freeCache(freeStorageSize);
2098                    if (retCode < 0) {
2099                        Slog.w(TAG, "Couldn't clear application caches");
2100                    }
2101                }
2102                if (observer != null) {
2103                    try {
2104                        observer.onRemoveCompleted(null, (retCode >= 0));
2105                    } catch (RemoteException e) {
2106                        Slog.w(TAG, "RemoveException when invoking call back");
2107                    }
2108                }
2109            }
2110        });
2111    }
2112
2113    @Override
2114    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2115        mContext.enforceCallingOrSelfPermission(
2116                android.Manifest.permission.CLEAR_APP_CACHE, null);
2117        // Queue up an async operation since clearing cache may take a little while.
2118        mHandler.post(new Runnable() {
2119            public void run() {
2120                mHandler.removeCallbacks(this);
2121                int retCode = -1;
2122                synchronized (mInstallLock) {
2123                    retCode = mInstaller.freeCache(freeStorageSize);
2124                    if (retCode < 0) {
2125                        Slog.w(TAG, "Couldn't clear application caches");
2126                    }
2127                }
2128                if(pi != null) {
2129                    try {
2130                        // Callback via pending intent
2131                        int code = (retCode >= 0) ? 1 : 0;
2132                        pi.sendIntent(null, code, null,
2133                                null, null);
2134                    } catch (SendIntentException e1) {
2135                        Slog.i(TAG, "Failed to send pending intent");
2136                    }
2137                }
2138            }
2139        });
2140    }
2141
2142    void freeStorage(long freeStorageSize) throws IOException {
2143        synchronized (mInstallLock) {
2144            if (mInstaller.freeCache(freeStorageSize) < 0) {
2145                throw new IOException("Failed to free enough space");
2146            }
2147        }
2148    }
2149
2150    @Override
2151    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2152        if (!sUserManager.exists(userId)) return null;
2153        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2154        synchronized (mPackages) {
2155            PackageParser.Activity a = mActivities.mActivities.get(component);
2156
2157            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2158            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2159                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2160                if (ps == null) return null;
2161                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2162                        userId);
2163            }
2164            if (mResolveComponentName.equals(component)) {
2165                return mResolveActivity;
2166            }
2167        }
2168        return null;
2169    }
2170
2171    @Override
2172    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2173            String resolvedType) {
2174        synchronized (mPackages) {
2175            PackageParser.Activity a = mActivities.mActivities.get(component);
2176            if (a == null) {
2177                return false;
2178            }
2179            for (int i=0; i<a.intents.size(); i++) {
2180                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2181                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2182                    return true;
2183                }
2184            }
2185            return false;
2186        }
2187    }
2188
2189    @Override
2190    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2191        if (!sUserManager.exists(userId)) return null;
2192        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2193        synchronized (mPackages) {
2194            PackageParser.Activity a = mReceivers.mActivities.get(component);
2195            if (DEBUG_PACKAGE_INFO) Log.v(
2196                TAG, "getReceiverInfo " + component + ": " + a);
2197            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2198                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2199                if (ps == null) return null;
2200                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2201                        userId);
2202            }
2203        }
2204        return null;
2205    }
2206
2207    @Override
2208    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2209        if (!sUserManager.exists(userId)) return null;
2210        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2211        synchronized (mPackages) {
2212            PackageParser.Service s = mServices.mServices.get(component);
2213            if (DEBUG_PACKAGE_INFO) Log.v(
2214                TAG, "getServiceInfo " + component + ": " + s);
2215            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2216                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2217                if (ps == null) return null;
2218                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2219                        userId);
2220            }
2221        }
2222        return null;
2223    }
2224
2225    @Override
2226    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2227        if (!sUserManager.exists(userId)) return null;
2228        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2229        synchronized (mPackages) {
2230            PackageParser.Provider p = mProviders.mProviders.get(component);
2231            if (DEBUG_PACKAGE_INFO) Log.v(
2232                TAG, "getProviderInfo " + component + ": " + p);
2233            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2234                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2235                if (ps == null) return null;
2236                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2237                        userId);
2238            }
2239        }
2240        return null;
2241    }
2242
2243    @Override
2244    public String[] getSystemSharedLibraryNames() {
2245        Set<String> libSet;
2246        synchronized (mPackages) {
2247            libSet = mSharedLibraries.keySet();
2248            int size = libSet.size();
2249            if (size > 0) {
2250                String[] libs = new String[size];
2251                libSet.toArray(libs);
2252                return libs;
2253            }
2254        }
2255        return null;
2256    }
2257
2258    @Override
2259    public FeatureInfo[] getSystemAvailableFeatures() {
2260        Collection<FeatureInfo> featSet;
2261        synchronized (mPackages) {
2262            featSet = mAvailableFeatures.values();
2263            int size = featSet.size();
2264            if (size > 0) {
2265                FeatureInfo[] features = new FeatureInfo[size+1];
2266                featSet.toArray(features);
2267                FeatureInfo fi = new FeatureInfo();
2268                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2269                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2270                features[size] = fi;
2271                return features;
2272            }
2273        }
2274        return null;
2275    }
2276
2277    @Override
2278    public boolean hasSystemFeature(String name) {
2279        synchronized (mPackages) {
2280            return mAvailableFeatures.containsKey(name);
2281        }
2282    }
2283
2284    private void checkValidCaller(int uid, int userId) {
2285        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2286            return;
2287
2288        throw new SecurityException("Caller uid=" + uid
2289                + " is not privileged to communicate with user=" + userId);
2290    }
2291
2292    @Override
2293    public int checkPermission(String permName, String pkgName) {
2294        synchronized (mPackages) {
2295            PackageParser.Package p = mPackages.get(pkgName);
2296            if (p != null && p.mExtras != null) {
2297                PackageSetting ps = (PackageSetting)p.mExtras;
2298                if (ps.sharedUser != null) {
2299                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2300                        return PackageManager.PERMISSION_GRANTED;
2301                    }
2302                } else if (ps.grantedPermissions.contains(permName)) {
2303                    return PackageManager.PERMISSION_GRANTED;
2304                }
2305            }
2306        }
2307        return PackageManager.PERMISSION_DENIED;
2308    }
2309
2310    @Override
2311    public int checkUidPermission(String permName, int uid) {
2312        synchronized (mPackages) {
2313            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2314            if (obj != null) {
2315                GrantedPermissions gp = (GrantedPermissions)obj;
2316                if (gp.grantedPermissions.contains(permName)) {
2317                    return PackageManager.PERMISSION_GRANTED;
2318                }
2319            } else {
2320                HashSet<String> perms = mSystemPermissions.get(uid);
2321                if (perms != null && perms.contains(permName)) {
2322                    return PackageManager.PERMISSION_GRANTED;
2323                }
2324            }
2325        }
2326        return PackageManager.PERMISSION_DENIED;
2327    }
2328
2329    /**
2330     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2331     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2332     * @param message the message to log on security exception
2333     */
2334    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2335            String message) {
2336        if (userId < 0) {
2337            throw new IllegalArgumentException("Invalid userId " + userId);
2338        }
2339        if (userId == UserHandle.getUserId(callingUid)) return;
2340        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2341            if (requireFullPermission) {
2342                mContext.enforceCallingOrSelfPermission(
2343                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2344            } else {
2345                try {
2346                    mContext.enforceCallingOrSelfPermission(
2347                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2348                } catch (SecurityException se) {
2349                    mContext.enforceCallingOrSelfPermission(
2350                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2351                }
2352            }
2353        }
2354    }
2355
2356    private BasePermission findPermissionTreeLP(String permName) {
2357        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2358            if (permName.startsWith(bp.name) &&
2359                    permName.length() > bp.name.length() &&
2360                    permName.charAt(bp.name.length()) == '.') {
2361                return bp;
2362            }
2363        }
2364        return null;
2365    }
2366
2367    private BasePermission checkPermissionTreeLP(String permName) {
2368        if (permName != null) {
2369            BasePermission bp = findPermissionTreeLP(permName);
2370            if (bp != null) {
2371                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2372                    return bp;
2373                }
2374                throw new SecurityException("Calling uid "
2375                        + Binder.getCallingUid()
2376                        + " is not allowed to add to permission tree "
2377                        + bp.name + " owned by uid " + bp.uid);
2378            }
2379        }
2380        throw new SecurityException("No permission tree found for " + permName);
2381    }
2382
2383    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2384        if (s1 == null) {
2385            return s2 == null;
2386        }
2387        if (s2 == null) {
2388            return false;
2389        }
2390        if (s1.getClass() != s2.getClass()) {
2391            return false;
2392        }
2393        return s1.equals(s2);
2394    }
2395
2396    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2397        if (pi1.icon != pi2.icon) return false;
2398        if (pi1.logo != pi2.logo) return false;
2399        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2400        if (!compareStrings(pi1.name, pi2.name)) return false;
2401        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2402        // We'll take care of setting this one.
2403        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2404        // These are not currently stored in settings.
2405        //if (!compareStrings(pi1.group, pi2.group)) return false;
2406        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2407        //if (pi1.labelRes != pi2.labelRes) return false;
2408        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2409        return true;
2410    }
2411
2412    int permissionInfoFootprint(PermissionInfo info) {
2413        int size = info.name.length();
2414        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2415        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2416        return size;
2417    }
2418
2419    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2420        int size = 0;
2421        for (BasePermission perm : mSettings.mPermissions.values()) {
2422            if (perm.uid == tree.uid) {
2423                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2424            }
2425        }
2426        return size;
2427    }
2428
2429    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2430        // We calculate the max size of permissions defined by this uid and throw
2431        // if that plus the size of 'info' would exceed our stated maximum.
2432        if (tree.uid != Process.SYSTEM_UID) {
2433            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2434            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2435                throw new SecurityException("Permission tree size cap exceeded");
2436            }
2437        }
2438    }
2439
2440    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2441        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2442            throw new SecurityException("Label must be specified in permission");
2443        }
2444        BasePermission tree = checkPermissionTreeLP(info.name);
2445        BasePermission bp = mSettings.mPermissions.get(info.name);
2446        boolean added = bp == null;
2447        boolean changed = true;
2448        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2449        if (added) {
2450            enforcePermissionCapLocked(info, tree);
2451            bp = new BasePermission(info.name, tree.sourcePackage,
2452                    BasePermission.TYPE_DYNAMIC);
2453        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2454            throw new SecurityException(
2455                    "Not allowed to modify non-dynamic permission "
2456                    + info.name);
2457        } else {
2458            if (bp.protectionLevel == fixedLevel
2459                    && bp.perm.owner.equals(tree.perm.owner)
2460                    && bp.uid == tree.uid
2461                    && comparePermissionInfos(bp.perm.info, info)) {
2462                changed = false;
2463            }
2464        }
2465        bp.protectionLevel = fixedLevel;
2466        info = new PermissionInfo(info);
2467        info.protectionLevel = fixedLevel;
2468        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2469        bp.perm.info.packageName = tree.perm.info.packageName;
2470        bp.uid = tree.uid;
2471        if (added) {
2472            mSettings.mPermissions.put(info.name, bp);
2473        }
2474        if (changed) {
2475            if (!async) {
2476                mSettings.writeLPr();
2477            } else {
2478                scheduleWriteSettingsLocked();
2479            }
2480        }
2481        return added;
2482    }
2483
2484    @Override
2485    public boolean addPermission(PermissionInfo info) {
2486        synchronized (mPackages) {
2487            return addPermissionLocked(info, false);
2488        }
2489    }
2490
2491    @Override
2492    public boolean addPermissionAsync(PermissionInfo info) {
2493        synchronized (mPackages) {
2494            return addPermissionLocked(info, true);
2495        }
2496    }
2497
2498    @Override
2499    public void removePermission(String name) {
2500        synchronized (mPackages) {
2501            checkPermissionTreeLP(name);
2502            BasePermission bp = mSettings.mPermissions.get(name);
2503            if (bp != null) {
2504                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2505                    throw new SecurityException(
2506                            "Not allowed to modify non-dynamic permission "
2507                            + name);
2508                }
2509                mSettings.mPermissions.remove(name);
2510                mSettings.writeLPr();
2511            }
2512        }
2513    }
2514
2515    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2516        int index = pkg.requestedPermissions.indexOf(bp.name);
2517        if (index == -1) {
2518            throw new SecurityException("Package " + pkg.packageName
2519                    + " has not requested permission " + bp.name);
2520        }
2521        boolean isNormal =
2522                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2523                        == PermissionInfo.PROTECTION_NORMAL);
2524        boolean isDangerous =
2525                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2526                        == PermissionInfo.PROTECTION_DANGEROUS);
2527        boolean isDevelopment =
2528                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2529
2530        if (!isNormal && !isDangerous && !isDevelopment) {
2531            throw new SecurityException("Permission " + bp.name
2532                    + " is not a changeable permission type");
2533        }
2534
2535        if (isNormal || isDangerous) {
2536            if (pkg.requestedPermissionsRequired.get(index)) {
2537                throw new SecurityException("Can't change " + bp.name
2538                        + ". It is required by the application");
2539            }
2540        }
2541    }
2542
2543    @Override
2544    public void grantPermission(String packageName, String permissionName) {
2545        mContext.enforceCallingOrSelfPermission(
2546                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2547        synchronized (mPackages) {
2548            final PackageParser.Package pkg = mPackages.get(packageName);
2549            if (pkg == null) {
2550                throw new IllegalArgumentException("Unknown package: " + packageName);
2551            }
2552            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2553            if (bp == null) {
2554                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2555            }
2556
2557            checkGrantRevokePermissions(pkg, bp);
2558
2559            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2560            if (ps == null) {
2561                return;
2562            }
2563            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2564            if (gp.grantedPermissions.add(permissionName)) {
2565                if (ps.haveGids) {
2566                    gp.gids = appendInts(gp.gids, bp.gids);
2567                }
2568                mSettings.writeLPr();
2569            }
2570        }
2571    }
2572
2573    @Override
2574    public void revokePermission(String packageName, String permissionName) {
2575        int changedAppId = -1;
2576
2577        synchronized (mPackages) {
2578            final PackageParser.Package pkg = mPackages.get(packageName);
2579            if (pkg == null) {
2580                throw new IllegalArgumentException("Unknown package: " + packageName);
2581            }
2582            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2583                mContext.enforceCallingOrSelfPermission(
2584                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2585            }
2586            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2587            if (bp == null) {
2588                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2589            }
2590
2591            checkGrantRevokePermissions(pkg, bp);
2592
2593            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2594            if (ps == null) {
2595                return;
2596            }
2597            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2598            if (gp.grantedPermissions.remove(permissionName)) {
2599                gp.grantedPermissions.remove(permissionName);
2600                if (ps.haveGids) {
2601                    gp.gids = removeInts(gp.gids, bp.gids);
2602                }
2603                mSettings.writeLPr();
2604                changedAppId = ps.appId;
2605            }
2606        }
2607
2608        if (changedAppId >= 0) {
2609            // We changed the perm on someone, kill its processes.
2610            IActivityManager am = ActivityManagerNative.getDefault();
2611            if (am != null) {
2612                final int callingUserId = UserHandle.getCallingUserId();
2613                final long ident = Binder.clearCallingIdentity();
2614                try {
2615                    //XXX we should only revoke for the calling user's app permissions,
2616                    // but for now we impact all users.
2617                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2618                    //        "revoke " + permissionName);
2619                    int[] users = sUserManager.getUserIds();
2620                    for (int user : users) {
2621                        am.killUid(UserHandle.getUid(user, changedAppId),
2622                                "revoke " + permissionName);
2623                    }
2624                } catch (RemoteException e) {
2625                } finally {
2626                    Binder.restoreCallingIdentity(ident);
2627                }
2628            }
2629        }
2630    }
2631
2632    @Override
2633    public boolean isProtectedBroadcast(String actionName) {
2634        synchronized (mPackages) {
2635            return mProtectedBroadcasts.contains(actionName);
2636        }
2637    }
2638
2639    @Override
2640    public int checkSignatures(String pkg1, String pkg2) {
2641        synchronized (mPackages) {
2642            final PackageParser.Package p1 = mPackages.get(pkg1);
2643            final PackageParser.Package p2 = mPackages.get(pkg2);
2644            if (p1 == null || p1.mExtras == null
2645                    || p2 == null || p2.mExtras == null) {
2646                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2647            }
2648            return compareSignatures(p1.mSignatures, p2.mSignatures);
2649        }
2650    }
2651
2652    @Override
2653    public int checkUidSignatures(int uid1, int uid2) {
2654        // Map to base uids.
2655        uid1 = UserHandle.getAppId(uid1);
2656        uid2 = UserHandle.getAppId(uid2);
2657        // reader
2658        synchronized (mPackages) {
2659            Signature[] s1;
2660            Signature[] s2;
2661            Object obj = mSettings.getUserIdLPr(uid1);
2662            if (obj != null) {
2663                if (obj instanceof SharedUserSetting) {
2664                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2665                } else if (obj instanceof PackageSetting) {
2666                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2667                } else {
2668                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2669                }
2670            } else {
2671                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2672            }
2673            obj = mSettings.getUserIdLPr(uid2);
2674            if (obj != null) {
2675                if (obj instanceof SharedUserSetting) {
2676                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2677                } else if (obj instanceof PackageSetting) {
2678                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2679                } else {
2680                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2681                }
2682            } else {
2683                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2684            }
2685            return compareSignatures(s1, s2);
2686        }
2687    }
2688
2689    /**
2690     * Compares two sets of signatures. Returns:
2691     * <br />
2692     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2693     * <br />
2694     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2695     * <br />
2696     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2697     * <br />
2698     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2699     * <br />
2700     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2701     */
2702    static int compareSignatures(Signature[] s1, Signature[] s2) {
2703        if (s1 == null) {
2704            return s2 == null
2705                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2706                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2707        }
2708
2709        if (s2 == null) {
2710            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2711        }
2712
2713        if (s1.length != s2.length) {
2714            return PackageManager.SIGNATURE_NO_MATCH;
2715        }
2716
2717        // Since both signature sets are of size 1, we can compare without HashSets.
2718        if (s1.length == 1) {
2719            return s1[0].equals(s2[0]) ?
2720                    PackageManager.SIGNATURE_MATCH :
2721                    PackageManager.SIGNATURE_NO_MATCH;
2722        }
2723
2724        HashSet<Signature> set1 = new HashSet<Signature>();
2725        for (Signature sig : s1) {
2726            set1.add(sig);
2727        }
2728        HashSet<Signature> set2 = new HashSet<Signature>();
2729        for (Signature sig : s2) {
2730            set2.add(sig);
2731        }
2732        // Make sure s2 contains all signatures in s1.
2733        if (set1.equals(set2)) {
2734            return PackageManager.SIGNATURE_MATCH;
2735        }
2736        return PackageManager.SIGNATURE_NO_MATCH;
2737    }
2738
2739    /**
2740     * If the database version for this type of package (internal storage or
2741     * external storage) is less than the version where package signatures
2742     * were updated, return true.
2743     */
2744    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2745        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2746                DatabaseVersion.SIGNATURE_END_ENTITY))
2747                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2748                        DatabaseVersion.SIGNATURE_END_ENTITY));
2749    }
2750
2751    /**
2752     * Used for backward compatibility to make sure any packages with
2753     * certificate chains get upgraded to the new style. {@code existingSigs}
2754     * will be in the old format (since they were stored on disk from before the
2755     * system upgrade) and {@code scannedSigs} will be in the newer format.
2756     */
2757    private int compareSignaturesCompat(PackageSignatures existingSigs,
2758            PackageParser.Package scannedPkg) {
2759        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2760            return PackageManager.SIGNATURE_NO_MATCH;
2761        }
2762
2763        HashSet<Signature> existingSet = new HashSet<Signature>();
2764        for (Signature sig : existingSigs.mSignatures) {
2765            existingSet.add(sig);
2766        }
2767        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2768        for (Signature sig : scannedPkg.mSignatures) {
2769            try {
2770                Signature[] chainSignatures = sig.getChainSignatures();
2771                for (Signature chainSig : chainSignatures) {
2772                    scannedCompatSet.add(chainSig);
2773                }
2774            } catch (CertificateEncodingException e) {
2775                scannedCompatSet.add(sig);
2776            }
2777        }
2778        /*
2779         * Make sure the expanded scanned set contains all signatures in the
2780         * existing one.
2781         */
2782        if (scannedCompatSet.equals(existingSet)) {
2783            // Migrate the old signatures to the new scheme.
2784            existingSigs.assignSignatures(scannedPkg.mSignatures);
2785            // The new KeySets will be re-added later in the scanning process.
2786            synchronized (mPackages) {
2787                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2788            }
2789            return PackageManager.SIGNATURE_MATCH;
2790        }
2791        return PackageManager.SIGNATURE_NO_MATCH;
2792    }
2793
2794    @Override
2795    public String[] getPackagesForUid(int uid) {
2796        uid = UserHandle.getAppId(uid);
2797        // reader
2798        synchronized (mPackages) {
2799            Object obj = mSettings.getUserIdLPr(uid);
2800            if (obj instanceof SharedUserSetting) {
2801                final SharedUserSetting sus = (SharedUserSetting) obj;
2802                final int N = sus.packages.size();
2803                final String[] res = new String[N];
2804                final Iterator<PackageSetting> it = sus.packages.iterator();
2805                int i = 0;
2806                while (it.hasNext()) {
2807                    res[i++] = it.next().name;
2808                }
2809                return res;
2810            } else if (obj instanceof PackageSetting) {
2811                final PackageSetting ps = (PackageSetting) obj;
2812                return new String[] { ps.name };
2813            }
2814        }
2815        return null;
2816    }
2817
2818    @Override
2819    public String getNameForUid(int uid) {
2820        // reader
2821        synchronized (mPackages) {
2822            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2823            if (obj instanceof SharedUserSetting) {
2824                final SharedUserSetting sus = (SharedUserSetting) obj;
2825                return sus.name + ":" + sus.userId;
2826            } else if (obj instanceof PackageSetting) {
2827                final PackageSetting ps = (PackageSetting) obj;
2828                return ps.name;
2829            }
2830        }
2831        return null;
2832    }
2833
2834    @Override
2835    public int getUidForSharedUser(String sharedUserName) {
2836        if(sharedUserName == null) {
2837            return -1;
2838        }
2839        // reader
2840        synchronized (mPackages) {
2841            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2842            if (suid == null) {
2843                return -1;
2844            }
2845            return suid.userId;
2846        }
2847    }
2848
2849    @Override
2850    public int getFlagsForUid(int uid) {
2851        synchronized (mPackages) {
2852            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2853            if (obj instanceof SharedUserSetting) {
2854                final SharedUserSetting sus = (SharedUserSetting) obj;
2855                return sus.pkgFlags;
2856            } else if (obj instanceof PackageSetting) {
2857                final PackageSetting ps = (PackageSetting) obj;
2858                return ps.pkgFlags;
2859            }
2860        }
2861        return 0;
2862    }
2863
2864    @Override
2865    public String[] getAppOpPermissionPackages(String permissionName) {
2866        synchronized (mPackages) {
2867            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2868            if (pkgs == null) {
2869                return null;
2870            }
2871            return pkgs.toArray(new String[pkgs.size()]);
2872        }
2873    }
2874
2875    @Override
2876    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2877            int flags, int userId) {
2878        if (!sUserManager.exists(userId)) return null;
2879        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2880        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2881        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2882    }
2883
2884    @Override
2885    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2886            IntentFilter filter, int match, ComponentName activity) {
2887        final int userId = UserHandle.getCallingUserId();
2888        if (DEBUG_PREFERRED) {
2889            Log.v(TAG, "setLastChosenActivity intent=" + intent
2890                + " resolvedType=" + resolvedType
2891                + " flags=" + flags
2892                + " filter=" + filter
2893                + " match=" + match
2894                + " activity=" + activity);
2895            filter.dump(new PrintStreamPrinter(System.out), "    ");
2896        }
2897        intent.setComponent(null);
2898        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2899        // Find any earlier preferred or last chosen entries and nuke them
2900        findPreferredActivity(intent, resolvedType,
2901                flags, query, 0, false, true, false, userId);
2902        // Add the new activity as the last chosen for this filter
2903        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2904                "Setting last chosen");
2905    }
2906
2907    @Override
2908    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2909        final int userId = UserHandle.getCallingUserId();
2910        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2911        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2912        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2913                false, false, false, userId);
2914    }
2915
2916    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2917            int flags, List<ResolveInfo> query, int userId) {
2918        if (query != null) {
2919            final int N = query.size();
2920            if (N == 1) {
2921                return query.get(0);
2922            } else if (N > 1) {
2923                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2924                // If there is more than one activity with the same priority,
2925                // then let the user decide between them.
2926                ResolveInfo r0 = query.get(0);
2927                ResolveInfo r1 = query.get(1);
2928                if (DEBUG_INTENT_MATCHING || debug) {
2929                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2930                            + r1.activityInfo.name + "=" + r1.priority);
2931                }
2932                // If the first activity has a higher priority, or a different
2933                // default, then it is always desireable to pick it.
2934                if (r0.priority != r1.priority
2935                        || r0.preferredOrder != r1.preferredOrder
2936                        || r0.isDefault != r1.isDefault) {
2937                    return query.get(0);
2938                }
2939                // If we have saved a preference for a preferred activity for
2940                // this Intent, use that.
2941                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2942                        flags, query, r0.priority, true, false, debug, userId);
2943                if (ri != null) {
2944                    return ri;
2945                }
2946                if (userId != 0) {
2947                    ri = new ResolveInfo(mResolveInfo);
2948                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2949                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2950                            ri.activityInfo.applicationInfo);
2951                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2952                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2953                    return ri;
2954                }
2955                return mResolveInfo;
2956            }
2957        }
2958        return null;
2959    }
2960
2961    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2962            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2963        final int N = query.size();
2964        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2965                .get(userId);
2966        // Get the list of persistent preferred activities that handle the intent
2967        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2968        List<PersistentPreferredActivity> pprefs = ppir != null
2969                ? ppir.queryIntent(intent, resolvedType,
2970                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2971                : null;
2972        if (pprefs != null && pprefs.size() > 0) {
2973            final int M = pprefs.size();
2974            for (int i=0; i<M; i++) {
2975                final PersistentPreferredActivity ppa = pprefs.get(i);
2976                if (DEBUG_PREFERRED || debug) {
2977                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2978                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2979                            + "\n  component=" + ppa.mComponent);
2980                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2981                }
2982                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
2983                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
2984                if (DEBUG_PREFERRED || debug) {
2985                    Slog.v(TAG, "Found persistent preferred activity:");
2986                    if (ai != null) {
2987                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2988                    } else {
2989                        Slog.v(TAG, "  null");
2990                    }
2991                }
2992                if (ai == null) {
2993                    // This previously registered persistent preferred activity
2994                    // component is no longer known. Ignore it and do NOT remove it.
2995                    continue;
2996                }
2997                for (int j=0; j<N; j++) {
2998                    final ResolveInfo ri = query.get(j);
2999                    if (!ri.activityInfo.applicationInfo.packageName
3000                            .equals(ai.applicationInfo.packageName)) {
3001                        continue;
3002                    }
3003                    if (!ri.activityInfo.name.equals(ai.name)) {
3004                        continue;
3005                    }
3006                    //  Found a persistent preference that can handle the intent.
3007                    if (DEBUG_PREFERRED || debug) {
3008                        Slog.v(TAG, "Returning persistent preferred activity: " +
3009                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3010                    }
3011                    return ri;
3012                }
3013            }
3014        }
3015        return null;
3016    }
3017
3018    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3019            List<ResolveInfo> query, int priority, boolean always,
3020            boolean removeMatches, boolean debug, int userId) {
3021        if (!sUserManager.exists(userId)) return null;
3022        // writer
3023        synchronized (mPackages) {
3024            if (intent.getSelector() != null) {
3025                intent = intent.getSelector();
3026            }
3027            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3028
3029            // Try to find a matching persistent preferred activity.
3030            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3031                    debug, userId);
3032
3033            // If a persistent preferred activity matched, use it.
3034            if (pri != null) {
3035                return pri;
3036            }
3037
3038            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3039            // Get the list of preferred activities that handle the intent
3040            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3041            List<PreferredActivity> prefs = pir != null
3042                    ? pir.queryIntent(intent, resolvedType,
3043                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3044                    : null;
3045            if (prefs != null && prefs.size() > 0) {
3046                boolean changed = false;
3047                try {
3048                    // First figure out how good the original match set is.
3049                    // We will only allow preferred activities that came
3050                    // from the same match quality.
3051                    int match = 0;
3052
3053                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3054
3055                    final int N = query.size();
3056                    for (int j=0; j<N; j++) {
3057                        final ResolveInfo ri = query.get(j);
3058                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3059                                + ": 0x" + Integer.toHexString(match));
3060                        if (ri.match > match) {
3061                            match = ri.match;
3062                        }
3063                    }
3064
3065                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3066                            + Integer.toHexString(match));
3067
3068                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3069                    final int M = prefs.size();
3070                    for (int i=0; i<M; i++) {
3071                        final PreferredActivity pa = prefs.get(i);
3072                        if (DEBUG_PREFERRED || debug) {
3073                            Slog.v(TAG, "Checking PreferredActivity ds="
3074                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3075                                    + "\n  component=" + pa.mPref.mComponent);
3076                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3077                        }
3078                        if (pa.mPref.mMatch != match) {
3079                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3080                                    + Integer.toHexString(pa.mPref.mMatch));
3081                            continue;
3082                        }
3083                        // If it's not an "always" type preferred activity and that's what we're
3084                        // looking for, skip it.
3085                        if (always && !pa.mPref.mAlways) {
3086                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3087                            continue;
3088                        }
3089                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3090                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3091                        if (DEBUG_PREFERRED || debug) {
3092                            Slog.v(TAG, "Found preferred activity:");
3093                            if (ai != null) {
3094                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3095                            } else {
3096                                Slog.v(TAG, "  null");
3097                            }
3098                        }
3099                        if (ai == null) {
3100                            // This previously registered preferred activity
3101                            // component is no longer known.  Most likely an update
3102                            // to the app was installed and in the new version this
3103                            // component no longer exists.  Clean it up by removing
3104                            // it from the preferred activities list, and skip it.
3105                            Slog.w(TAG, "Removing dangling preferred activity: "
3106                                    + pa.mPref.mComponent);
3107                            pir.removeFilter(pa);
3108                            changed = true;
3109                            continue;
3110                        }
3111                        for (int j=0; j<N; j++) {
3112                            final ResolveInfo ri = query.get(j);
3113                            if (!ri.activityInfo.applicationInfo.packageName
3114                                    .equals(ai.applicationInfo.packageName)) {
3115                                continue;
3116                            }
3117                            if (!ri.activityInfo.name.equals(ai.name)) {
3118                                continue;
3119                            }
3120
3121                            if (removeMatches) {
3122                                pir.removeFilter(pa);
3123                                changed = true;
3124                                if (DEBUG_PREFERRED) {
3125                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3126                                }
3127                                break;
3128                            }
3129
3130                            // Okay we found a previously set preferred or last chosen app.
3131                            // If the result set is different from when this
3132                            // was created, we need to clear it and re-ask the
3133                            // user their preference, if we're looking for an "always" type entry.
3134                            if (always && !pa.mPref.sameSet(query, priority)) {
3135                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3136                                        + intent + " type " + resolvedType);
3137                                if (DEBUG_PREFERRED) {
3138                                    Slog.v(TAG, "Removing preferred activity since set changed "
3139                                            + pa.mPref.mComponent);
3140                                }
3141                                pir.removeFilter(pa);
3142                                // Re-add the filter as a "last chosen" entry (!always)
3143                                PreferredActivity lastChosen = new PreferredActivity(
3144                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3145                                pir.addFilter(lastChosen);
3146                                changed = true;
3147                                return null;
3148                            }
3149
3150                            // Yay! Either the set matched or we're looking for the last chosen
3151                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3152                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3153                            return ri;
3154                        }
3155                    }
3156                } finally {
3157                    if (changed) {
3158                        if (DEBUG_PREFERRED) {
3159                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3160                        }
3161                        mSettings.writePackageRestrictionsLPr(userId);
3162                    }
3163                }
3164            }
3165        }
3166        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3167        return null;
3168    }
3169
3170    /*
3171     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3172     */
3173    @Override
3174    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3175            int targetUserId) {
3176        mContext.enforceCallingOrSelfPermission(
3177                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3178        List<CrossProfileIntentFilter> matches =
3179                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3180        if (matches != null) {
3181            int size = matches.size();
3182            for (int i = 0; i < size; i++) {
3183                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3184            }
3185        }
3186        ArrayList<String> packageNames = null;
3187        SparseArray<ArrayList<String>> fromSource =
3188                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3189        if (fromSource != null) {
3190            packageNames = fromSource.get(targetUserId);
3191            if (packageNames != null) {
3192                // We need the package name, so we try to resolve with the loosest flags possible
3193                List<ResolveInfo> resolveInfos = mActivities.queryIntent(intent, resolvedType,
3194                        PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3195                int count = resolveInfos.size();
3196                for (int i = 0; i < count; i++) {
3197                    ResolveInfo resolveInfo = resolveInfos.get(i);
3198                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3199                        return true;
3200                    }
3201                }
3202            }
3203        }
3204        return false;
3205    }
3206
3207    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3208            String resolvedType, int userId) {
3209        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3210        if (resolver != null) {
3211            return resolver.queryIntent(intent, resolvedType, false, userId);
3212        }
3213        return null;
3214    }
3215
3216    @Override
3217    public List<ResolveInfo> queryIntentActivities(Intent intent,
3218            String resolvedType, int flags, int userId) {
3219        if (!sUserManager.exists(userId)) return Collections.emptyList();
3220        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3221        ComponentName comp = intent.getComponent();
3222        if (comp == null) {
3223            if (intent.getSelector() != null) {
3224                intent = intent.getSelector();
3225                comp = intent.getComponent();
3226            }
3227        }
3228
3229        if (comp != null) {
3230            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3231            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3232            if (ai != null) {
3233                final ResolveInfo ri = new ResolveInfo();
3234                ri.activityInfo = ai;
3235                list.add(ri);
3236            }
3237            return list;
3238        }
3239
3240        // reader
3241        synchronized (mPackages) {
3242            final String pkgName = intent.getPackage();
3243            if (pkgName == null) {
3244                ResolveInfo resolveInfo = null;
3245
3246                // Check if the intent needs to be forwarded to another user for this package
3247                ArrayList<ResolveInfo> crossProfileResult =
3248                        queryIntentActivitiesCrossProfilePackage(
3249                                intent, resolvedType, flags, userId);
3250                if (!crossProfileResult.isEmpty()) {
3251                    // Skip the current profile
3252                    return crossProfileResult;
3253                }
3254                List<CrossProfileIntentFilter> matchingFilters =
3255                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3256                // Check for results that need to skip the current profile.
3257                resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3258                        resolvedType, flags, userId);
3259                if (resolveInfo != null) {
3260                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3261                    result.add(resolveInfo);
3262                    return result;
3263                }
3264                // Check for cross profile results.
3265                resolveInfo = queryCrossProfileIntents(
3266                        matchingFilters, intent, resolvedType, flags, userId);
3267
3268                // Check for results in the current profile.
3269                List<ResolveInfo> result = mActivities.queryIntent(
3270                        intent, resolvedType, flags, userId);
3271                if (resolveInfo != null) {
3272                    result.add(resolveInfo);
3273                    Collections.sort(result, mResolvePrioritySorter);
3274                }
3275                return result;
3276            }
3277            final PackageParser.Package pkg = mPackages.get(pkgName);
3278            if (pkg != null) {
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                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3287                        pkg.activities, userId);
3288            }
3289            return new ArrayList<ResolveInfo>();
3290        }
3291    }
3292
3293    private ResolveInfo querySkipCurrentProfileIntents(
3294            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3295            int flags, int sourceUserId) {
3296        if (matchingFilters != null) {
3297            int size = matchingFilters.size();
3298            for (int i = 0; i < size; i ++) {
3299                CrossProfileIntentFilter filter = matchingFilters.get(i);
3300                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3301                    // Checking if there are activities in the target user that can handle the
3302                    // intent.
3303                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3304                            flags, sourceUserId);
3305                    if (resolveInfo != null) {
3306                        return resolveInfo;
3307                    }
3308                }
3309            }
3310        }
3311        return null;
3312    }
3313
3314    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3315            Intent intent, String resolvedType, int flags, int userId) {
3316        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3317        SparseArray<ArrayList<String>> sourceForwardingInfo =
3318                mSettings.mCrossProfilePackageInfo.get(userId);
3319        if (sourceForwardingInfo != null) {
3320            int NI = sourceForwardingInfo.size();
3321            for (int i = 0; i < NI; i++) {
3322                int targetUserId = sourceForwardingInfo.keyAt(i);
3323                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3324                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3325                        intent, resolvedType, flags, targetUserId);
3326                int NJ = resolveInfos.size();
3327                for (int j = 0; j < NJ; j++) {
3328                    ResolveInfo resolveInfo = resolveInfos.get(j);
3329                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3330                        matchingResolveInfos.add(createForwardingResolveInfo(
3331                                resolveInfo.filter, userId, targetUserId));
3332                    }
3333                }
3334            }
3335        }
3336        return matchingResolveInfos;
3337    }
3338
3339    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3340            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3341            String packageName) {
3342        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3343        SparseArray<ArrayList<String>> sourceForwardingInfo =
3344                mSettings.mCrossProfilePackageInfo.get(userId);
3345        if (sourceForwardingInfo != null) {
3346            int NI = sourceForwardingInfo.size();
3347            for (int i = 0; i < NI; i++) {
3348                int targetUserId = sourceForwardingInfo.keyAt(i);
3349                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3350                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3351                            intent, resolvedType, flags, pkg.activities, targetUserId);
3352                    int NJ = resolveInfos.size();
3353                    for (int j = 0; j < NJ; j++) {
3354                        ResolveInfo resolveInfo = resolveInfos.get(j);
3355                        matchingResolveInfos.add(createForwardingResolveInfo(
3356                                resolveInfo.filter, userId, targetUserId));
3357                    }
3358                }
3359            }
3360        }
3361        return matchingResolveInfos;
3362    }
3363
3364    // Return matching ResolveInfo if any for skip current profile intent filters.
3365    private ResolveInfo queryCrossProfileIntents(
3366            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3367            int flags, int sourceUserId) {
3368        if (matchingFilters != null) {
3369            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3370            // match the same intent. For performance reasons, it is better not to
3371            // run queryIntent twice for the same userId
3372            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3373            int size = matchingFilters.size();
3374            for (int i = 0; i < size; i++) {
3375                CrossProfileIntentFilter filter = matchingFilters.get(i);
3376                int targetUserId = filter.getTargetUserId();
3377                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3378                        && !alreadyTriedUserIds.get(targetUserId)) {
3379                    // Checking if there are activities in the target user that can handle the
3380                    // intent.
3381                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3382                            flags, sourceUserId);
3383                    if (resolveInfo != null) return resolveInfo;
3384                    alreadyTriedUserIds.put(targetUserId, true);
3385                }
3386            }
3387        }
3388        return null;
3389    }
3390
3391    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3392            String resolvedType, int flags, int sourceUserId) {
3393        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3394                resolvedType, flags, filter.getTargetUserId());
3395        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3396            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3397        }
3398        return null;
3399    }
3400
3401    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3402            int sourceUserId, int targetUserId) {
3403        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3404        String className;
3405        if (targetUserId == UserHandle.USER_OWNER) {
3406            className = FORWARD_INTENT_TO_USER_OWNER;
3407        } else {
3408            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3409        }
3410        ComponentName forwardingActivityComponentName = new ComponentName(
3411                mAndroidApplication.packageName, className);
3412        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3413                sourceUserId);
3414        if (targetUserId == UserHandle.USER_OWNER) {
3415            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3416            forwardingResolveInfo.noResourceId = true;
3417        }
3418        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3419        forwardingResolveInfo.priority = 0;
3420        forwardingResolveInfo.preferredOrder = 0;
3421        forwardingResolveInfo.match = 0;
3422        forwardingResolveInfo.isDefault = true;
3423        forwardingResolveInfo.filter = filter;
3424        forwardingResolveInfo.targetUserId = targetUserId;
3425        return forwardingResolveInfo;
3426    }
3427
3428    @Override
3429    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3430            Intent[] specifics, String[] specificTypes, Intent intent,
3431            String resolvedType, int flags, int userId) {
3432        if (!sUserManager.exists(userId)) return Collections.emptyList();
3433        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3434                "query intent activity options");
3435        final String resultsAction = intent.getAction();
3436
3437        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3438                | PackageManager.GET_RESOLVED_FILTER, userId);
3439
3440        if (DEBUG_INTENT_MATCHING) {
3441            Log.v(TAG, "Query " + intent + ": " + results);
3442        }
3443
3444        int specificsPos = 0;
3445        int N;
3446
3447        // todo: note that the algorithm used here is O(N^2).  This
3448        // isn't a problem in our current environment, but if we start running
3449        // into situations where we have more than 5 or 10 matches then this
3450        // should probably be changed to something smarter...
3451
3452        // First we go through and resolve each of the specific items
3453        // that were supplied, taking care of removing any corresponding
3454        // duplicate items in the generic resolve list.
3455        if (specifics != null) {
3456            for (int i=0; i<specifics.length; i++) {
3457                final Intent sintent = specifics[i];
3458                if (sintent == null) {
3459                    continue;
3460                }
3461
3462                if (DEBUG_INTENT_MATCHING) {
3463                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3464                }
3465
3466                String action = sintent.getAction();
3467                if (resultsAction != null && resultsAction.equals(action)) {
3468                    // If this action was explicitly requested, then don't
3469                    // remove things that have it.
3470                    action = null;
3471                }
3472
3473                ResolveInfo ri = null;
3474                ActivityInfo ai = null;
3475
3476                ComponentName comp = sintent.getComponent();
3477                if (comp == null) {
3478                    ri = resolveIntent(
3479                        sintent,
3480                        specificTypes != null ? specificTypes[i] : null,
3481                            flags, userId);
3482                    if (ri == null) {
3483                        continue;
3484                    }
3485                    if (ri == mResolveInfo) {
3486                        // ACK!  Must do something better with this.
3487                    }
3488                    ai = ri.activityInfo;
3489                    comp = new ComponentName(ai.applicationInfo.packageName,
3490                            ai.name);
3491                } else {
3492                    ai = getActivityInfo(comp, flags, userId);
3493                    if (ai == null) {
3494                        continue;
3495                    }
3496                }
3497
3498                // Look for any generic query activities that are duplicates
3499                // of this specific one, and remove them from the results.
3500                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3501                N = results.size();
3502                int j;
3503                for (j=specificsPos; j<N; j++) {
3504                    ResolveInfo sri = results.get(j);
3505                    if ((sri.activityInfo.name.equals(comp.getClassName())
3506                            && sri.activityInfo.applicationInfo.packageName.equals(
3507                                    comp.getPackageName()))
3508                        || (action != null && sri.filter.matchAction(action))) {
3509                        results.remove(j);
3510                        if (DEBUG_INTENT_MATCHING) Log.v(
3511                            TAG, "Removing duplicate item from " + j
3512                            + " due to specific " + specificsPos);
3513                        if (ri == null) {
3514                            ri = sri;
3515                        }
3516                        j--;
3517                        N--;
3518                    }
3519                }
3520
3521                // Add this specific item to its proper place.
3522                if (ri == null) {
3523                    ri = new ResolveInfo();
3524                    ri.activityInfo = ai;
3525                }
3526                results.add(specificsPos, ri);
3527                ri.specificIndex = i;
3528                specificsPos++;
3529            }
3530        }
3531
3532        // Now we go through the remaining generic results and remove any
3533        // duplicate actions that are found here.
3534        N = results.size();
3535        for (int i=specificsPos; i<N-1; i++) {
3536            final ResolveInfo rii = results.get(i);
3537            if (rii.filter == null) {
3538                continue;
3539            }
3540
3541            // Iterate over all of the actions of this result's intent
3542            // filter...  typically this should be just one.
3543            final Iterator<String> it = rii.filter.actionsIterator();
3544            if (it == null) {
3545                continue;
3546            }
3547            while (it.hasNext()) {
3548                final String action = it.next();
3549                if (resultsAction != null && resultsAction.equals(action)) {
3550                    // If this action was explicitly requested, then don't
3551                    // remove things that have it.
3552                    continue;
3553                }
3554                for (int j=i+1; j<N; j++) {
3555                    final ResolveInfo rij = results.get(j);
3556                    if (rij.filter != null && rij.filter.hasAction(action)) {
3557                        results.remove(j);
3558                        if (DEBUG_INTENT_MATCHING) Log.v(
3559                            TAG, "Removing duplicate item from " + j
3560                            + " due to action " + action + " at " + i);
3561                        j--;
3562                        N--;
3563                    }
3564                }
3565            }
3566
3567            // If the caller didn't request filter information, drop it now
3568            // so we don't have to marshall/unmarshall it.
3569            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3570                rii.filter = null;
3571            }
3572        }
3573
3574        // Filter out the caller activity if so requested.
3575        if (caller != null) {
3576            N = results.size();
3577            for (int i=0; i<N; i++) {
3578                ActivityInfo ainfo = results.get(i).activityInfo;
3579                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3580                        && caller.getClassName().equals(ainfo.name)) {
3581                    results.remove(i);
3582                    break;
3583                }
3584            }
3585        }
3586
3587        // If the caller didn't request filter information,
3588        // drop them now so we don't have to
3589        // marshall/unmarshall it.
3590        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3591            N = results.size();
3592            for (int i=0; i<N; i++) {
3593                results.get(i).filter = null;
3594            }
3595        }
3596
3597        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3598        return results;
3599    }
3600
3601    @Override
3602    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3603            int userId) {
3604        if (!sUserManager.exists(userId)) return Collections.emptyList();
3605        ComponentName comp = intent.getComponent();
3606        if (comp == null) {
3607            if (intent.getSelector() != null) {
3608                intent = intent.getSelector();
3609                comp = intent.getComponent();
3610            }
3611        }
3612        if (comp != null) {
3613            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3614            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3615            if (ai != null) {
3616                ResolveInfo ri = new ResolveInfo();
3617                ri.activityInfo = ai;
3618                list.add(ri);
3619            }
3620            return list;
3621        }
3622
3623        // reader
3624        synchronized (mPackages) {
3625            String pkgName = intent.getPackage();
3626            if (pkgName == null) {
3627                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3628            }
3629            final PackageParser.Package pkg = mPackages.get(pkgName);
3630            if (pkg != null) {
3631                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3632                        userId);
3633            }
3634            return null;
3635        }
3636    }
3637
3638    @Override
3639    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3640        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3641        if (!sUserManager.exists(userId)) return null;
3642        if (query != null) {
3643            if (query.size() >= 1) {
3644                // If there is more than one service with the same priority,
3645                // just arbitrarily pick the first one.
3646                return query.get(0);
3647            }
3648        }
3649        return null;
3650    }
3651
3652    @Override
3653    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3654            int userId) {
3655        if (!sUserManager.exists(userId)) return Collections.emptyList();
3656        ComponentName comp = intent.getComponent();
3657        if (comp == null) {
3658            if (intent.getSelector() != null) {
3659                intent = intent.getSelector();
3660                comp = intent.getComponent();
3661            }
3662        }
3663        if (comp != null) {
3664            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3665            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3666            if (si != null) {
3667                final ResolveInfo ri = new ResolveInfo();
3668                ri.serviceInfo = si;
3669                list.add(ri);
3670            }
3671            return list;
3672        }
3673
3674        // reader
3675        synchronized (mPackages) {
3676            String pkgName = intent.getPackage();
3677            if (pkgName == null) {
3678                return mServices.queryIntent(intent, resolvedType, flags, userId);
3679            }
3680            final PackageParser.Package pkg = mPackages.get(pkgName);
3681            if (pkg != null) {
3682                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3683                        userId);
3684            }
3685            return null;
3686        }
3687    }
3688
3689    @Override
3690    public List<ResolveInfo> queryIntentContentProviders(
3691            Intent intent, String resolvedType, int flags, int userId) {
3692        if (!sUserManager.exists(userId)) return Collections.emptyList();
3693        ComponentName comp = intent.getComponent();
3694        if (comp == null) {
3695            if (intent.getSelector() != null) {
3696                intent = intent.getSelector();
3697                comp = intent.getComponent();
3698            }
3699        }
3700        if (comp != null) {
3701            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3702            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3703            if (pi != null) {
3704                final ResolveInfo ri = new ResolveInfo();
3705                ri.providerInfo = pi;
3706                list.add(ri);
3707            }
3708            return list;
3709        }
3710
3711        // reader
3712        synchronized (mPackages) {
3713            String pkgName = intent.getPackage();
3714            if (pkgName == null) {
3715                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3716            }
3717            final PackageParser.Package pkg = mPackages.get(pkgName);
3718            if (pkg != null) {
3719                return mProviders.queryIntentForPackage(
3720                        intent, resolvedType, flags, pkg.providers, userId);
3721            }
3722            return null;
3723        }
3724    }
3725
3726    @Override
3727    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3728        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3729
3730        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3731
3732        // writer
3733        synchronized (mPackages) {
3734            ArrayList<PackageInfo> list;
3735            if (listUninstalled) {
3736                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3737                for (PackageSetting ps : mSettings.mPackages.values()) {
3738                    PackageInfo pi;
3739                    if (ps.pkg != null) {
3740                        pi = generatePackageInfo(ps.pkg, flags, userId);
3741                    } else {
3742                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3743                    }
3744                    if (pi != null) {
3745                        list.add(pi);
3746                    }
3747                }
3748            } else {
3749                list = new ArrayList<PackageInfo>(mPackages.size());
3750                for (PackageParser.Package p : mPackages.values()) {
3751                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3752                    if (pi != null) {
3753                        list.add(pi);
3754                    }
3755                }
3756            }
3757
3758            return new ParceledListSlice<PackageInfo>(list);
3759        }
3760    }
3761
3762    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3763            String[] permissions, boolean[] tmp, int flags, int userId) {
3764        int numMatch = 0;
3765        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3766        for (int i=0; i<permissions.length; i++) {
3767            if (gp.grantedPermissions.contains(permissions[i])) {
3768                tmp[i] = true;
3769                numMatch++;
3770            } else {
3771                tmp[i] = false;
3772            }
3773        }
3774        if (numMatch == 0) {
3775            return;
3776        }
3777        PackageInfo pi;
3778        if (ps.pkg != null) {
3779            pi = generatePackageInfo(ps.pkg, flags, userId);
3780        } else {
3781            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3782        }
3783        // The above might return null in cases of uninstalled apps or install-state
3784        // skew across users/profiles.
3785        if (pi != null) {
3786            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3787                if (numMatch == permissions.length) {
3788                    pi.requestedPermissions = permissions;
3789                } else {
3790                    pi.requestedPermissions = new String[numMatch];
3791                    numMatch = 0;
3792                    for (int i=0; i<permissions.length; i++) {
3793                        if (tmp[i]) {
3794                            pi.requestedPermissions[numMatch] = permissions[i];
3795                            numMatch++;
3796                        }
3797                    }
3798                }
3799            }
3800            list.add(pi);
3801        }
3802    }
3803
3804    @Override
3805    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3806            String[] permissions, int flags, int userId) {
3807        if (!sUserManager.exists(userId)) return null;
3808        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3809
3810        // writer
3811        synchronized (mPackages) {
3812            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3813            boolean[] tmpBools = new boolean[permissions.length];
3814            if (listUninstalled) {
3815                for (PackageSetting ps : mSettings.mPackages.values()) {
3816                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3817                }
3818            } else {
3819                for (PackageParser.Package pkg : mPackages.values()) {
3820                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3821                    if (ps != null) {
3822                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3823                                userId);
3824                    }
3825                }
3826            }
3827
3828            return new ParceledListSlice<PackageInfo>(list);
3829        }
3830    }
3831
3832    @Override
3833    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3834        if (!sUserManager.exists(userId)) return null;
3835        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3836
3837        // writer
3838        synchronized (mPackages) {
3839            ArrayList<ApplicationInfo> list;
3840            if (listUninstalled) {
3841                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3842                for (PackageSetting ps : mSettings.mPackages.values()) {
3843                    ApplicationInfo ai;
3844                    if (ps.pkg != null) {
3845                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3846                                ps.readUserState(userId), userId);
3847                    } else {
3848                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3849                    }
3850                    if (ai != null) {
3851                        list.add(ai);
3852                    }
3853                }
3854            } else {
3855                list = new ArrayList<ApplicationInfo>(mPackages.size());
3856                for (PackageParser.Package p : mPackages.values()) {
3857                    if (p.mExtras != null) {
3858                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3859                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3860                        if (ai != null) {
3861                            list.add(ai);
3862                        }
3863                    }
3864                }
3865            }
3866
3867            return new ParceledListSlice<ApplicationInfo>(list);
3868        }
3869    }
3870
3871    public List<ApplicationInfo> getPersistentApplications(int flags) {
3872        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3873
3874        // reader
3875        synchronized (mPackages) {
3876            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3877            final int userId = UserHandle.getCallingUserId();
3878            while (i.hasNext()) {
3879                final PackageParser.Package p = i.next();
3880                if (p.applicationInfo != null
3881                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3882                        && (!mSafeMode || isSystemApp(p))) {
3883                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3884                    if (ps != null) {
3885                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3886                                ps.readUserState(userId), userId);
3887                        if (ai != null) {
3888                            finalList.add(ai);
3889                        }
3890                    }
3891                }
3892            }
3893        }
3894
3895        return finalList;
3896    }
3897
3898    @Override
3899    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3900        if (!sUserManager.exists(userId)) return null;
3901        // reader
3902        synchronized (mPackages) {
3903            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3904            PackageSetting ps = provider != null
3905                    ? mSettings.mPackages.get(provider.owner.packageName)
3906                    : null;
3907            return ps != null
3908                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3909                    && (!mSafeMode || (provider.info.applicationInfo.flags
3910                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3911                    ? PackageParser.generateProviderInfo(provider, flags,
3912                            ps.readUserState(userId), userId)
3913                    : null;
3914        }
3915    }
3916
3917    /**
3918     * @deprecated
3919     */
3920    @Deprecated
3921    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3922        // reader
3923        synchronized (mPackages) {
3924            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3925                    .entrySet().iterator();
3926            final int userId = UserHandle.getCallingUserId();
3927            while (i.hasNext()) {
3928                Map.Entry<String, PackageParser.Provider> entry = i.next();
3929                PackageParser.Provider p = entry.getValue();
3930                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3931
3932                if (ps != null && p.syncable
3933                        && (!mSafeMode || (p.info.applicationInfo.flags
3934                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3935                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3936                            ps.readUserState(userId), userId);
3937                    if (info != null) {
3938                        outNames.add(entry.getKey());
3939                        outInfo.add(info);
3940                    }
3941                }
3942            }
3943        }
3944    }
3945
3946    @Override
3947    public List<ProviderInfo> queryContentProviders(String processName,
3948            int uid, int flags) {
3949        ArrayList<ProviderInfo> finalList = null;
3950        // reader
3951        synchronized (mPackages) {
3952            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3953            final int userId = processName != null ?
3954                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3955            while (i.hasNext()) {
3956                final PackageParser.Provider p = i.next();
3957                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3958                if (ps != null && p.info.authority != null
3959                        && (processName == null
3960                                || (p.info.processName.equals(processName)
3961                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3962                        && mSettings.isEnabledLPr(p.info, flags, userId)
3963                        && (!mSafeMode
3964                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3965                    if (finalList == null) {
3966                        finalList = new ArrayList<ProviderInfo>(3);
3967                    }
3968                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3969                            ps.readUserState(userId), userId);
3970                    if (info != null) {
3971                        finalList.add(info);
3972                    }
3973                }
3974            }
3975        }
3976
3977        if (finalList != null) {
3978            Collections.sort(finalList, mProviderInitOrderSorter);
3979        }
3980
3981        return finalList;
3982    }
3983
3984    @Override
3985    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3986            int flags) {
3987        // reader
3988        synchronized (mPackages) {
3989            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3990            return PackageParser.generateInstrumentationInfo(i, flags);
3991        }
3992    }
3993
3994    @Override
3995    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3996            int flags) {
3997        ArrayList<InstrumentationInfo> finalList =
3998            new ArrayList<InstrumentationInfo>();
3999
4000        // reader
4001        synchronized (mPackages) {
4002            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4003            while (i.hasNext()) {
4004                final PackageParser.Instrumentation p = i.next();
4005                if (targetPackage == null
4006                        || targetPackage.equals(p.info.targetPackage)) {
4007                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4008                            flags);
4009                    if (ii != null) {
4010                        finalList.add(ii);
4011                    }
4012                }
4013            }
4014        }
4015
4016        return finalList;
4017    }
4018
4019    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4020        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4021        if (overlays == null) {
4022            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4023            return;
4024        }
4025        for (PackageParser.Package opkg : overlays.values()) {
4026            // Not much to do if idmap fails: we already logged the error
4027            // and we certainly don't want to abort installation of pkg simply
4028            // because an overlay didn't fit properly. For these reasons,
4029            // ignore the return value of createIdmapForPackagePairLI.
4030            createIdmapForPackagePairLI(pkg, opkg);
4031        }
4032    }
4033
4034    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4035            PackageParser.Package opkg) {
4036        if (!opkg.mTrustedOverlay) {
4037            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4038                    opkg.baseCodePath + ": overlay not trusted");
4039            return false;
4040        }
4041        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4042        if (overlaySet == null) {
4043            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4044                    opkg.baseCodePath + " but target package has no known overlays");
4045            return false;
4046        }
4047        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4048        // TODO: generate idmap for split APKs
4049        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4050            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4051                    + opkg.baseCodePath);
4052            return false;
4053        }
4054        PackageParser.Package[] overlayArray =
4055            overlaySet.values().toArray(new PackageParser.Package[0]);
4056        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4057            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4058                return p1.mOverlayPriority - p2.mOverlayPriority;
4059            }
4060        };
4061        Arrays.sort(overlayArray, cmp);
4062
4063        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4064        int i = 0;
4065        for (PackageParser.Package p : overlayArray) {
4066            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4067        }
4068        return true;
4069    }
4070
4071    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4072        final File[] files = dir.listFiles();
4073        if (ArrayUtils.isEmpty(files)) {
4074            Log.d(TAG, "No files in app dir " + dir);
4075            return;
4076        }
4077
4078        if (DEBUG_PACKAGE_SCANNING) {
4079            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4080                    + " flags=0x" + Integer.toHexString(parseFlags));
4081        }
4082
4083        for (File file : files) {
4084            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4085                    && !PackageInstallerService.isStageName(file.getName());
4086            if (!isPackage) {
4087                // Ignore entries which are not packages
4088                continue;
4089            }
4090            try {
4091                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4092                        scanFlags, currentTime, null);
4093            } catch (PackageManagerException e) {
4094                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4095
4096                // Delete invalid userdata apps
4097                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4098                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4099                    Slog.w(TAG, "Deleting invalid package at " + file);
4100                    if (file.isDirectory()) {
4101                        FileUtils.deleteContents(file);
4102                    }
4103                    file.delete();
4104                }
4105            }
4106        }
4107    }
4108
4109    private static File getSettingsProblemFile() {
4110        File dataDir = Environment.getDataDirectory();
4111        File systemDir = new File(dataDir, "system");
4112        File fname = new File(systemDir, "uiderrors.txt");
4113        return fname;
4114    }
4115
4116    static void reportSettingsProblem(int priority, String msg) {
4117        try {
4118            File fname = getSettingsProblemFile();
4119            FileOutputStream out = new FileOutputStream(fname, true);
4120            PrintWriter pw = new FastPrintWriter(out);
4121            SimpleDateFormat formatter = new SimpleDateFormat();
4122            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4123            pw.println(dateString + ": " + msg);
4124            pw.close();
4125            FileUtils.setPermissions(
4126                    fname.toString(),
4127                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4128                    -1, -1);
4129        } catch (java.io.IOException e) {
4130        }
4131        Slog.println(priority, TAG, msg);
4132    }
4133
4134    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4135            PackageParser.Package pkg, File srcFile, int parseFlags)
4136            throws PackageManagerException {
4137        if (ps != null
4138                && ps.codePath.equals(srcFile)
4139                && ps.timeStamp == srcFile.lastModified()
4140                && !isCompatSignatureUpdateNeeded(pkg)) {
4141            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4142            if (ps.signatures.mSignatures != null
4143                    && ps.signatures.mSignatures.length != 0
4144                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4145                // Optimization: reuse the existing cached certificates
4146                // if the package appears to be unchanged.
4147                pkg.mSignatures = ps.signatures.mSignatures;
4148                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4149                synchronized (mPackages) {
4150                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4151                }
4152                return;
4153            }
4154
4155            Slog.w(TAG, "PackageSetting for " + ps.name
4156                    + " is missing signatures.  Collecting certs again to recover them.");
4157        } else {
4158            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4159        }
4160
4161        try {
4162            pp.collectCertificates(pkg, parseFlags);
4163            pp.collectManifestDigest(pkg);
4164        } catch (PackageParserException e) {
4165            throw new PackageManagerException(e.error, "Failed to collect certificates for "
4166                    + pkg.packageName + ": " + e.getMessage());
4167        }
4168    }
4169
4170    /*
4171     *  Scan a package and return the newly parsed package.
4172     *  Returns null in case of errors and the error code is stored in mLastScanError
4173     */
4174    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4175            long currentTime, UserHandle user) throws PackageManagerException {
4176        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4177        parseFlags |= mDefParseFlags;
4178        PackageParser pp = new PackageParser();
4179        pp.setSeparateProcesses(mSeparateProcesses);
4180        pp.setOnlyCoreApps(mOnlyCore);
4181        pp.setDisplayMetrics(mMetrics);
4182
4183        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4184            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4185        }
4186
4187        final PackageParser.Package pkg;
4188        try {
4189            pkg = pp.parsePackage(scanFile, parseFlags);
4190        } catch (PackageParserException e) {
4191            throw new PackageManagerException(e.error,
4192                    "Failed to scan " + scanFile + ": " + e.getMessage());
4193        }
4194
4195        PackageSetting ps = null;
4196        PackageSetting updatedPkg;
4197        // reader
4198        synchronized (mPackages) {
4199            // Look to see if we already know about this package.
4200            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4201            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4202                // This package has been renamed to its original name.  Let's
4203                // use that.
4204                ps = mSettings.peekPackageLPr(oldName);
4205            }
4206            // If there was no original package, see one for the real package name.
4207            if (ps == null) {
4208                ps = mSettings.peekPackageLPr(pkg.packageName);
4209            }
4210            // Check to see if this package could be hiding/updating a system
4211            // package.  Must look for it either under the original or real
4212            // package name depending on our state.
4213            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4214            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4215        }
4216        boolean updatedPkgBetter = false;
4217        // First check if this is a system package that may involve an update
4218        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4219            if (ps != null && !ps.codePath.equals(scanFile)) {
4220                // The path has changed from what was last scanned...  check the
4221                // version of the new path against what we have stored to determine
4222                // what to do.
4223                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4224                if (pkg.mVersionCode < ps.versionCode) {
4225                    // The system package has been updated and the code path does not match
4226                    // Ignore entry. Skip it.
4227                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4228                            + " ignored: updated version " + ps.versionCode
4229                            + " better than this " + pkg.mVersionCode);
4230                    if (!updatedPkg.codePath.equals(scanFile)) {
4231                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4232                                + ps.name + " changing from " + updatedPkg.codePathString
4233                                + " to " + scanFile);
4234                        updatedPkg.codePath = scanFile;
4235                        updatedPkg.codePathString = scanFile.toString();
4236                        // This is the point at which we know that the system-disk APK
4237                        // for this package has moved during a reboot (e.g. due to an OTA),
4238                        // so we need to reevaluate it for privilege policy.
4239                        if (locationIsPrivileged(scanFile)) {
4240                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4241                        }
4242                    }
4243                    updatedPkg.pkg = pkg;
4244                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4245                } else {
4246                    // The current app on the system partition is better than
4247                    // what we have updated to on the data partition; switch
4248                    // back to the system partition version.
4249                    // At this point, its safely assumed that package installation for
4250                    // apps in system partition will go through. If not there won't be a working
4251                    // version of the app
4252                    // writer
4253                    synchronized (mPackages) {
4254                        // Just remove the loaded entries from package lists.
4255                        mPackages.remove(ps.name);
4256                    }
4257                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4258                            + "reverting from " + ps.codePathString
4259                            + ": new version " + pkg.mVersionCode
4260                            + " better than installed " + ps.versionCode);
4261
4262                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4263                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4264                            getAppDexInstructionSets(ps));
4265                    synchronized (mInstallLock) {
4266                        args.cleanUpResourcesLI();
4267                    }
4268                    synchronized (mPackages) {
4269                        mSettings.enableSystemPackageLPw(ps.name);
4270                    }
4271                    updatedPkgBetter = true;
4272                }
4273            }
4274        }
4275
4276        if (updatedPkg != null) {
4277            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4278            // initially
4279            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4280
4281            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4282            // flag set initially
4283            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4284                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4285            }
4286        }
4287
4288        // Verify certificates against what was last scanned
4289        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4290
4291        /*
4292         * A new system app appeared, but we already had a non-system one of the
4293         * same name installed earlier.
4294         */
4295        boolean shouldHideSystemApp = false;
4296        if (updatedPkg == null && ps != null
4297                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4298            /*
4299             * Check to make sure the signatures match first. If they don't,
4300             * wipe the installed application and its data.
4301             */
4302            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4303                    != PackageManager.SIGNATURE_MATCH) {
4304                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4305                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4306                ps = null;
4307            } else {
4308                /*
4309                 * If the newly-added system app is an older version than the
4310                 * already installed version, hide it. It will be scanned later
4311                 * and re-added like an update.
4312                 */
4313                if (pkg.mVersionCode < ps.versionCode) {
4314                    shouldHideSystemApp = true;
4315                } else {
4316                    /*
4317                     * The newly found system app is a newer version that the
4318                     * one previously installed. Simply remove the
4319                     * already-installed application and replace it with our own
4320                     * while keeping the application data.
4321                     */
4322                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4323                            + ps.codePathString + ": new version " + pkg.mVersionCode
4324                            + " better than installed " + ps.versionCode);
4325                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4326                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4327                            getAppDexInstructionSets(ps));
4328                    synchronized (mInstallLock) {
4329                        args.cleanUpResourcesLI();
4330                    }
4331                }
4332            }
4333        }
4334
4335        // The apk is forward locked (not public) if its code and resources
4336        // are kept in different files. (except for app in either system or
4337        // vendor path).
4338        // TODO grab this value from PackageSettings
4339        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4340            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4341                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4342            }
4343        }
4344
4345        // TODO: extend to support forward-locked splits
4346        String resourcePath = null;
4347        String baseResourcePath = null;
4348        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4349            if (ps != null && ps.resourcePathString != null) {
4350                resourcePath = ps.resourcePathString;
4351                baseResourcePath = ps.resourcePathString;
4352            } else {
4353                // Should not happen at all. Just log an error.
4354                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4355            }
4356        } else {
4357            resourcePath = pkg.codePath;
4358            baseResourcePath = pkg.baseCodePath;
4359        }
4360
4361        // Set application objects path explicitly.
4362        pkg.applicationInfo.setCodePath(pkg.codePath);
4363        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4364        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4365        pkg.applicationInfo.setResourcePath(resourcePath);
4366        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4367        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4368
4369        // Note that we invoke the following method only if we are about to unpack an application
4370        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4371                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4372
4373        /*
4374         * If the system app should be overridden by a previously installed
4375         * data, hide the system app now and let the /data/app scan pick it up
4376         * again.
4377         */
4378        if (shouldHideSystemApp) {
4379            synchronized (mPackages) {
4380                /*
4381                 * We have to grant systems permissions before we hide, because
4382                 * grantPermissions will assume the package update is trying to
4383                 * expand its permissions.
4384                 */
4385                grantPermissionsLPw(pkg, true);
4386                mSettings.disableSystemPackageLPw(pkg.packageName);
4387            }
4388        }
4389
4390        return scannedPkg;
4391    }
4392
4393    private static String fixProcessName(String defProcessName,
4394            String processName, int uid) {
4395        if (processName == null) {
4396            return defProcessName;
4397        }
4398        return processName;
4399    }
4400
4401    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4402            throws PackageManagerException {
4403        if (pkgSetting.signatures.mSignatures != null) {
4404            // Already existing package. Make sure signatures match
4405            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4406                    == PackageManager.SIGNATURE_MATCH;
4407            if (!match) {
4408                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4409                        == PackageManager.SIGNATURE_MATCH;
4410            }
4411            if (!match) {
4412                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4413                        + pkg.packageName + " signatures do not match the "
4414                        + "previously installed version; ignoring!");
4415            }
4416        }
4417
4418        // Check for shared user signatures
4419        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4420            // Already existing package. Make sure signatures match
4421            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4422                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4423            if (!match) {
4424                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4425                        == PackageManager.SIGNATURE_MATCH;
4426            }
4427            if (!match) {
4428                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4429                        "Package " + pkg.packageName
4430                        + " has no signatures that match those in shared user "
4431                        + pkgSetting.sharedUser.name + "; ignoring!");
4432            }
4433        }
4434    }
4435
4436    /**
4437     * Enforces that only the system UID or root's UID can call a method exposed
4438     * via Binder.
4439     *
4440     * @param message used as message if SecurityException is thrown
4441     * @throws SecurityException if the caller is not system or root
4442     */
4443    private static final void enforceSystemOrRoot(String message) {
4444        final int uid = Binder.getCallingUid();
4445        if (uid != Process.SYSTEM_UID && uid != 0) {
4446            throw new SecurityException(message);
4447        }
4448    }
4449
4450    @Override
4451    public void performBootDexOpt() {
4452        enforceSystemOrRoot("Only the system can request dexopt be performed");
4453
4454        final HashSet<PackageParser.Package> pkgs;
4455        synchronized (mPackages) {
4456            pkgs = mDeferredDexOpt;
4457            mDeferredDexOpt = null;
4458        }
4459
4460        if (pkgs != null) {
4461            // Filter out packages that aren't recently used.
4462            //
4463            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4464            // should do a full dexopt.
4465            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4466                // TODO: add a property to control this?
4467                long dexOptLRUThresholdInMinutes;
4468                if (mLazyDexOpt) {
4469                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4470                } else {
4471                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4472                }
4473                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4474
4475                int total = pkgs.size();
4476                int skipped = 0;
4477                long now = System.currentTimeMillis();
4478                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4479                    PackageParser.Package pkg = i.next();
4480                    long then = pkg.mLastPackageUsageTimeInMills;
4481                    if (then + dexOptLRUThresholdInMills < now) {
4482                        if (DEBUG_DEXOPT) {
4483                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4484                                  ((then == 0) ? "never" : new Date(then)));
4485                        }
4486                        i.remove();
4487                        skipped++;
4488                    }
4489                }
4490                if (DEBUG_DEXOPT) {
4491                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4492                }
4493            }
4494
4495            int i = 0;
4496            for (PackageParser.Package pkg : pkgs) {
4497                i++;
4498                if (DEBUG_DEXOPT) {
4499                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4500                          + ": " + pkg.packageName);
4501                }
4502                if (!isFirstBoot()) {
4503                    try {
4504                        ActivityManagerNative.getDefault().showBootMessage(
4505                                mContext.getResources().getString(
4506                                        R.string.android_upgrading_apk,
4507                                        i, pkgs.size()), true);
4508                    } catch (RemoteException e) {
4509                    }
4510                }
4511                PackageParser.Package p = pkg;
4512                synchronized (mInstallLock) {
4513                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4514                            true /* include dependencies */);
4515                }
4516            }
4517        }
4518    }
4519
4520    @Override
4521    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4522        return performDexOpt(packageName, instructionSet, false);
4523    }
4524
4525    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4526        if (info.primaryCpuAbi == null) {
4527            return getPreferredInstructionSet();
4528        }
4529
4530        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4531    }
4532
4533    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4534        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4535        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4536        if (!dexopt && !updateUsage) {
4537            // We aren't going to dexopt or update usage, so bail early.
4538            return false;
4539        }
4540        PackageParser.Package p;
4541        final String targetInstructionSet;
4542        synchronized (mPackages) {
4543            p = mPackages.get(packageName);
4544            if (p == null) {
4545                return false;
4546            }
4547            if (updateUsage) {
4548                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4549            }
4550            mPackageUsage.write(false);
4551            if (!dexopt) {
4552                // We aren't going to dexopt, so bail early.
4553                return false;
4554            }
4555
4556            targetInstructionSet = instructionSet != null ? instructionSet :
4557                    getPrimaryInstructionSet(p.applicationInfo);
4558            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4559                return false;
4560            }
4561        }
4562
4563        synchronized (mInstallLock) {
4564            final String[] instructionSets = new String[] { targetInstructionSet };
4565            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4566                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4567        }
4568    }
4569
4570    public HashSet<String> getPackagesThatNeedDexOpt() {
4571        HashSet<String> pkgs = null;
4572        synchronized (mPackages) {
4573            for (PackageParser.Package p : mPackages.values()) {
4574                if (DEBUG_DEXOPT) {
4575                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4576                }
4577                if (!p.mDexOptPerformed.isEmpty()) {
4578                    continue;
4579                }
4580                if (pkgs == null) {
4581                    pkgs = new HashSet<String>();
4582                }
4583                pkgs.add(p.packageName);
4584            }
4585        }
4586        return pkgs;
4587    }
4588
4589    public void shutdown() {
4590        mPackageUsage.write(true);
4591    }
4592
4593    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4594             boolean forceDex, boolean defer, HashSet<String> done) {
4595        for (int i=0; i<libs.size(); i++) {
4596            PackageParser.Package libPkg;
4597            String libName;
4598            synchronized (mPackages) {
4599                libName = libs.get(i);
4600                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4601                if (lib != null && lib.apk != null) {
4602                    libPkg = mPackages.get(lib.apk);
4603                } else {
4604                    libPkg = null;
4605                }
4606            }
4607            if (libPkg != null && !done.contains(libName)) {
4608                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4609            }
4610        }
4611    }
4612
4613    static final int DEX_OPT_SKIPPED = 0;
4614    static final int DEX_OPT_PERFORMED = 1;
4615    static final int DEX_OPT_DEFERRED = 2;
4616    static final int DEX_OPT_FAILED = -1;
4617
4618    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4619            boolean forceDex, boolean defer, HashSet<String> done) {
4620        final String[] instructionSets = targetInstructionSets != null ?
4621                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4622
4623        if (done != null) {
4624            done.add(pkg.packageName);
4625            if (pkg.usesLibraries != null) {
4626                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4627            }
4628            if (pkg.usesOptionalLibraries != null) {
4629                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4630            }
4631        }
4632
4633        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4634            return DEX_OPT_SKIPPED;
4635        }
4636
4637        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4638
4639        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4640        boolean performedDexOpt = false;
4641        // There are three basic cases here:
4642        // 1.) we need to dexopt, either because we are forced or it is needed
4643        // 2.) we are defering a needed dexopt
4644        // 3.) we are skipping an unneeded dexopt
4645        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4646        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4647            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4648                continue;
4649            }
4650
4651            for (String path : paths) {
4652                try {
4653                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4654                    // patckage or the one we find does not match the image checksum (i.e. it was
4655                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4656                    // odex file and it matches the checksum of the image but not its base address,
4657                    // meaning we need to move it.
4658                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4659                            pkg.packageName, dexCodeInstructionSet, defer);
4660                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4661                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4662                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4663                                + " vmSafeMode=" + vmSafeMode);
4664                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4665                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4666                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4667
4668                        if (ret < 0) {
4669                            // Don't bother running dexopt again if we failed, it will probably
4670                            // just result in an error again. Also, don't bother dexopting for other
4671                            // paths & ISAs.
4672                            return DEX_OPT_FAILED;
4673                        }
4674
4675                        performedDexOpt = true;
4676                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4677                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4678                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4679                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4680                                pkg.packageName, dexCodeInstructionSet);
4681
4682                        if (ret < 0) {
4683                            // Don't bother running patchoat again if we failed, it will probably
4684                            // just result in an error again. Also, don't bother dexopting for other
4685                            // paths & ISAs.
4686                            return DEX_OPT_FAILED;
4687                        }
4688
4689                        performedDexOpt = true;
4690                    }
4691
4692                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4693                    // paths and instruction sets. We'll deal with them all together when we process
4694                    // our list of deferred dexopts.
4695                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4696                        if (mDeferredDexOpt == null) {
4697                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4698                        }
4699                        mDeferredDexOpt.add(pkg);
4700                        return DEX_OPT_DEFERRED;
4701                    }
4702                } catch (FileNotFoundException e) {
4703                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4704                    return DEX_OPT_FAILED;
4705                } catch (IOException e) {
4706                    Slog.w(TAG, "IOException reading apk: " + path, e);
4707                    return DEX_OPT_FAILED;
4708                } catch (StaleDexCacheError e) {
4709                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4710                    return DEX_OPT_FAILED;
4711                } catch (Exception e) {
4712                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4713                    return DEX_OPT_FAILED;
4714                }
4715            }
4716
4717            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4718            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4719            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4720            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4721            // it.
4722            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4723        }
4724
4725        // If we've gotten here, we're sure that no error occurred and that we haven't
4726        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4727        // we've skipped all of them because they are up to date. In both cases this
4728        // package doesn't need dexopt any longer.
4729        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4730    }
4731
4732    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4733        if (info.primaryCpuAbi != null) {
4734            if (info.secondaryCpuAbi != null) {
4735                return new String[] {
4736                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4737                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4738            } else {
4739                return new String[] {
4740                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4741            }
4742        }
4743
4744        return new String[] { getPreferredInstructionSet() };
4745    }
4746
4747    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4748        if (ps.primaryCpuAbiString != null) {
4749            if (ps.secondaryCpuAbiString != null) {
4750                return new String[] {
4751                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4752                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4753            } else {
4754                return new String[] {
4755                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4756            }
4757        }
4758
4759        return new String[] { getPreferredInstructionSet() };
4760    }
4761
4762    private static String getPreferredInstructionSet() {
4763        if (sPreferredInstructionSet == null) {
4764            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4765        }
4766
4767        return sPreferredInstructionSet;
4768    }
4769
4770    private static List<String> getAllInstructionSets() {
4771        final String[] allAbis = Build.SUPPORTED_ABIS;
4772        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4773
4774        for (String abi : allAbis) {
4775            final String instructionSet = VMRuntime.getInstructionSet(abi);
4776            if (!allInstructionSets.contains(instructionSet)) {
4777                allInstructionSets.add(instructionSet);
4778            }
4779        }
4780
4781        return allInstructionSets;
4782    }
4783
4784    /**
4785     * Returns the instruction set that should be used to compile dex code. In the presence of
4786     * a native bridge this might be different than the one shared libraries use.
4787     */
4788    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4789        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4790        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4791    }
4792
4793    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4794        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4795        for (String instructionSet : instructionSets) {
4796            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4797        }
4798        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4799    }
4800
4801    @Override
4802    public void forceDexOpt(String packageName) {
4803        enforceSystemOrRoot("forceDexOpt");
4804
4805        PackageParser.Package pkg;
4806        synchronized (mPackages) {
4807            pkg = mPackages.get(packageName);
4808            if (pkg == null) {
4809                throw new IllegalArgumentException("Missing package: " + packageName);
4810            }
4811        }
4812
4813        synchronized (mInstallLock) {
4814            final String[] instructionSets = new String[] {
4815                    getPrimaryInstructionSet(pkg.applicationInfo) };
4816            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4817            if (res != DEX_OPT_PERFORMED) {
4818                throw new IllegalStateException("Failed to dexopt: " + res);
4819            }
4820        }
4821    }
4822
4823    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4824                                boolean forceDex, boolean defer, boolean inclDependencies) {
4825        HashSet<String> done;
4826        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4827            done = new HashSet<String>();
4828            done.add(pkg.packageName);
4829        } else {
4830            done = null;
4831        }
4832        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4833    }
4834
4835    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4836        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4837            Slog.w(TAG, "Unable to update from " + oldPkg.name
4838                    + " to " + newPkg.packageName
4839                    + ": old package not in system partition");
4840            return false;
4841        } else if (mPackages.get(oldPkg.name) != null) {
4842            Slog.w(TAG, "Unable to update from " + oldPkg.name
4843                    + " to " + newPkg.packageName
4844                    + ": old package still exists");
4845            return false;
4846        }
4847        return true;
4848    }
4849
4850    File getDataPathForUser(int userId) {
4851        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4852    }
4853
4854    private File getDataPathForPackage(String packageName, int userId) {
4855        /*
4856         * Until we fully support multiple users, return the directory we
4857         * previously would have. The PackageManagerTests will need to be
4858         * revised when this is changed back..
4859         */
4860        if (userId == 0) {
4861            return new File(mAppDataDir, packageName);
4862        } else {
4863            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4864                + File.separator + packageName);
4865        }
4866    }
4867
4868    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4869        int[] users = sUserManager.getUserIds();
4870        int res = mInstaller.install(packageName, uid, uid, seinfo);
4871        if (res < 0) {
4872            return res;
4873        }
4874        for (int user : users) {
4875            if (user != 0) {
4876                res = mInstaller.createUserData(packageName,
4877                        UserHandle.getUid(user, uid), user, seinfo);
4878                if (res < 0) {
4879                    return res;
4880                }
4881            }
4882        }
4883        return res;
4884    }
4885
4886    private int removeDataDirsLI(String packageName) {
4887        int[] users = sUserManager.getUserIds();
4888        int res = 0;
4889        for (int user : users) {
4890            int resInner = mInstaller.remove(packageName, user);
4891            if (resInner < 0) {
4892                res = resInner;
4893            }
4894        }
4895
4896        return res;
4897    }
4898
4899    private int deleteCodeCacheDirsLI(String packageName) {
4900        int[] users = sUserManager.getUserIds();
4901        int res = 0;
4902        for (int user : users) {
4903            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4904            if (resInner < 0) {
4905                res = resInner;
4906            }
4907        }
4908        return res;
4909    }
4910
4911    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4912            PackageParser.Package changingLib) {
4913        if (file.path != null) {
4914            usesLibraryFiles.add(file.path);
4915            return;
4916        }
4917        PackageParser.Package p = mPackages.get(file.apk);
4918        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4919            // If we are doing this while in the middle of updating a library apk,
4920            // then we need to make sure to use that new apk for determining the
4921            // dependencies here.  (We haven't yet finished committing the new apk
4922            // to the package manager state.)
4923            if (p == null || p.packageName.equals(changingLib.packageName)) {
4924                p = changingLib;
4925            }
4926        }
4927        if (p != null) {
4928            usesLibraryFiles.addAll(p.getAllCodePaths());
4929        }
4930    }
4931
4932    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4933            PackageParser.Package changingLib) throws PackageManagerException {
4934        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4935            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4936            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4937            for (int i=0; i<N; i++) {
4938                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4939                if (file == null) {
4940                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4941                            "Package " + pkg.packageName + " requires unavailable shared library "
4942                            + pkg.usesLibraries.get(i) + "; failing!");
4943                }
4944                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4945            }
4946            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4947            for (int i=0; i<N; i++) {
4948                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4949                if (file == null) {
4950                    Slog.w(TAG, "Package " + pkg.packageName
4951                            + " desires unavailable shared library "
4952                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4953                } else {
4954                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4955                }
4956            }
4957            N = usesLibraryFiles.size();
4958            if (N > 0) {
4959                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4960            } else {
4961                pkg.usesLibraryFiles = null;
4962            }
4963        }
4964    }
4965
4966    private static boolean hasString(List<String> list, List<String> which) {
4967        if (list == null) {
4968            return false;
4969        }
4970        for (int i=list.size()-1; i>=0; i--) {
4971            for (int j=which.size()-1; j>=0; j--) {
4972                if (which.get(j).equals(list.get(i))) {
4973                    return true;
4974                }
4975            }
4976        }
4977        return false;
4978    }
4979
4980    private void updateAllSharedLibrariesLPw() {
4981        for (PackageParser.Package pkg : mPackages.values()) {
4982            try {
4983                updateSharedLibrariesLPw(pkg, null);
4984            } catch (PackageManagerException e) {
4985                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4986            }
4987        }
4988    }
4989
4990    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4991            PackageParser.Package changingPkg) {
4992        ArrayList<PackageParser.Package> res = null;
4993        for (PackageParser.Package pkg : mPackages.values()) {
4994            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4995                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4996                if (res == null) {
4997                    res = new ArrayList<PackageParser.Package>();
4998                }
4999                res.add(pkg);
5000                try {
5001                    updateSharedLibrariesLPw(pkg, changingPkg);
5002                } catch (PackageManagerException e) {
5003                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5004                }
5005            }
5006        }
5007        return res;
5008    }
5009
5010    /**
5011     * Derive the value of the {@code cpuAbiOverride} based on the provided
5012     * value and an optional stored value from the package settings.
5013     */
5014    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5015        String cpuAbiOverride = null;
5016
5017        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5018            cpuAbiOverride = null;
5019        } else if (abiOverride != null) {
5020            cpuAbiOverride = abiOverride;
5021        } else if (settings != null) {
5022            cpuAbiOverride = settings.cpuAbiOverrideString;
5023        }
5024
5025        return cpuAbiOverride;
5026    }
5027
5028    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5029            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5030        final File scanFile = new File(pkg.codePath);
5031        if (pkg.applicationInfo.getCodePath() == null ||
5032                pkg.applicationInfo.getResourcePath() == null) {
5033            // Bail out. The resource and code paths haven't been set.
5034            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5035                    "Code and resource paths haven't been set correctly");
5036        }
5037
5038        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5039            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5040        }
5041
5042        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5043            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5044        }
5045
5046        if (mCustomResolverComponentName != null &&
5047                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5048            setUpCustomResolverActivity(pkg);
5049        }
5050
5051        if (pkg.packageName.equals("android")) {
5052            synchronized (mPackages) {
5053                if (mAndroidApplication != null) {
5054                    Slog.w(TAG, "*************************************************");
5055                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5056                    Slog.w(TAG, " file=" + scanFile);
5057                    Slog.w(TAG, "*************************************************");
5058                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5059                            "Core android package being redefined.  Skipping.");
5060                }
5061
5062                // Set up information for our fall-back user intent resolution activity.
5063                mPlatformPackage = pkg;
5064                pkg.mVersionCode = mSdkVersion;
5065                mAndroidApplication = pkg.applicationInfo;
5066
5067                if (!mResolverReplaced) {
5068                    mResolveActivity.applicationInfo = mAndroidApplication;
5069                    mResolveActivity.name = ResolverActivity.class.getName();
5070                    mResolveActivity.packageName = mAndroidApplication.packageName;
5071                    mResolveActivity.processName = "system:ui";
5072                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5073                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5074                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5075                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5076                    mResolveActivity.exported = true;
5077                    mResolveActivity.enabled = true;
5078                    mResolveInfo.activityInfo = mResolveActivity;
5079                    mResolveInfo.priority = 0;
5080                    mResolveInfo.preferredOrder = 0;
5081                    mResolveInfo.match = 0;
5082                    mResolveComponentName = new ComponentName(
5083                            mAndroidApplication.packageName, mResolveActivity.name);
5084                }
5085            }
5086        }
5087
5088        if (DEBUG_PACKAGE_SCANNING) {
5089            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5090                Log.d(TAG, "Scanning package " + pkg.packageName);
5091        }
5092
5093        if (mPackages.containsKey(pkg.packageName)
5094                || mSharedLibraries.containsKey(pkg.packageName)) {
5095            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5096                    "Application package " + pkg.packageName
5097                    + " already installed.  Skipping duplicate.");
5098        }
5099
5100        // Initialize package source and resource directories
5101        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5102        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5103
5104        SharedUserSetting suid = null;
5105        PackageSetting pkgSetting = null;
5106
5107        if (!isSystemApp(pkg)) {
5108            // Only system apps can use these features.
5109            pkg.mOriginalPackages = null;
5110            pkg.mRealPackage = null;
5111            pkg.mAdoptPermissions = null;
5112        }
5113
5114        // writer
5115        synchronized (mPackages) {
5116            if (pkg.mSharedUserId != null) {
5117                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5118                if (suid == null) {
5119                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5120                            "Creating application package " + pkg.packageName
5121                            + " for shared user failed");
5122                }
5123                if (DEBUG_PACKAGE_SCANNING) {
5124                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5125                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5126                                + "): packages=" + suid.packages);
5127                }
5128            }
5129
5130            // Check if we are renaming from an original package name.
5131            PackageSetting origPackage = null;
5132            String realName = null;
5133            if (pkg.mOriginalPackages != null) {
5134                // This package may need to be renamed to a previously
5135                // installed name.  Let's check on that...
5136                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5137                if (pkg.mOriginalPackages.contains(renamed)) {
5138                    // This package had originally been installed as the
5139                    // original name, and we have already taken care of
5140                    // transitioning to the new one.  Just update the new
5141                    // one to continue using the old name.
5142                    realName = pkg.mRealPackage;
5143                    if (!pkg.packageName.equals(renamed)) {
5144                        // Callers into this function may have already taken
5145                        // care of renaming the package; only do it here if
5146                        // it is not already done.
5147                        pkg.setPackageName(renamed);
5148                    }
5149
5150                } else {
5151                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5152                        if ((origPackage = mSettings.peekPackageLPr(
5153                                pkg.mOriginalPackages.get(i))) != null) {
5154                            // We do have the package already installed under its
5155                            // original name...  should we use it?
5156                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5157                                // New package is not compatible with original.
5158                                origPackage = null;
5159                                continue;
5160                            } else if (origPackage.sharedUser != null) {
5161                                // Make sure uid is compatible between packages.
5162                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5163                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5164                                            + " to " + pkg.packageName + ": old uid "
5165                                            + origPackage.sharedUser.name
5166                                            + " differs from " + pkg.mSharedUserId);
5167                                    origPackage = null;
5168                                    continue;
5169                                }
5170                            } else {
5171                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5172                                        + pkg.packageName + " to old name " + origPackage.name);
5173                            }
5174                            break;
5175                        }
5176                    }
5177                }
5178            }
5179
5180            if (mTransferedPackages.contains(pkg.packageName)) {
5181                Slog.w(TAG, "Package " + pkg.packageName
5182                        + " was transferred to another, but its .apk remains");
5183            }
5184
5185            // Just create the setting, don't add it yet. For already existing packages
5186            // the PkgSetting exists already and doesn't have to be created.
5187            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5188                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5189                    pkg.applicationInfo.primaryCpuAbi,
5190                    pkg.applicationInfo.secondaryCpuAbi,
5191                    pkg.applicationInfo.flags, user, false);
5192            if (pkgSetting == null) {
5193                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5194                        "Creating application package " + pkg.packageName + " failed");
5195            }
5196
5197            if (pkgSetting.origPackage != null) {
5198                // If we are first transitioning from an original package,
5199                // fix up the new package's name now.  We need to do this after
5200                // looking up the package under its new name, so getPackageLP
5201                // can take care of fiddling things correctly.
5202                pkg.setPackageName(origPackage.name);
5203
5204                // File a report about this.
5205                String msg = "New package " + pkgSetting.realName
5206                        + " renamed to replace old package " + pkgSetting.name;
5207                reportSettingsProblem(Log.WARN, msg);
5208
5209                // Make a note of it.
5210                mTransferedPackages.add(origPackage.name);
5211
5212                // No longer need to retain this.
5213                pkgSetting.origPackage = null;
5214            }
5215
5216            if (realName != null) {
5217                // Make a note of it.
5218                mTransferedPackages.add(pkg.packageName);
5219            }
5220
5221            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5222                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5223            }
5224
5225            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5226                // Check all shared libraries and map to their actual file path.
5227                // We only do this here for apps not on a system dir, because those
5228                // are the only ones that can fail an install due to this.  We
5229                // will take care of the system apps by updating all of their
5230                // library paths after the scan is done.
5231                updateSharedLibrariesLPw(pkg, null);
5232            }
5233
5234            if (mFoundPolicyFile) {
5235                SELinuxMMAC.assignSeinfoValue(pkg);
5236            }
5237
5238            pkg.applicationInfo.uid = pkgSetting.appId;
5239            pkg.mExtras = pkgSetting;
5240            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5241                try {
5242                    verifySignaturesLP(pkgSetting, pkg);
5243                } catch (PackageManagerException e) {
5244                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5245                        throw e;
5246                    }
5247                    // The signature has changed, but this package is in the system
5248                    // image...  let's recover!
5249                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5250                    // However...  if this package is part of a shared user, but it
5251                    // doesn't match the signature of the shared user, let's fail.
5252                    // What this means is that you can't change the signatures
5253                    // associated with an overall shared user, which doesn't seem all
5254                    // that unreasonable.
5255                    if (pkgSetting.sharedUser != null) {
5256                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5257                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5258                            throw new PackageManagerException(
5259                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5260                                            "Signature mismatch for shared user : "
5261                                            + pkgSetting.sharedUser);
5262                        }
5263                    }
5264                    // File a report about this.
5265                    String msg = "System package " + pkg.packageName
5266                        + " signature changed; retaining data.";
5267                    reportSettingsProblem(Log.WARN, msg);
5268                }
5269            } else {
5270                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5271                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5272                            + pkg.packageName + " upgrade keys do not match the "
5273                            + "previously installed version");
5274                } else {
5275                    // signatures may have changed as result of upgrade
5276                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5277                }
5278            }
5279            // Verify that this new package doesn't have any content providers
5280            // that conflict with existing packages.  Only do this if the
5281            // package isn't already installed, since we don't want to break
5282            // things that are installed.
5283            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5284                final int N = pkg.providers.size();
5285                int i;
5286                for (i=0; i<N; i++) {
5287                    PackageParser.Provider p = pkg.providers.get(i);
5288                    if (p.info.authority != null) {
5289                        String names[] = p.info.authority.split(";");
5290                        for (int j = 0; j < names.length; j++) {
5291                            if (mProvidersByAuthority.containsKey(names[j])) {
5292                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5293                                final String otherPackageName =
5294                                        ((other != null && other.getComponentName() != null) ?
5295                                                other.getComponentName().getPackageName() : "?");
5296                                throw new PackageManagerException(
5297                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5298                                                "Can't install because provider name " + names[j]
5299                                                + " (in package " + pkg.applicationInfo.packageName
5300                                                + ") is already used by " + otherPackageName);
5301                            }
5302                        }
5303                    }
5304                }
5305            }
5306
5307            if (pkg.mAdoptPermissions != null) {
5308                // This package wants to adopt ownership of permissions from
5309                // another package.
5310                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5311                    final String origName = pkg.mAdoptPermissions.get(i);
5312                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5313                    if (orig != null) {
5314                        if (verifyPackageUpdateLPr(orig, pkg)) {
5315                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5316                                    + pkg.packageName);
5317                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5318                        }
5319                    }
5320                }
5321            }
5322        }
5323
5324        final String pkgName = pkg.packageName;
5325
5326        final long scanFileTime = scanFile.lastModified();
5327        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5328        pkg.applicationInfo.processName = fixProcessName(
5329                pkg.applicationInfo.packageName,
5330                pkg.applicationInfo.processName,
5331                pkg.applicationInfo.uid);
5332
5333        File dataPath;
5334        if (mPlatformPackage == pkg) {
5335            // The system package is special.
5336            dataPath = new File (Environment.getDataDirectory(), "system");
5337            pkg.applicationInfo.dataDir = dataPath.getPath();
5338
5339        } else {
5340            // This is a normal package, need to make its data directory.
5341            dataPath = getDataPathForPackage(pkg.packageName, 0);
5342
5343            boolean uidError = false;
5344
5345            if (dataPath.exists()) {
5346                int currentUid = 0;
5347                try {
5348                    StructStat stat = Os.stat(dataPath.getPath());
5349                    currentUid = stat.st_uid;
5350                } catch (ErrnoException e) {
5351                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5352                }
5353
5354                // If we have mismatched owners for the data path, we have a problem.
5355                if (currentUid != pkg.applicationInfo.uid) {
5356                    boolean recovered = false;
5357                    if (currentUid == 0) {
5358                        // The directory somehow became owned by root.  Wow.
5359                        // This is probably because the system was stopped while
5360                        // installd was in the middle of messing with its libs
5361                        // directory.  Ask installd to fix that.
5362                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5363                                pkg.applicationInfo.uid);
5364                        if (ret >= 0) {
5365                            recovered = true;
5366                            String msg = "Package " + pkg.packageName
5367                                    + " unexpectedly changed to uid 0; recovered to " +
5368                                    + pkg.applicationInfo.uid;
5369                            reportSettingsProblem(Log.WARN, msg);
5370                        }
5371                    }
5372                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5373                            || (scanFlags&SCAN_BOOTING) != 0)) {
5374                        // If this is a system app, we can at least delete its
5375                        // current data so the application will still work.
5376                        int ret = removeDataDirsLI(pkgName);
5377                        if (ret >= 0) {
5378                            // TODO: Kill the processes first
5379                            // Old data gone!
5380                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5381                                    ? "System package " : "Third party package ";
5382                            String msg = prefix + pkg.packageName
5383                                    + " has changed from uid: "
5384                                    + currentUid + " to "
5385                                    + pkg.applicationInfo.uid + "; old data erased";
5386                            reportSettingsProblem(Log.WARN, msg);
5387                            recovered = true;
5388
5389                            // And now re-install the app.
5390                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5391                                                   pkg.applicationInfo.seinfo);
5392                            if (ret == -1) {
5393                                // Ack should not happen!
5394                                msg = prefix + pkg.packageName
5395                                        + " could not have data directory re-created after delete.";
5396                                reportSettingsProblem(Log.WARN, msg);
5397                                throw new PackageManagerException(
5398                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5399                            }
5400                        }
5401                        if (!recovered) {
5402                            mHasSystemUidErrors = true;
5403                        }
5404                    } else if (!recovered) {
5405                        // If we allow this install to proceed, we will be broken.
5406                        // Abort, abort!
5407                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5408                                "scanPackageLI");
5409                    }
5410                    if (!recovered) {
5411                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5412                            + pkg.applicationInfo.uid + "/fs_"
5413                            + currentUid;
5414                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5415                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5416                        String msg = "Package " + pkg.packageName
5417                                + " has mismatched uid: "
5418                                + currentUid + " on disk, "
5419                                + pkg.applicationInfo.uid + " in settings";
5420                        // writer
5421                        synchronized (mPackages) {
5422                            mSettings.mReadMessages.append(msg);
5423                            mSettings.mReadMessages.append('\n');
5424                            uidError = true;
5425                            if (!pkgSetting.uidError) {
5426                                reportSettingsProblem(Log.ERROR, msg);
5427                            }
5428                        }
5429                    }
5430                }
5431                pkg.applicationInfo.dataDir = dataPath.getPath();
5432                if (mShouldRestoreconData) {
5433                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5434                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5435                                pkg.applicationInfo.uid);
5436                }
5437            } else {
5438                if (DEBUG_PACKAGE_SCANNING) {
5439                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5440                        Log.v(TAG, "Want this data dir: " + dataPath);
5441                }
5442                //invoke installer to do the actual installation
5443                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5444                                           pkg.applicationInfo.seinfo);
5445                if (ret < 0) {
5446                    // Error from installer
5447                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5448                            "Unable to create data dirs [errorCode=" + ret + "]");
5449                }
5450
5451                if (dataPath.exists()) {
5452                    pkg.applicationInfo.dataDir = dataPath.getPath();
5453                } else {
5454                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5455                    pkg.applicationInfo.dataDir = null;
5456                }
5457            }
5458
5459            pkgSetting.uidError = uidError;
5460        }
5461
5462        final String path = scanFile.getPath();
5463        final String codePath = pkg.applicationInfo.getCodePath();
5464        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5465        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5466            setBundledAppAbisAndRoots(pkg, pkgSetting);
5467
5468            // If we haven't found any native libraries for the app, check if it has
5469            // renderscript code. We'll need to force the app to 32 bit if it has
5470            // renderscript bitcode.
5471            if (pkg.applicationInfo.primaryCpuAbi == null
5472                    && pkg.applicationInfo.secondaryCpuAbi == null
5473                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5474                NativeLibraryHelper.Handle handle = null;
5475                try {
5476                    handle = NativeLibraryHelper.Handle.create(scanFile);
5477                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5478                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5479                    }
5480                } catch (IOException ioe) {
5481                    Slog.w(TAG, "Error scanning system app : " + ioe);
5482                } finally {
5483                    IoUtils.closeQuietly(handle);
5484                }
5485            }
5486
5487            setNativeLibraryPaths(pkg);
5488        } else {
5489            // TODO: We can probably be smarter about this stuff. For installed apps,
5490            // we can calculate this information at install time once and for all. For
5491            // system apps, we can probably assume that this information doesn't change
5492            // after the first boot scan. As things stand, we do lots of unnecessary work.
5493
5494            // Give ourselves some initial paths; we'll come back for another
5495            // pass once we've determined ABI below.
5496            setNativeLibraryPaths(pkg);
5497
5498            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5499            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5500            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5501
5502            NativeLibraryHelper.Handle handle = null;
5503            try {
5504                handle = NativeLibraryHelper.Handle.create(scanFile);
5505                // TODO(multiArch): This can be null for apps that didn't go through the
5506                // usual installation process. We can calculate it again, like we
5507                // do during install time.
5508                //
5509                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5510                // unnecessary.
5511                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5512
5513                // Null out the abis so that they can be recalculated.
5514                pkg.applicationInfo.primaryCpuAbi = null;
5515                pkg.applicationInfo.secondaryCpuAbi = null;
5516                if (isMultiArch(pkg.applicationInfo)) {
5517                    // Warn if we've set an abiOverride for multi-lib packages..
5518                    // By definition, we need to copy both 32 and 64 bit libraries for
5519                    // such packages.
5520                    if (pkg.cpuAbiOverride != null
5521                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5522                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5523                    }
5524
5525                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5526                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5527                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5528                        if (isAsec) {
5529                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5530                        } else {
5531                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5532                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5533                                    useIsaSpecificSubdirs);
5534                        }
5535                    }
5536
5537                    maybeThrowExceptionForMultiArchCopy(
5538                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5539
5540                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5541                        if (isAsec) {
5542                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5543                        } else {
5544                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5545                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5546                                    useIsaSpecificSubdirs);
5547                        }
5548                    }
5549
5550                    maybeThrowExceptionForMultiArchCopy(
5551                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5552
5553                    if (abi64 >= 0) {
5554                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5555                    }
5556
5557                    if (abi32 >= 0) {
5558                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5559                        if (abi64 >= 0) {
5560                            pkg.applicationInfo.secondaryCpuAbi = abi;
5561                        } else {
5562                            pkg.applicationInfo.primaryCpuAbi = abi;
5563                        }
5564                    }
5565                } else {
5566                    String[] abiList = (cpuAbiOverride != null) ?
5567                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5568
5569                    // Enable gross and lame hacks for apps that are built with old
5570                    // SDK tools. We must scan their APKs for renderscript bitcode and
5571                    // not launch them if it's present. Don't bother checking on devices
5572                    // that don't have 64 bit support.
5573                    boolean needsRenderScriptOverride = false;
5574                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5575                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5576                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5577                        needsRenderScriptOverride = true;
5578                    }
5579
5580                    final int copyRet;
5581                    if (isAsec) {
5582                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5583                    } else {
5584                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5585                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5586                    }
5587
5588                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5589                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5590                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5591                    }
5592
5593                    if (copyRet >= 0) {
5594                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5595                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5596                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5597                    } else if (needsRenderScriptOverride) {
5598                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5599                    }
5600                }
5601            } catch (IOException ioe) {
5602                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5603            } finally {
5604                IoUtils.closeQuietly(handle);
5605            }
5606
5607            // Now that we've calculated the ABIs and determined if it's an internal app,
5608            // we will go ahead and populate the nativeLibraryPath.
5609            setNativeLibraryPaths(pkg);
5610
5611            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5612            final int[] userIds = sUserManager.getUserIds();
5613            synchronized (mInstallLock) {
5614                // Create a native library symlink only if we have native libraries
5615                // and if the native libraries are 32 bit libraries. We do not provide
5616                // this symlink for 64 bit libraries.
5617                if (pkg.applicationInfo.primaryCpuAbi != null &&
5618                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5619                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5620                    for (int userId : userIds) {
5621                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5622                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5623                                    "Failed linking native library dir (user=" + userId + ")");
5624                        }
5625                    }
5626                }
5627            }
5628        }
5629
5630        // This is a special case for the "system" package, where the ABI is
5631        // dictated by the zygote configuration (and init.rc). We should keep track
5632        // of this ABI so that we can deal with "normal" applications that run under
5633        // the same UID correctly.
5634        if (mPlatformPackage == pkg) {
5635            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5636                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5637        }
5638
5639        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5640        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5641        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5642        // Copy the derived override back to the parsed package, so that we can
5643        // update the package settings accordingly.
5644        pkg.cpuAbiOverride = cpuAbiOverride;
5645
5646        Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5647                + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5648                + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5649
5650        // Push the derived path down into PackageSettings so we know what to
5651        // clean up at uninstall time.
5652        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5653
5654        if (DEBUG_ABI_SELECTION) {
5655            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5656                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5657                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5658        }
5659
5660        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5661            // We don't do this here during boot because we can do it all
5662            // at once after scanning all existing packages.
5663            //
5664            // We also do this *before* we perform dexopt on this package, so that
5665            // we can avoid redundant dexopts, and also to make sure we've got the
5666            // code and package path correct.
5667            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5668                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5669        }
5670
5671        if ((scanFlags&SCAN_NO_DEX) == 0) {
5672            if (performDexOptLI(pkg, null /* instruction sets */, forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5673                    == DEX_OPT_FAILED) {
5674                if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5675                    removeDataDirsLI(pkg.packageName);
5676                }
5677
5678                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5679            }
5680        }
5681
5682        if (mFactoryTest && pkg.requestedPermissions.contains(
5683                android.Manifest.permission.FACTORY_TEST)) {
5684            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5685        }
5686
5687        ArrayList<PackageParser.Package> clientLibPkgs = null;
5688
5689        // writer
5690        synchronized (mPackages) {
5691            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5692                // Only system apps can add new shared libraries.
5693                if (pkg.libraryNames != null) {
5694                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5695                        String name = pkg.libraryNames.get(i);
5696                        boolean allowed = false;
5697                        if (isUpdatedSystemApp(pkg)) {
5698                            // New library entries can only be added through the
5699                            // system image.  This is important to get rid of a lot
5700                            // of nasty edge cases: for example if we allowed a non-
5701                            // system update of the app to add a library, then uninstalling
5702                            // the update would make the library go away, and assumptions
5703                            // we made such as through app install filtering would now
5704                            // have allowed apps on the device which aren't compatible
5705                            // with it.  Better to just have the restriction here, be
5706                            // conservative, and create many fewer cases that can negatively
5707                            // impact the user experience.
5708                            final PackageSetting sysPs = mSettings
5709                                    .getDisabledSystemPkgLPr(pkg.packageName);
5710                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5711                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5712                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5713                                        allowed = true;
5714                                        allowed = true;
5715                                        break;
5716                                    }
5717                                }
5718                            }
5719                        } else {
5720                            allowed = true;
5721                        }
5722                        if (allowed) {
5723                            if (!mSharedLibraries.containsKey(name)) {
5724                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5725                            } else if (!name.equals(pkg.packageName)) {
5726                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5727                                        + name + " already exists; skipping");
5728                            }
5729                        } else {
5730                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5731                                    + name + " that is not declared on system image; skipping");
5732                        }
5733                    }
5734                    if ((scanFlags&SCAN_BOOTING) == 0) {
5735                        // If we are not booting, we need to update any applications
5736                        // that are clients of our shared library.  If we are booting,
5737                        // this will all be done once the scan is complete.
5738                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5739                    }
5740                }
5741            }
5742        }
5743
5744        // We also need to dexopt any apps that are dependent on this library.  Note that
5745        // if these fail, we should abort the install since installing the library will
5746        // result in some apps being broken.
5747        if (clientLibPkgs != null) {
5748            if ((scanFlags&SCAN_NO_DEX) == 0) {
5749                for (int i=0; i<clientLibPkgs.size(); i++) {
5750                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5751                    if (performDexOptLI(clientPkg, null /* instruction sets */,
5752                            forceDex, (scanFlags&SCAN_DEFER_DEX) != 0, false)
5753                            == DEX_OPT_FAILED) {
5754                        if ((scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5755                            removeDataDirsLI(pkg.packageName);
5756                        }
5757
5758                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5759                                "scanPackageLI failed to dexopt clientLibPkgs");
5760                    }
5761                }
5762            }
5763        }
5764
5765        // Request the ActivityManager to kill the process(only for existing packages)
5766        // so that we do not end up in a confused state while the user is still using the older
5767        // version of the application while the new one gets installed.
5768        if ((scanFlags & SCAN_REPLACING) != 0) {
5769            killApplication(pkg.applicationInfo.packageName,
5770                        pkg.applicationInfo.uid, "update pkg");
5771        }
5772
5773        // Also need to kill any apps that are dependent on the library.
5774        if (clientLibPkgs != null) {
5775            for (int i=0; i<clientLibPkgs.size(); i++) {
5776                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5777                killApplication(clientPkg.applicationInfo.packageName,
5778                        clientPkg.applicationInfo.uid, "update lib");
5779            }
5780        }
5781
5782        // writer
5783        synchronized (mPackages) {
5784            // We don't expect installation to fail beyond this point
5785
5786            // Add the new setting to mSettings
5787            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5788            // Add the new setting to mPackages
5789            mPackages.put(pkg.applicationInfo.packageName, pkg);
5790            // Make sure we don't accidentally delete its data.
5791            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5792            while (iter.hasNext()) {
5793                PackageCleanItem item = iter.next();
5794                if (pkgName.equals(item.packageName)) {
5795                    iter.remove();
5796                }
5797            }
5798
5799            // Take care of first install / last update times.
5800            if (currentTime != 0) {
5801                if (pkgSetting.firstInstallTime == 0) {
5802                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5803                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5804                    pkgSetting.lastUpdateTime = currentTime;
5805                }
5806            } else if (pkgSetting.firstInstallTime == 0) {
5807                // We need *something*.  Take time time stamp of the file.
5808                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5809            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5810                if (scanFileTime != pkgSetting.timeStamp) {
5811                    // A package on the system image has changed; consider this
5812                    // to be an update.
5813                    pkgSetting.lastUpdateTime = scanFileTime;
5814                }
5815            }
5816
5817            // Add the package's KeySets to the global KeySetManagerService
5818            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5819            try {
5820                // Old KeySetData no longer valid.
5821                ksms.removeAppKeySetDataLPw(pkg.packageName);
5822                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5823                if (pkg.mKeySetMapping != null) {
5824                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5825                            pkg.mKeySetMapping.entrySet()) {
5826                        if (entry.getValue() != null) {
5827                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5828                                                          entry.getValue(), entry.getKey());
5829                        }
5830                    }
5831                    if (pkg.mUpgradeKeySets != null) {
5832                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5833                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5834                        }
5835                    }
5836                }
5837            } catch (NullPointerException e) {
5838                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5839            } catch (IllegalArgumentException e) {
5840                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5841            }
5842
5843            int N = pkg.providers.size();
5844            StringBuilder r = null;
5845            int i;
5846            for (i=0; i<N; i++) {
5847                PackageParser.Provider p = pkg.providers.get(i);
5848                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5849                        p.info.processName, pkg.applicationInfo.uid);
5850                mProviders.addProvider(p);
5851                p.syncable = p.info.isSyncable;
5852                if (p.info.authority != null) {
5853                    String names[] = p.info.authority.split(";");
5854                    p.info.authority = null;
5855                    for (int j = 0; j < names.length; j++) {
5856                        if (j == 1 && p.syncable) {
5857                            // We only want the first authority for a provider to possibly be
5858                            // syncable, so if we already added this provider using a different
5859                            // authority clear the syncable flag. We copy the provider before
5860                            // changing it because the mProviders object contains a reference
5861                            // to a provider that we don't want to change.
5862                            // Only do this for the second authority since the resulting provider
5863                            // object can be the same for all future authorities for this provider.
5864                            p = new PackageParser.Provider(p);
5865                            p.syncable = false;
5866                        }
5867                        if (!mProvidersByAuthority.containsKey(names[j])) {
5868                            mProvidersByAuthority.put(names[j], p);
5869                            if (p.info.authority == null) {
5870                                p.info.authority = names[j];
5871                            } else {
5872                                p.info.authority = p.info.authority + ";" + names[j];
5873                            }
5874                            if (DEBUG_PACKAGE_SCANNING) {
5875                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5876                                    Log.d(TAG, "Registered content provider: " + names[j]
5877                                            + ", className = " + p.info.name + ", isSyncable = "
5878                                            + p.info.isSyncable);
5879                            }
5880                        } else {
5881                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5882                            Slog.w(TAG, "Skipping provider name " + names[j] +
5883                                    " (in package " + pkg.applicationInfo.packageName +
5884                                    "): name already used by "
5885                                    + ((other != null && other.getComponentName() != null)
5886                                            ? other.getComponentName().getPackageName() : "?"));
5887                        }
5888                    }
5889                }
5890                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5891                    if (r == null) {
5892                        r = new StringBuilder(256);
5893                    } else {
5894                        r.append(' ');
5895                    }
5896                    r.append(p.info.name);
5897                }
5898            }
5899            if (r != null) {
5900                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5901            }
5902
5903            N = pkg.services.size();
5904            r = null;
5905            for (i=0; i<N; i++) {
5906                PackageParser.Service s = pkg.services.get(i);
5907                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5908                        s.info.processName, pkg.applicationInfo.uid);
5909                mServices.addService(s);
5910                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5911                    if (r == null) {
5912                        r = new StringBuilder(256);
5913                    } else {
5914                        r.append(' ');
5915                    }
5916                    r.append(s.info.name);
5917                }
5918            }
5919            if (r != null) {
5920                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5921            }
5922
5923            N = pkg.receivers.size();
5924            r = null;
5925            for (i=0; i<N; i++) {
5926                PackageParser.Activity a = pkg.receivers.get(i);
5927                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5928                        a.info.processName, pkg.applicationInfo.uid);
5929                mReceivers.addActivity(a, "receiver");
5930                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5931                    if (r == null) {
5932                        r = new StringBuilder(256);
5933                    } else {
5934                        r.append(' ');
5935                    }
5936                    r.append(a.info.name);
5937                }
5938            }
5939            if (r != null) {
5940                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5941            }
5942
5943            N = pkg.activities.size();
5944            r = null;
5945            for (i=0; i<N; i++) {
5946                PackageParser.Activity a = pkg.activities.get(i);
5947                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5948                        a.info.processName, pkg.applicationInfo.uid);
5949                mActivities.addActivity(a, "activity");
5950                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5951                    if (r == null) {
5952                        r = new StringBuilder(256);
5953                    } else {
5954                        r.append(' ');
5955                    }
5956                    r.append(a.info.name);
5957                }
5958            }
5959            if (r != null) {
5960                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5961            }
5962
5963            N = pkg.permissionGroups.size();
5964            r = null;
5965            for (i=0; i<N; i++) {
5966                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5967                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5968                if (cur == null) {
5969                    mPermissionGroups.put(pg.info.name, pg);
5970                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5971                        if (r == null) {
5972                            r = new StringBuilder(256);
5973                        } else {
5974                            r.append(' ');
5975                        }
5976                        r.append(pg.info.name);
5977                    }
5978                } else {
5979                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5980                            + pg.info.packageName + " ignored: original from "
5981                            + cur.info.packageName);
5982                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5983                        if (r == null) {
5984                            r = new StringBuilder(256);
5985                        } else {
5986                            r.append(' ');
5987                        }
5988                        r.append("DUP:");
5989                        r.append(pg.info.name);
5990                    }
5991                }
5992            }
5993            if (r != null) {
5994                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5995            }
5996
5997            N = pkg.permissions.size();
5998            r = null;
5999            for (i=0; i<N; i++) {
6000                PackageParser.Permission p = pkg.permissions.get(i);
6001                HashMap<String, BasePermission> permissionMap =
6002                        p.tree ? mSettings.mPermissionTrees
6003                        : mSettings.mPermissions;
6004                p.group = mPermissionGroups.get(p.info.group);
6005                if (p.info.group == null || p.group != null) {
6006                    BasePermission bp = permissionMap.get(p.info.name);
6007                    if (bp == null) {
6008                        bp = new BasePermission(p.info.name, p.info.packageName,
6009                                BasePermission.TYPE_NORMAL);
6010                        permissionMap.put(p.info.name, bp);
6011                    }
6012                    if (bp.perm == null) {
6013                        if (bp.sourcePackage != null
6014                                && !bp.sourcePackage.equals(p.info.packageName)) {
6015                            // If this is a permission that was formerly defined by a non-system
6016                            // app, but is now defined by a system app (following an upgrade),
6017                            // discard the previous declaration and consider the system's to be
6018                            // canonical.
6019                            if (isSystemApp(p.owner)) {
6020                                String msg = "New decl " + p.owner + " of permission  "
6021                                        + p.info.name + " is system";
6022                                reportSettingsProblem(Log.WARN, msg);
6023                                bp.sourcePackage = null;
6024                            }
6025                        }
6026                        if (bp.sourcePackage == null
6027                                || bp.sourcePackage.equals(p.info.packageName)) {
6028                            BasePermission tree = findPermissionTreeLP(p.info.name);
6029                            if (tree == null
6030                                    || tree.sourcePackage.equals(p.info.packageName)) {
6031                                bp.packageSetting = pkgSetting;
6032                                bp.perm = p;
6033                                bp.uid = pkg.applicationInfo.uid;
6034                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6035                                    if (r == null) {
6036                                        r = new StringBuilder(256);
6037                                    } else {
6038                                        r.append(' ');
6039                                    }
6040                                    r.append(p.info.name);
6041                                }
6042                            } else {
6043                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6044                                        + p.info.packageName + " ignored: base tree "
6045                                        + tree.name + " is from package "
6046                                        + tree.sourcePackage);
6047                            }
6048                        } else {
6049                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6050                                    + p.info.packageName + " ignored: original from "
6051                                    + bp.sourcePackage);
6052                        }
6053                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6054                        if (r == null) {
6055                            r = new StringBuilder(256);
6056                        } else {
6057                            r.append(' ');
6058                        }
6059                        r.append("DUP:");
6060                        r.append(p.info.name);
6061                    }
6062                    if (bp.perm == p) {
6063                        bp.protectionLevel = p.info.protectionLevel;
6064                    }
6065                } else {
6066                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6067                            + p.info.packageName + " ignored: no group "
6068                            + p.group);
6069                }
6070            }
6071            if (r != null) {
6072                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6073            }
6074
6075            N = pkg.instrumentation.size();
6076            r = null;
6077            for (i=0; i<N; i++) {
6078                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6079                a.info.packageName = pkg.applicationInfo.packageName;
6080                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6081                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6082                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6083                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6084                a.info.dataDir = pkg.applicationInfo.dataDir;
6085
6086                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6087                // need other information about the application, like the ABI and what not ?
6088                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6089                mInstrumentation.put(a.getComponentName(), a);
6090                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6091                    if (r == null) {
6092                        r = new StringBuilder(256);
6093                    } else {
6094                        r.append(' ');
6095                    }
6096                    r.append(a.info.name);
6097                }
6098            }
6099            if (r != null) {
6100                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6101            }
6102
6103            if (pkg.protectedBroadcasts != null) {
6104                N = pkg.protectedBroadcasts.size();
6105                for (i=0; i<N; i++) {
6106                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6107                }
6108            }
6109
6110            pkgSetting.setTimeStamp(scanFileTime);
6111
6112            // Create idmap files for pairs of (packages, overlay packages).
6113            // Note: "android", ie framework-res.apk, is handled by native layers.
6114            if (pkg.mOverlayTarget != null) {
6115                // This is an overlay package.
6116                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6117                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6118                        mOverlays.put(pkg.mOverlayTarget,
6119                                new HashMap<String, PackageParser.Package>());
6120                    }
6121                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6122                    map.put(pkg.packageName, pkg);
6123                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6124                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6125                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6126                                "scanPackageLI failed to createIdmap");
6127                    }
6128                }
6129            } else if (mOverlays.containsKey(pkg.packageName) &&
6130                    !pkg.packageName.equals("android")) {
6131                // This is a regular package, with one or more known overlay packages.
6132                createIdmapsForPackageLI(pkg);
6133            }
6134        }
6135
6136        return pkg;
6137    }
6138
6139    /**
6140     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6141     * i.e, so that all packages can be run inside a single process if required.
6142     *
6143     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6144     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6145     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6146     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6147     * updating a package that belongs to a shared user.
6148     *
6149     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6150     * adds unnecessary complexity.
6151     */
6152    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6153            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6154        String requiredInstructionSet = null;
6155        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6156            requiredInstructionSet = VMRuntime.getInstructionSet(
6157                     scannedPackage.applicationInfo.primaryCpuAbi);
6158        }
6159
6160        PackageSetting requirer = null;
6161        for (PackageSetting ps : packagesForUser) {
6162            // If packagesForUser contains scannedPackage, we skip it. This will happen
6163            // when scannedPackage is an update of an existing package. Without this check,
6164            // we will never be able to change the ABI of any package belonging to a shared
6165            // user, even if it's compatible with other packages.
6166            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6167                if (ps.primaryCpuAbiString == null) {
6168                    continue;
6169                }
6170
6171                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6172                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6173                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6174                    // this but there's not much we can do.
6175                    String errorMessage = "Instruction set mismatch, "
6176                            + ((requirer == null) ? "[caller]" : requirer)
6177                            + " requires " + requiredInstructionSet + " whereas " + ps
6178                            + " requires " + instructionSet;
6179                    Slog.w(TAG, errorMessage);
6180                }
6181
6182                if (requiredInstructionSet == null) {
6183                    requiredInstructionSet = instructionSet;
6184                    requirer = ps;
6185                }
6186            }
6187        }
6188
6189        if (requiredInstructionSet != null) {
6190            String adjustedAbi;
6191            if (requirer != null) {
6192                // requirer != null implies that either scannedPackage was null or that scannedPackage
6193                // did not require an ABI, in which case we have to adjust scannedPackage to match
6194                // the ABI of the set (which is the same as requirer's ABI)
6195                adjustedAbi = requirer.primaryCpuAbiString;
6196                if (scannedPackage != null) {
6197                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6198                }
6199            } else {
6200                // requirer == null implies that we're updating all ABIs in the set to
6201                // match scannedPackage.
6202                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6203            }
6204
6205            for (PackageSetting ps : packagesForUser) {
6206                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6207                    if (ps.primaryCpuAbiString != null) {
6208                        continue;
6209                    }
6210
6211                    ps.primaryCpuAbiString = adjustedAbi;
6212                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6213                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6214                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6215
6216                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6217                                deferDexOpt, true) == DEX_OPT_FAILED) {
6218                            ps.primaryCpuAbiString = null;
6219                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6220                            return;
6221                        } else {
6222                            mInstaller.rmdex(ps.codePathString,
6223                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6224                        }
6225                    }
6226                }
6227            }
6228        }
6229    }
6230
6231    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6232        synchronized (mPackages) {
6233            mResolverReplaced = true;
6234            // Set up information for custom user intent resolution activity.
6235            mResolveActivity.applicationInfo = pkg.applicationInfo;
6236            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6237            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6238            mResolveActivity.processName = null;
6239            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6240            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6241                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6242            mResolveActivity.theme = 0;
6243            mResolveActivity.exported = true;
6244            mResolveActivity.enabled = true;
6245            mResolveInfo.activityInfo = mResolveActivity;
6246            mResolveInfo.priority = 0;
6247            mResolveInfo.preferredOrder = 0;
6248            mResolveInfo.match = 0;
6249            mResolveComponentName = mCustomResolverComponentName;
6250            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6251                    mResolveComponentName);
6252        }
6253    }
6254
6255    private static String calculateBundledApkRoot(final String codePathString) {
6256        final File codePath = new File(codePathString);
6257        final File codeRoot;
6258        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6259            codeRoot = Environment.getRootDirectory();
6260        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6261            codeRoot = Environment.getOemDirectory();
6262        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6263            codeRoot = Environment.getVendorDirectory();
6264        } else {
6265            // Unrecognized code path; take its top real segment as the apk root:
6266            // e.g. /something/app/blah.apk => /something
6267            try {
6268                File f = codePath.getCanonicalFile();
6269                File parent = f.getParentFile();    // non-null because codePath is a file
6270                File tmp;
6271                while ((tmp = parent.getParentFile()) != null) {
6272                    f = parent;
6273                    parent = tmp;
6274                }
6275                codeRoot = f;
6276                Slog.w(TAG, "Unrecognized code path "
6277                        + codePath + " - using " + codeRoot);
6278            } catch (IOException e) {
6279                // Can't canonicalize the code path -- shenanigans?
6280                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6281                return Environment.getRootDirectory().getPath();
6282            }
6283        }
6284        return codeRoot.getPath();
6285    }
6286
6287    /**
6288     * Derive and set the location of native libraries for the given package,
6289     * which varies depending on where and how the package was installed.
6290     */
6291    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6292        final ApplicationInfo info = pkg.applicationInfo;
6293        final String codePath = pkg.codePath;
6294        final File codeFile = new File(codePath);
6295        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6296        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6297
6298        info.nativeLibraryRootDir = null;
6299        info.nativeLibraryRootRequiresIsa = false;
6300        info.nativeLibraryDir = null;
6301        info.secondaryNativeLibraryDir = null;
6302
6303        if (isApkFile(codeFile)) {
6304            // Monolithic install
6305            if (bundledApp) {
6306                // If "/system/lib64/apkname" exists, assume that is the per-package
6307                // native library directory to use; otherwise use "/system/lib/apkname".
6308                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6309                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6310                        getPrimaryInstructionSet(info));
6311
6312                // This is a bundled system app so choose the path based on the ABI.
6313                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6314                // is just the default path.
6315                final String apkName = deriveCodePathName(codePath);
6316                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6317                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6318                        apkName).getAbsolutePath();
6319
6320                if (info.secondaryCpuAbi != null) {
6321                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6322                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6323                            secondaryLibDir, apkName).getAbsolutePath();
6324                }
6325            } else if (asecApp) {
6326                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6327                        .getAbsolutePath();
6328            } else {
6329                final String apkName = deriveCodePathName(codePath);
6330                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6331                        .getAbsolutePath();
6332            }
6333
6334            info.nativeLibraryRootRequiresIsa = false;
6335            info.nativeLibraryDir = info.nativeLibraryRootDir;
6336        } else {
6337            // Cluster install
6338            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6339            info.nativeLibraryRootRequiresIsa = true;
6340
6341            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6342                    getPrimaryInstructionSet(info)).getAbsolutePath();
6343
6344            if (info.secondaryCpuAbi != null) {
6345                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6346                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6347            }
6348        }
6349    }
6350
6351    /**
6352     * Calculate the abis and roots for a bundled app. These can uniquely
6353     * be determined from the contents of the system partition, i.e whether
6354     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6355     * of this information, and instead assume that the system was built
6356     * sensibly.
6357     */
6358    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6359                                           PackageSetting pkgSetting) {
6360        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6361
6362        // If "/system/lib64/apkname" exists, assume that is the per-package
6363        // native library directory to use; otherwise use "/system/lib/apkname".
6364        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6365        setBundledAppAbi(pkg, apkRoot, apkName);
6366        // pkgSetting might be null during rescan following uninstall of updates
6367        // to a bundled app, so accommodate that possibility.  The settings in
6368        // that case will be established later from the parsed package.
6369        //
6370        // If the settings aren't null, sync them up with what we've just derived.
6371        // note that apkRoot isn't stored in the package settings.
6372        if (pkgSetting != null) {
6373            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6374            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6375        }
6376    }
6377
6378    /**
6379     * Deduces the ABI of a bundled app and sets the relevant fields on the
6380     * parsed pkg object.
6381     *
6382     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6383     *        under which system libraries are installed.
6384     * @param apkName the name of the installed package.
6385     */
6386    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6387        final File codeFile = new File(pkg.codePath);
6388
6389        final boolean has64BitLibs;
6390        final boolean has32BitLibs;
6391        if (isApkFile(codeFile)) {
6392            // Monolithic install
6393            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6394            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6395        } else {
6396            // Cluster install
6397            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6398            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6399                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6400                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6401                has64BitLibs = (new File(rootDir, isa)).exists();
6402            } else {
6403                has64BitLibs = false;
6404            }
6405            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6406                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6407                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6408                has32BitLibs = (new File(rootDir, isa)).exists();
6409            } else {
6410                has32BitLibs = false;
6411            }
6412        }
6413
6414        if (has64BitLibs && !has32BitLibs) {
6415            // The package has 64 bit libs, but not 32 bit libs. Its primary
6416            // ABI should be 64 bit. We can safely assume here that the bundled
6417            // native libraries correspond to the most preferred ABI in the list.
6418
6419            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6420            pkg.applicationInfo.secondaryCpuAbi = null;
6421        } else if (has32BitLibs && !has64BitLibs) {
6422            // The package has 32 bit libs but not 64 bit libs. Its primary
6423            // ABI should be 32 bit.
6424
6425            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6426            pkg.applicationInfo.secondaryCpuAbi = null;
6427        } else if (has32BitLibs && has64BitLibs) {
6428            // The application has both 64 and 32 bit bundled libraries. We check
6429            // here that the app declares multiArch support, and warn if it doesn't.
6430            //
6431            // We will be lenient here and record both ABIs. The primary will be the
6432            // ABI that's higher on the list, i.e, a device that's configured to prefer
6433            // 64 bit apps will see a 64 bit primary ABI,
6434
6435            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6436                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6437            }
6438
6439            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6440                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6441                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6442            } else {
6443                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6444                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6445            }
6446        } else {
6447            pkg.applicationInfo.primaryCpuAbi = null;
6448            pkg.applicationInfo.secondaryCpuAbi = null;
6449        }
6450    }
6451
6452    private void killApplication(String pkgName, int appId, String reason) {
6453        // Request the ActivityManager to kill the process(only for existing packages)
6454        // so that we do not end up in a confused state while the user is still using the older
6455        // version of the application while the new one gets installed.
6456        IActivityManager am = ActivityManagerNative.getDefault();
6457        if (am != null) {
6458            try {
6459                am.killApplicationWithAppId(pkgName, appId, reason);
6460            } catch (RemoteException e) {
6461            }
6462        }
6463    }
6464
6465    void removePackageLI(PackageSetting ps, boolean chatty) {
6466        if (DEBUG_INSTALL) {
6467            if (chatty)
6468                Log.d(TAG, "Removing package " + ps.name);
6469        }
6470
6471        // writer
6472        synchronized (mPackages) {
6473            mPackages.remove(ps.name);
6474            final PackageParser.Package pkg = ps.pkg;
6475            if (pkg != null) {
6476                cleanPackageDataStructuresLILPw(pkg, chatty);
6477            }
6478        }
6479    }
6480
6481    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6482        if (DEBUG_INSTALL) {
6483            if (chatty)
6484                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6485        }
6486
6487        // writer
6488        synchronized (mPackages) {
6489            mPackages.remove(pkg.applicationInfo.packageName);
6490            cleanPackageDataStructuresLILPw(pkg, chatty);
6491        }
6492    }
6493
6494    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6495        int N = pkg.providers.size();
6496        StringBuilder r = null;
6497        int i;
6498        for (i=0; i<N; i++) {
6499            PackageParser.Provider p = pkg.providers.get(i);
6500            mProviders.removeProvider(p);
6501            if (p.info.authority == null) {
6502
6503                /* There was another ContentProvider with this authority when
6504                 * this app was installed so this authority is null,
6505                 * Ignore it as we don't have to unregister the provider.
6506                 */
6507                continue;
6508            }
6509            String names[] = p.info.authority.split(";");
6510            for (int j = 0; j < names.length; j++) {
6511                if (mProvidersByAuthority.get(names[j]) == p) {
6512                    mProvidersByAuthority.remove(names[j]);
6513                    if (DEBUG_REMOVE) {
6514                        if (chatty)
6515                            Log.d(TAG, "Unregistered content provider: " + names[j]
6516                                    + ", className = " + p.info.name + ", isSyncable = "
6517                                    + p.info.isSyncable);
6518                    }
6519                }
6520            }
6521            if (DEBUG_REMOVE && chatty) {
6522                if (r == null) {
6523                    r = new StringBuilder(256);
6524                } else {
6525                    r.append(' ');
6526                }
6527                r.append(p.info.name);
6528            }
6529        }
6530        if (r != null) {
6531            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6532        }
6533
6534        N = pkg.services.size();
6535        r = null;
6536        for (i=0; i<N; i++) {
6537            PackageParser.Service s = pkg.services.get(i);
6538            mServices.removeService(s);
6539            if (chatty) {
6540                if (r == null) {
6541                    r = new StringBuilder(256);
6542                } else {
6543                    r.append(' ');
6544                }
6545                r.append(s.info.name);
6546            }
6547        }
6548        if (r != null) {
6549            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6550        }
6551
6552        N = pkg.receivers.size();
6553        r = null;
6554        for (i=0; i<N; i++) {
6555            PackageParser.Activity a = pkg.receivers.get(i);
6556            mReceivers.removeActivity(a, "receiver");
6557            if (DEBUG_REMOVE && chatty) {
6558                if (r == null) {
6559                    r = new StringBuilder(256);
6560                } else {
6561                    r.append(' ');
6562                }
6563                r.append(a.info.name);
6564            }
6565        }
6566        if (r != null) {
6567            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6568        }
6569
6570        N = pkg.activities.size();
6571        r = null;
6572        for (i=0; i<N; i++) {
6573            PackageParser.Activity a = pkg.activities.get(i);
6574            mActivities.removeActivity(a, "activity");
6575            if (DEBUG_REMOVE && chatty) {
6576                if (r == null) {
6577                    r = new StringBuilder(256);
6578                } else {
6579                    r.append(' ');
6580                }
6581                r.append(a.info.name);
6582            }
6583        }
6584        if (r != null) {
6585            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6586        }
6587
6588        N = pkg.permissions.size();
6589        r = null;
6590        for (i=0; i<N; i++) {
6591            PackageParser.Permission p = pkg.permissions.get(i);
6592            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6593            if (bp == null) {
6594                bp = mSettings.mPermissionTrees.get(p.info.name);
6595            }
6596            if (bp != null && bp.perm == p) {
6597                bp.perm = null;
6598                if (DEBUG_REMOVE && chatty) {
6599                    if (r == null) {
6600                        r = new StringBuilder(256);
6601                    } else {
6602                        r.append(' ');
6603                    }
6604                    r.append(p.info.name);
6605                }
6606            }
6607            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6608                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6609                if (appOpPerms != null) {
6610                    appOpPerms.remove(pkg.packageName);
6611                }
6612            }
6613        }
6614        if (r != null) {
6615            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6616        }
6617
6618        N = pkg.requestedPermissions.size();
6619        r = null;
6620        for (i=0; i<N; i++) {
6621            String perm = pkg.requestedPermissions.get(i);
6622            BasePermission bp = mSettings.mPermissions.get(perm);
6623            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6624                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6625                if (appOpPerms != null) {
6626                    appOpPerms.remove(pkg.packageName);
6627                    if (appOpPerms.isEmpty()) {
6628                        mAppOpPermissionPackages.remove(perm);
6629                    }
6630                }
6631            }
6632        }
6633        if (r != null) {
6634            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6635        }
6636
6637        N = pkg.instrumentation.size();
6638        r = null;
6639        for (i=0; i<N; i++) {
6640            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6641            mInstrumentation.remove(a.getComponentName());
6642            if (DEBUG_REMOVE && chatty) {
6643                if (r == null) {
6644                    r = new StringBuilder(256);
6645                } else {
6646                    r.append(' ');
6647                }
6648                r.append(a.info.name);
6649            }
6650        }
6651        if (r != null) {
6652            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6653        }
6654
6655        r = null;
6656        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6657            // Only system apps can hold shared libraries.
6658            if (pkg.libraryNames != null) {
6659                for (i=0; i<pkg.libraryNames.size(); i++) {
6660                    String name = pkg.libraryNames.get(i);
6661                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6662                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6663                        mSharedLibraries.remove(name);
6664                        if (DEBUG_REMOVE && chatty) {
6665                            if (r == null) {
6666                                r = new StringBuilder(256);
6667                            } else {
6668                                r.append(' ');
6669                            }
6670                            r.append(name);
6671                        }
6672                    }
6673                }
6674            }
6675        }
6676        if (r != null) {
6677            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6678        }
6679    }
6680
6681    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6682        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6683            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6684                return true;
6685            }
6686        }
6687        return false;
6688    }
6689
6690    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6691    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6692    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6693
6694    private void updatePermissionsLPw(String changingPkg,
6695            PackageParser.Package pkgInfo, int flags) {
6696        // Make sure there are no dangling permission trees.
6697        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6698        while (it.hasNext()) {
6699            final BasePermission bp = it.next();
6700            if (bp.packageSetting == null) {
6701                // We may not yet have parsed the package, so just see if
6702                // we still know about its settings.
6703                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6704            }
6705            if (bp.packageSetting == null) {
6706                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6707                        + " from package " + bp.sourcePackage);
6708                it.remove();
6709            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6710                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6711                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6712                            + " from package " + bp.sourcePackage);
6713                    flags |= UPDATE_PERMISSIONS_ALL;
6714                    it.remove();
6715                }
6716            }
6717        }
6718
6719        // Make sure all dynamic permissions have been assigned to a package,
6720        // and make sure there are no dangling permissions.
6721        it = mSettings.mPermissions.values().iterator();
6722        while (it.hasNext()) {
6723            final BasePermission bp = it.next();
6724            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6725                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6726                        + bp.name + " pkg=" + bp.sourcePackage
6727                        + " info=" + bp.pendingInfo);
6728                if (bp.packageSetting == null && bp.pendingInfo != null) {
6729                    final BasePermission tree = findPermissionTreeLP(bp.name);
6730                    if (tree != null && tree.perm != null) {
6731                        bp.packageSetting = tree.packageSetting;
6732                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6733                                new PermissionInfo(bp.pendingInfo));
6734                        bp.perm.info.packageName = tree.perm.info.packageName;
6735                        bp.perm.info.name = bp.name;
6736                        bp.uid = tree.uid;
6737                    }
6738                }
6739            }
6740            if (bp.packageSetting == null) {
6741                // We may not yet have parsed the package, so just see if
6742                // we still know about its settings.
6743                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6744            }
6745            if (bp.packageSetting == null) {
6746                Slog.w(TAG, "Removing dangling permission: " + bp.name
6747                        + " from package " + bp.sourcePackage);
6748                it.remove();
6749            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6750                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6751                    Slog.i(TAG, "Removing old permission: " + bp.name
6752                            + " from package " + bp.sourcePackage);
6753                    flags |= UPDATE_PERMISSIONS_ALL;
6754                    it.remove();
6755                }
6756            }
6757        }
6758
6759        // Now update the permissions for all packages, in particular
6760        // replace the granted permissions of the system packages.
6761        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6762            for (PackageParser.Package pkg : mPackages.values()) {
6763                if (pkg != pkgInfo) {
6764                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6765                }
6766            }
6767        }
6768
6769        if (pkgInfo != null) {
6770            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6771        }
6772    }
6773
6774    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6775        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6776        if (ps == null) {
6777            return;
6778        }
6779        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6780        HashSet<String> origPermissions = gp.grantedPermissions;
6781        boolean changedPermission = false;
6782
6783        if (replace) {
6784            ps.permissionsFixed = false;
6785            if (gp == ps) {
6786                origPermissions = new HashSet<String>(gp.grantedPermissions);
6787                gp.grantedPermissions.clear();
6788                gp.gids = mGlobalGids;
6789            }
6790        }
6791
6792        if (gp.gids == null) {
6793            gp.gids = mGlobalGids;
6794        }
6795
6796        final int N = pkg.requestedPermissions.size();
6797        for (int i=0; i<N; i++) {
6798            final String name = pkg.requestedPermissions.get(i);
6799            final boolean required = pkg.requestedPermissionsRequired.get(i);
6800            final BasePermission bp = mSettings.mPermissions.get(name);
6801            if (DEBUG_INSTALL) {
6802                if (gp != ps) {
6803                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6804                }
6805            }
6806
6807            if (bp == null || bp.packageSetting == null) {
6808                Slog.w(TAG, "Unknown permission " + name
6809                        + " in package " + pkg.packageName);
6810                continue;
6811            }
6812
6813            final String perm = bp.name;
6814            boolean allowed;
6815            boolean allowedSig = false;
6816            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6817                // Keep track of app op permissions.
6818                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6819                if (pkgs == null) {
6820                    pkgs = new ArraySet<>();
6821                    mAppOpPermissionPackages.put(bp.name, pkgs);
6822                }
6823                pkgs.add(pkg.packageName);
6824            }
6825            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6826            if (level == PermissionInfo.PROTECTION_NORMAL
6827                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6828                // We grant a normal or dangerous permission if any of the following
6829                // are true:
6830                // 1) The permission is required
6831                // 2) The permission is optional, but was granted in the past
6832                // 3) The permission is optional, but was requested by an
6833                //    app in /system (not /data)
6834                //
6835                // Otherwise, reject the permission.
6836                allowed = (required || origPermissions.contains(perm)
6837                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6838            } else if (bp.packageSetting == null) {
6839                // This permission is invalid; skip it.
6840                allowed = false;
6841            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6842                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6843                if (allowed) {
6844                    allowedSig = true;
6845                }
6846            } else {
6847                allowed = false;
6848            }
6849            if (DEBUG_INSTALL) {
6850                if (gp != ps) {
6851                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6852                }
6853            }
6854            if (allowed) {
6855                if (!isSystemApp(ps) && ps.permissionsFixed) {
6856                    // If this is an existing, non-system package, then
6857                    // we can't add any new permissions to it.
6858                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6859                        // Except...  if this is a permission that was added
6860                        // to the platform (note: need to only do this when
6861                        // updating the platform).
6862                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6863                    }
6864                }
6865                if (allowed) {
6866                    if (!gp.grantedPermissions.contains(perm)) {
6867                        changedPermission = true;
6868                        gp.grantedPermissions.add(perm);
6869                        gp.gids = appendInts(gp.gids, bp.gids);
6870                    } else if (!ps.haveGids) {
6871                        gp.gids = appendInts(gp.gids, bp.gids);
6872                    }
6873                } else {
6874                    Slog.w(TAG, "Not granting permission " + perm
6875                            + " to package " + pkg.packageName
6876                            + " because it was previously installed without");
6877                }
6878            } else {
6879                if (gp.grantedPermissions.remove(perm)) {
6880                    changedPermission = true;
6881                    gp.gids = removeInts(gp.gids, bp.gids);
6882                    Slog.i(TAG, "Un-granting permission " + perm
6883                            + " from package " + pkg.packageName
6884                            + " (protectionLevel=" + bp.protectionLevel
6885                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6886                            + ")");
6887                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6888                    // Don't print warning for app op permissions, since it is fine for them
6889                    // not to be granted, there is a UI for the user to decide.
6890                    Slog.w(TAG, "Not granting permission " + perm
6891                            + " to package " + pkg.packageName
6892                            + " (protectionLevel=" + bp.protectionLevel
6893                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6894                            + ")");
6895                }
6896            }
6897        }
6898
6899        if ((changedPermission || replace) && !ps.permissionsFixed &&
6900                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6901            // This is the first that we have heard about this package, so the
6902            // permissions we have now selected are fixed until explicitly
6903            // changed.
6904            ps.permissionsFixed = true;
6905        }
6906        ps.haveGids = true;
6907    }
6908
6909    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6910        boolean allowed = false;
6911        final int NP = PackageParser.NEW_PERMISSIONS.length;
6912        for (int ip=0; ip<NP; ip++) {
6913            final PackageParser.NewPermissionInfo npi
6914                    = PackageParser.NEW_PERMISSIONS[ip];
6915            if (npi.name.equals(perm)
6916                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6917                allowed = true;
6918                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6919                        + pkg.packageName);
6920                break;
6921            }
6922        }
6923        return allowed;
6924    }
6925
6926    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6927                                          BasePermission bp, HashSet<String> origPermissions) {
6928        boolean allowed;
6929        allowed = (compareSignatures(
6930                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6931                        == PackageManager.SIGNATURE_MATCH)
6932                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6933                        == PackageManager.SIGNATURE_MATCH);
6934        if (!allowed && (bp.protectionLevel
6935                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6936            if (isSystemApp(pkg)) {
6937                // For updated system applications, a system permission
6938                // is granted only if it had been defined by the original application.
6939                if (isUpdatedSystemApp(pkg)) {
6940                    final PackageSetting sysPs = mSettings
6941                            .getDisabledSystemPkgLPr(pkg.packageName);
6942                    final GrantedPermissions origGp = sysPs.sharedUser != null
6943                            ? sysPs.sharedUser : sysPs;
6944
6945                    if (origGp.grantedPermissions.contains(perm)) {
6946                        // If the original was granted this permission, we take
6947                        // that grant decision as read and propagate it to the
6948                        // update.
6949                        allowed = true;
6950                    } else {
6951                        // The system apk may have been updated with an older
6952                        // version of the one on the data partition, but which
6953                        // granted a new system permission that it didn't have
6954                        // before.  In this case we do want to allow the app to
6955                        // now get the new permission if the ancestral apk is
6956                        // privileged to get it.
6957                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6958                            for (int j=0;
6959                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6960                                if (perm.equals(
6961                                        sysPs.pkg.requestedPermissions.get(j))) {
6962                                    allowed = true;
6963                                    break;
6964                                }
6965                            }
6966                        }
6967                    }
6968                } else {
6969                    allowed = isPrivilegedApp(pkg);
6970                }
6971            }
6972        }
6973        if (!allowed && (bp.protectionLevel
6974                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6975            // For development permissions, a development permission
6976            // is granted only if it was already granted.
6977            allowed = origPermissions.contains(perm);
6978        }
6979        return allowed;
6980    }
6981
6982    final class ActivityIntentResolver
6983            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6984        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6985                boolean defaultOnly, int userId) {
6986            if (!sUserManager.exists(userId)) return null;
6987            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6988            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6989        }
6990
6991        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6992                int userId) {
6993            if (!sUserManager.exists(userId)) return null;
6994            mFlags = flags;
6995            return super.queryIntent(intent, resolvedType,
6996                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6997        }
6998
6999        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7000                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7001            if (!sUserManager.exists(userId)) return null;
7002            if (packageActivities == null) {
7003                return null;
7004            }
7005            mFlags = flags;
7006            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7007            final int N = packageActivities.size();
7008            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7009                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7010
7011            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7012            for (int i = 0; i < N; ++i) {
7013                intentFilters = packageActivities.get(i).intents;
7014                if (intentFilters != null && intentFilters.size() > 0) {
7015                    PackageParser.ActivityIntentInfo[] array =
7016                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7017                    intentFilters.toArray(array);
7018                    listCut.add(array);
7019                }
7020            }
7021            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7022        }
7023
7024        public final void addActivity(PackageParser.Activity a, String type) {
7025            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7026            mActivities.put(a.getComponentName(), a);
7027            if (DEBUG_SHOW_INFO)
7028                Log.v(
7029                TAG, "  " + type + " " +
7030                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7031            if (DEBUG_SHOW_INFO)
7032                Log.v(TAG, "    Class=" + a.info.name);
7033            final int NI = a.intents.size();
7034            for (int j=0; j<NI; j++) {
7035                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7036                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7037                    intent.setPriority(0);
7038                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7039                            + a.className + " with priority > 0, forcing to 0");
7040                }
7041                if (DEBUG_SHOW_INFO) {
7042                    Log.v(TAG, "    IntentFilter:");
7043                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7044                }
7045                if (!intent.debugCheck()) {
7046                    Log.w(TAG, "==> For Activity " + a.info.name);
7047                }
7048                addFilter(intent);
7049            }
7050        }
7051
7052        public final void removeActivity(PackageParser.Activity a, String type) {
7053            mActivities.remove(a.getComponentName());
7054            if (DEBUG_SHOW_INFO) {
7055                Log.v(TAG, "  " + type + " "
7056                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7057                                : a.info.name) + ":");
7058                Log.v(TAG, "    Class=" + a.info.name);
7059            }
7060            final int NI = a.intents.size();
7061            for (int j=0; j<NI; j++) {
7062                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7063                if (DEBUG_SHOW_INFO) {
7064                    Log.v(TAG, "    IntentFilter:");
7065                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7066                }
7067                removeFilter(intent);
7068            }
7069        }
7070
7071        @Override
7072        protected boolean allowFilterResult(
7073                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7074            ActivityInfo filterAi = filter.activity.info;
7075            for (int i=dest.size()-1; i>=0; i--) {
7076                ActivityInfo destAi = dest.get(i).activityInfo;
7077                if (destAi.name == filterAi.name
7078                        && destAi.packageName == filterAi.packageName) {
7079                    return false;
7080                }
7081            }
7082            return true;
7083        }
7084
7085        @Override
7086        protected ActivityIntentInfo[] newArray(int size) {
7087            return new ActivityIntentInfo[size];
7088        }
7089
7090        @Override
7091        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7092            if (!sUserManager.exists(userId)) return true;
7093            PackageParser.Package p = filter.activity.owner;
7094            if (p != null) {
7095                PackageSetting ps = (PackageSetting)p.mExtras;
7096                if (ps != null) {
7097                    // System apps are never considered stopped for purposes of
7098                    // filtering, because there may be no way for the user to
7099                    // actually re-launch them.
7100                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7101                            && ps.getStopped(userId);
7102                }
7103            }
7104            return false;
7105        }
7106
7107        @Override
7108        protected boolean isPackageForFilter(String packageName,
7109                PackageParser.ActivityIntentInfo info) {
7110            return packageName.equals(info.activity.owner.packageName);
7111        }
7112
7113        @Override
7114        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7115                int match, int userId) {
7116            if (!sUserManager.exists(userId)) return null;
7117            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7118                return null;
7119            }
7120            final PackageParser.Activity activity = info.activity;
7121            if (mSafeMode && (activity.info.applicationInfo.flags
7122                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7123                return null;
7124            }
7125            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7126            if (ps == null) {
7127                return null;
7128            }
7129            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7130                    ps.readUserState(userId), userId);
7131            if (ai == null) {
7132                return null;
7133            }
7134            final ResolveInfo res = new ResolveInfo();
7135            res.activityInfo = ai;
7136            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7137                res.filter = info;
7138            }
7139            res.priority = info.getPriority();
7140            res.preferredOrder = activity.owner.mPreferredOrder;
7141            //System.out.println("Result: " + res.activityInfo.className +
7142            //                   " = " + res.priority);
7143            res.match = match;
7144            res.isDefault = info.hasDefault;
7145            res.labelRes = info.labelRes;
7146            res.nonLocalizedLabel = info.nonLocalizedLabel;
7147            if (userNeedsBadging(userId)) {
7148                res.noResourceId = true;
7149            } else {
7150                res.icon = info.icon;
7151            }
7152            res.system = isSystemApp(res.activityInfo.applicationInfo);
7153            return res;
7154        }
7155
7156        @Override
7157        protected void sortResults(List<ResolveInfo> results) {
7158            Collections.sort(results, mResolvePrioritySorter);
7159        }
7160
7161        @Override
7162        protected void dumpFilter(PrintWriter out, String prefix,
7163                PackageParser.ActivityIntentInfo filter) {
7164            out.print(prefix); out.print(
7165                    Integer.toHexString(System.identityHashCode(filter.activity)));
7166                    out.print(' ');
7167                    filter.activity.printComponentShortName(out);
7168                    out.print(" filter ");
7169                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7170        }
7171
7172//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7173//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7174//            final List<ResolveInfo> retList = Lists.newArrayList();
7175//            while (i.hasNext()) {
7176//                final ResolveInfo resolveInfo = i.next();
7177//                if (isEnabledLP(resolveInfo.activityInfo)) {
7178//                    retList.add(resolveInfo);
7179//                }
7180//            }
7181//            return retList;
7182//        }
7183
7184        // Keys are String (activity class name), values are Activity.
7185        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7186                = new HashMap<ComponentName, PackageParser.Activity>();
7187        private int mFlags;
7188    }
7189
7190    private final class ServiceIntentResolver
7191            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7192        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7193                boolean defaultOnly, int userId) {
7194            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7195            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7196        }
7197
7198        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7199                int userId) {
7200            if (!sUserManager.exists(userId)) return null;
7201            mFlags = flags;
7202            return super.queryIntent(intent, resolvedType,
7203                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7204        }
7205
7206        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7207                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7208            if (!sUserManager.exists(userId)) return null;
7209            if (packageServices == null) {
7210                return null;
7211            }
7212            mFlags = flags;
7213            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7214            final int N = packageServices.size();
7215            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7216                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7217
7218            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7219            for (int i = 0; i < N; ++i) {
7220                intentFilters = packageServices.get(i).intents;
7221                if (intentFilters != null && intentFilters.size() > 0) {
7222                    PackageParser.ServiceIntentInfo[] array =
7223                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7224                    intentFilters.toArray(array);
7225                    listCut.add(array);
7226                }
7227            }
7228            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7229        }
7230
7231        public final void addService(PackageParser.Service s) {
7232            mServices.put(s.getComponentName(), s);
7233            if (DEBUG_SHOW_INFO) {
7234                Log.v(TAG, "  "
7235                        + (s.info.nonLocalizedLabel != null
7236                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7237                Log.v(TAG, "    Class=" + s.info.name);
7238            }
7239            final int NI = s.intents.size();
7240            int j;
7241            for (j=0; j<NI; j++) {
7242                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7243                if (DEBUG_SHOW_INFO) {
7244                    Log.v(TAG, "    IntentFilter:");
7245                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7246                }
7247                if (!intent.debugCheck()) {
7248                    Log.w(TAG, "==> For Service " + s.info.name);
7249                }
7250                addFilter(intent);
7251            }
7252        }
7253
7254        public final void removeService(PackageParser.Service s) {
7255            mServices.remove(s.getComponentName());
7256            if (DEBUG_SHOW_INFO) {
7257                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7258                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7259                Log.v(TAG, "    Class=" + s.info.name);
7260            }
7261            final int NI = s.intents.size();
7262            int j;
7263            for (j=0; j<NI; j++) {
7264                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7265                if (DEBUG_SHOW_INFO) {
7266                    Log.v(TAG, "    IntentFilter:");
7267                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7268                }
7269                removeFilter(intent);
7270            }
7271        }
7272
7273        @Override
7274        protected boolean allowFilterResult(
7275                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7276            ServiceInfo filterSi = filter.service.info;
7277            for (int i=dest.size()-1; i>=0; i--) {
7278                ServiceInfo destAi = dest.get(i).serviceInfo;
7279                if (destAi.name == filterSi.name
7280                        && destAi.packageName == filterSi.packageName) {
7281                    return false;
7282                }
7283            }
7284            return true;
7285        }
7286
7287        @Override
7288        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7289            return new PackageParser.ServiceIntentInfo[size];
7290        }
7291
7292        @Override
7293        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7294            if (!sUserManager.exists(userId)) return true;
7295            PackageParser.Package p = filter.service.owner;
7296            if (p != null) {
7297                PackageSetting ps = (PackageSetting)p.mExtras;
7298                if (ps != null) {
7299                    // System apps are never considered stopped for purposes of
7300                    // filtering, because there may be no way for the user to
7301                    // actually re-launch them.
7302                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7303                            && ps.getStopped(userId);
7304                }
7305            }
7306            return false;
7307        }
7308
7309        @Override
7310        protected boolean isPackageForFilter(String packageName,
7311                PackageParser.ServiceIntentInfo info) {
7312            return packageName.equals(info.service.owner.packageName);
7313        }
7314
7315        @Override
7316        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7317                int match, int userId) {
7318            if (!sUserManager.exists(userId)) return null;
7319            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7320            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7321                return null;
7322            }
7323            final PackageParser.Service service = info.service;
7324            if (mSafeMode && (service.info.applicationInfo.flags
7325                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7326                return null;
7327            }
7328            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7329            if (ps == null) {
7330                return null;
7331            }
7332            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7333                    ps.readUserState(userId), userId);
7334            if (si == null) {
7335                return null;
7336            }
7337            final ResolveInfo res = new ResolveInfo();
7338            res.serviceInfo = si;
7339            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7340                res.filter = filter;
7341            }
7342            res.priority = info.getPriority();
7343            res.preferredOrder = service.owner.mPreferredOrder;
7344            //System.out.println("Result: " + res.activityInfo.className +
7345            //                   " = " + res.priority);
7346            res.match = match;
7347            res.isDefault = info.hasDefault;
7348            res.labelRes = info.labelRes;
7349            res.nonLocalizedLabel = info.nonLocalizedLabel;
7350            res.icon = info.icon;
7351            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7352            return res;
7353        }
7354
7355        @Override
7356        protected void sortResults(List<ResolveInfo> results) {
7357            Collections.sort(results, mResolvePrioritySorter);
7358        }
7359
7360        @Override
7361        protected void dumpFilter(PrintWriter out, String prefix,
7362                PackageParser.ServiceIntentInfo filter) {
7363            out.print(prefix); out.print(
7364                    Integer.toHexString(System.identityHashCode(filter.service)));
7365                    out.print(' ');
7366                    filter.service.printComponentShortName(out);
7367                    out.print(" filter ");
7368                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7369        }
7370
7371//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7372//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7373//            final List<ResolveInfo> retList = Lists.newArrayList();
7374//            while (i.hasNext()) {
7375//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7376//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7377//                    retList.add(resolveInfo);
7378//                }
7379//            }
7380//            return retList;
7381//        }
7382
7383        // Keys are String (activity class name), values are Activity.
7384        private final HashMap<ComponentName, PackageParser.Service> mServices
7385                = new HashMap<ComponentName, PackageParser.Service>();
7386        private int mFlags;
7387    };
7388
7389    private final class ProviderIntentResolver
7390            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7391        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7392                boolean defaultOnly, int userId) {
7393            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7394            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7395        }
7396
7397        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7398                int userId) {
7399            if (!sUserManager.exists(userId))
7400                return null;
7401            mFlags = flags;
7402            return super.queryIntent(intent, resolvedType,
7403                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7404        }
7405
7406        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7407                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7408            if (!sUserManager.exists(userId))
7409                return null;
7410            if (packageProviders == null) {
7411                return null;
7412            }
7413            mFlags = flags;
7414            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7415            final int N = packageProviders.size();
7416            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7417                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7418
7419            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7420            for (int i = 0; i < N; ++i) {
7421                intentFilters = packageProviders.get(i).intents;
7422                if (intentFilters != null && intentFilters.size() > 0) {
7423                    PackageParser.ProviderIntentInfo[] array =
7424                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7425                    intentFilters.toArray(array);
7426                    listCut.add(array);
7427                }
7428            }
7429            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7430        }
7431
7432        public final void addProvider(PackageParser.Provider p) {
7433            if (mProviders.containsKey(p.getComponentName())) {
7434                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7435                return;
7436            }
7437
7438            mProviders.put(p.getComponentName(), p);
7439            if (DEBUG_SHOW_INFO) {
7440                Log.v(TAG, "  "
7441                        + (p.info.nonLocalizedLabel != null
7442                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7443                Log.v(TAG, "    Class=" + p.info.name);
7444            }
7445            final int NI = p.intents.size();
7446            int j;
7447            for (j = 0; j < NI; j++) {
7448                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7449                if (DEBUG_SHOW_INFO) {
7450                    Log.v(TAG, "    IntentFilter:");
7451                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7452                }
7453                if (!intent.debugCheck()) {
7454                    Log.w(TAG, "==> For Provider " + p.info.name);
7455                }
7456                addFilter(intent);
7457            }
7458        }
7459
7460        public final void removeProvider(PackageParser.Provider p) {
7461            mProviders.remove(p.getComponentName());
7462            if (DEBUG_SHOW_INFO) {
7463                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7464                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7465                Log.v(TAG, "    Class=" + p.info.name);
7466            }
7467            final int NI = p.intents.size();
7468            int j;
7469            for (j = 0; j < NI; j++) {
7470                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7471                if (DEBUG_SHOW_INFO) {
7472                    Log.v(TAG, "    IntentFilter:");
7473                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7474                }
7475                removeFilter(intent);
7476            }
7477        }
7478
7479        @Override
7480        protected boolean allowFilterResult(
7481                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7482            ProviderInfo filterPi = filter.provider.info;
7483            for (int i = dest.size() - 1; i >= 0; i--) {
7484                ProviderInfo destPi = dest.get(i).providerInfo;
7485                if (destPi.name == filterPi.name
7486                        && destPi.packageName == filterPi.packageName) {
7487                    return false;
7488                }
7489            }
7490            return true;
7491        }
7492
7493        @Override
7494        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7495            return new PackageParser.ProviderIntentInfo[size];
7496        }
7497
7498        @Override
7499        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7500            if (!sUserManager.exists(userId))
7501                return true;
7502            PackageParser.Package p = filter.provider.owner;
7503            if (p != null) {
7504                PackageSetting ps = (PackageSetting) p.mExtras;
7505                if (ps != null) {
7506                    // System apps are never considered stopped for purposes of
7507                    // filtering, because there may be no way for the user to
7508                    // actually re-launch them.
7509                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7510                            && ps.getStopped(userId);
7511                }
7512            }
7513            return false;
7514        }
7515
7516        @Override
7517        protected boolean isPackageForFilter(String packageName,
7518                PackageParser.ProviderIntentInfo info) {
7519            return packageName.equals(info.provider.owner.packageName);
7520        }
7521
7522        @Override
7523        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7524                int match, int userId) {
7525            if (!sUserManager.exists(userId))
7526                return null;
7527            final PackageParser.ProviderIntentInfo info = filter;
7528            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7529                return null;
7530            }
7531            final PackageParser.Provider provider = info.provider;
7532            if (mSafeMode && (provider.info.applicationInfo.flags
7533                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7534                return null;
7535            }
7536            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7537            if (ps == null) {
7538                return null;
7539            }
7540            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7541                    ps.readUserState(userId), userId);
7542            if (pi == null) {
7543                return null;
7544            }
7545            final ResolveInfo res = new ResolveInfo();
7546            res.providerInfo = pi;
7547            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7548                res.filter = filter;
7549            }
7550            res.priority = info.getPriority();
7551            res.preferredOrder = provider.owner.mPreferredOrder;
7552            res.match = match;
7553            res.isDefault = info.hasDefault;
7554            res.labelRes = info.labelRes;
7555            res.nonLocalizedLabel = info.nonLocalizedLabel;
7556            res.icon = info.icon;
7557            res.system = isSystemApp(res.providerInfo.applicationInfo);
7558            return res;
7559        }
7560
7561        @Override
7562        protected void sortResults(List<ResolveInfo> results) {
7563            Collections.sort(results, mResolvePrioritySorter);
7564        }
7565
7566        @Override
7567        protected void dumpFilter(PrintWriter out, String prefix,
7568                PackageParser.ProviderIntentInfo filter) {
7569            out.print(prefix);
7570            out.print(
7571                    Integer.toHexString(System.identityHashCode(filter.provider)));
7572            out.print(' ');
7573            filter.provider.printComponentShortName(out);
7574            out.print(" filter ");
7575            out.println(Integer.toHexString(System.identityHashCode(filter)));
7576        }
7577
7578        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7579                = new HashMap<ComponentName, PackageParser.Provider>();
7580        private int mFlags;
7581    };
7582
7583    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7584            new Comparator<ResolveInfo>() {
7585        public int compare(ResolveInfo r1, ResolveInfo r2) {
7586            int v1 = r1.priority;
7587            int v2 = r2.priority;
7588            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7589            if (v1 != v2) {
7590                return (v1 > v2) ? -1 : 1;
7591            }
7592            v1 = r1.preferredOrder;
7593            v2 = r2.preferredOrder;
7594            if (v1 != v2) {
7595                return (v1 > v2) ? -1 : 1;
7596            }
7597            if (r1.isDefault != r2.isDefault) {
7598                return r1.isDefault ? -1 : 1;
7599            }
7600            v1 = r1.match;
7601            v2 = r2.match;
7602            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7603            if (v1 != v2) {
7604                return (v1 > v2) ? -1 : 1;
7605            }
7606            if (r1.system != r2.system) {
7607                return r1.system ? -1 : 1;
7608            }
7609            return 0;
7610        }
7611    };
7612
7613    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7614            new Comparator<ProviderInfo>() {
7615        public int compare(ProviderInfo p1, ProviderInfo p2) {
7616            final int v1 = p1.initOrder;
7617            final int v2 = p2.initOrder;
7618            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7619        }
7620    };
7621
7622    static final void sendPackageBroadcast(String action, String pkg,
7623            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7624            int[] userIds) {
7625        IActivityManager am = ActivityManagerNative.getDefault();
7626        if (am != null) {
7627            try {
7628                if (userIds == null) {
7629                    userIds = am.getRunningUserIds();
7630                }
7631                for (int id : userIds) {
7632                    final Intent intent = new Intent(action,
7633                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7634                    if (extras != null) {
7635                        intent.putExtras(extras);
7636                    }
7637                    if (targetPkg != null) {
7638                        intent.setPackage(targetPkg);
7639                    }
7640                    // Modify the UID when posting to other users
7641                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7642                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7643                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7644                        intent.putExtra(Intent.EXTRA_UID, uid);
7645                    }
7646                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7647                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7648                    if (DEBUG_BROADCASTS) {
7649                        RuntimeException here = new RuntimeException("here");
7650                        here.fillInStackTrace();
7651                        Slog.d(TAG, "Sending to user " + id + ": "
7652                                + intent.toShortString(false, true, false, false)
7653                                + " " + intent.getExtras(), here);
7654                    }
7655                    am.broadcastIntent(null, intent, null, finishedReceiver,
7656                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7657                            finishedReceiver != null, false, id);
7658                }
7659            } catch (RemoteException ex) {
7660            }
7661        }
7662    }
7663
7664    /**
7665     * Check if the external storage media is available. This is true if there
7666     * is a mounted external storage medium or if the external storage is
7667     * emulated.
7668     */
7669    private boolean isExternalMediaAvailable() {
7670        return mMediaMounted || Environment.isExternalStorageEmulated();
7671    }
7672
7673    @Override
7674    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7675        // writer
7676        synchronized (mPackages) {
7677            if (!isExternalMediaAvailable()) {
7678                // If the external storage is no longer mounted at this point,
7679                // the caller may not have been able to delete all of this
7680                // packages files and can not delete any more.  Bail.
7681                return null;
7682            }
7683            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7684            if (lastPackage != null) {
7685                pkgs.remove(lastPackage);
7686            }
7687            if (pkgs.size() > 0) {
7688                return pkgs.get(0);
7689            }
7690        }
7691        return null;
7692    }
7693
7694    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7695        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7696                userId, andCode ? 1 : 0, packageName);
7697        if (mSystemReady) {
7698            msg.sendToTarget();
7699        } else {
7700            if (mPostSystemReadyMessages == null) {
7701                mPostSystemReadyMessages = new ArrayList<>();
7702            }
7703            mPostSystemReadyMessages.add(msg);
7704        }
7705    }
7706
7707    void startCleaningPackages() {
7708        // reader
7709        synchronized (mPackages) {
7710            if (!isExternalMediaAvailable()) {
7711                return;
7712            }
7713            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7714                return;
7715            }
7716        }
7717        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7718        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7719        IActivityManager am = ActivityManagerNative.getDefault();
7720        if (am != null) {
7721            try {
7722                am.startService(null, intent, null, UserHandle.USER_OWNER);
7723            } catch (RemoteException e) {
7724            }
7725        }
7726    }
7727
7728    @Override
7729    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7730            int installFlags, String installerPackageName, VerificationParams verificationParams,
7731            String packageAbiOverride) {
7732        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7733                packageAbiOverride, UserHandle.getCallingUserId());
7734    }
7735
7736    @Override
7737    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7738            int installFlags, String installerPackageName, VerificationParams verificationParams,
7739            String packageAbiOverride, int userId) {
7740        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7741                null);
7742        if (UserHandle.getCallingUserId() != userId) {
7743            mContext.enforceCallingOrSelfPermission(
7744                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7745                    "installPackage " + userId);
7746        }
7747
7748        final File originFile = new File(originPath);
7749        final int uid = Binder.getCallingUid();
7750        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7751            try {
7752                if (observer != null) {
7753                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7754                }
7755            } catch (RemoteException re) {
7756            }
7757            return;
7758        }
7759
7760        UserHandle user;
7761        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7762            user = UserHandle.ALL;
7763        } else {
7764            user = new UserHandle(userId);
7765        }
7766
7767        final int filteredInstallFlags;
7768        if (uid == Process.SHELL_UID || uid == 0) {
7769            if (DEBUG_INSTALL) {
7770                Slog.v(TAG, "Install from ADB");
7771            }
7772            filteredInstallFlags = installFlags | PackageManager.INSTALL_FROM_ADB;
7773        } else {
7774            filteredInstallFlags = installFlags & ~PackageManager.INSTALL_FROM_ADB;
7775        }
7776
7777        verificationParams.setInstallerUid(uid);
7778
7779        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7780
7781        final Message msg = mHandler.obtainMessage(INIT_COPY);
7782        msg.obj = new InstallParams(origin, observer, filteredInstallFlags,
7783                installerPackageName, verificationParams, user, packageAbiOverride);
7784        mHandler.sendMessage(msg);
7785    }
7786
7787    void installStage(String packageName, File stagedDir, String stagedCid,
7788            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7789            String installerPackageName, int installerUid, UserHandle user) {
7790        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7791                params.referrerUri, installerUid, null);
7792
7793        final OriginInfo origin;
7794        if (stagedDir != null) {
7795            origin = OriginInfo.fromStagedFile(stagedDir);
7796        } else {
7797            origin = OriginInfo.fromStagedContainer(stagedCid);
7798        }
7799
7800        final Message msg = mHandler.obtainMessage(INIT_COPY);
7801        msg.obj = new InstallParams(origin, observer, params.installFlags,
7802                installerPackageName, verifParams, user, params.abiOverride);
7803        mHandler.sendMessage(msg);
7804    }
7805
7806    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7807        Bundle extras = new Bundle(1);
7808        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7809
7810        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7811                packageName, extras, null, null, new int[] {userId});
7812        try {
7813            IActivityManager am = ActivityManagerNative.getDefault();
7814            final boolean isSystem =
7815                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7816            if (isSystem && am.isUserRunning(userId, false)) {
7817                // The just-installed/enabled app is bundled on the system, so presumed
7818                // to be able to run automatically without needing an explicit launch.
7819                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7820                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7821                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7822                        .setPackage(packageName);
7823                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7824                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7825            }
7826        } catch (RemoteException e) {
7827            // shouldn't happen
7828            Slog.w(TAG, "Unable to bootstrap installed package", e);
7829        }
7830    }
7831
7832    @Override
7833    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7834            int userId) {
7835        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7836        PackageSetting pkgSetting;
7837        final int uid = Binder.getCallingUid();
7838        if (UserHandle.getUserId(uid) != userId) {
7839            mContext.enforceCallingOrSelfPermission(
7840                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7841                    "setApplicationHiddenSetting for user " + userId);
7842        }
7843
7844        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7845            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7846            return false;
7847        }
7848
7849        long callingId = Binder.clearCallingIdentity();
7850        try {
7851            boolean sendAdded = false;
7852            boolean sendRemoved = false;
7853            // writer
7854            synchronized (mPackages) {
7855                pkgSetting = mSettings.mPackages.get(packageName);
7856                if (pkgSetting == null) {
7857                    return false;
7858                }
7859                if (pkgSetting.getHidden(userId) != hidden) {
7860                    pkgSetting.setHidden(hidden, userId);
7861                    mSettings.writePackageRestrictionsLPr(userId);
7862                    if (hidden) {
7863                        sendRemoved = true;
7864                    } else {
7865                        sendAdded = true;
7866                    }
7867                }
7868            }
7869            if (sendAdded) {
7870                sendPackageAddedForUser(packageName, pkgSetting, userId);
7871                return true;
7872            }
7873            if (sendRemoved) {
7874                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7875                        "hiding pkg");
7876                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7877            }
7878        } finally {
7879            Binder.restoreCallingIdentity(callingId);
7880        }
7881        return false;
7882    }
7883
7884    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7885            int userId) {
7886        final PackageRemovedInfo info = new PackageRemovedInfo();
7887        info.removedPackage = packageName;
7888        info.removedUsers = new int[] {userId};
7889        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7890        info.sendBroadcast(false, false, false);
7891    }
7892
7893    /**
7894     * Returns true if application is not found or there was an error. Otherwise it returns
7895     * the hidden state of the package for the given user.
7896     */
7897    @Override
7898    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7899        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7900        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7901                "getApplicationHidden for user " + userId);
7902        PackageSetting pkgSetting;
7903        long callingId = Binder.clearCallingIdentity();
7904        try {
7905            // writer
7906            synchronized (mPackages) {
7907                pkgSetting = mSettings.mPackages.get(packageName);
7908                if (pkgSetting == null) {
7909                    return true;
7910                }
7911                return pkgSetting.getHidden(userId);
7912            }
7913        } finally {
7914            Binder.restoreCallingIdentity(callingId);
7915        }
7916    }
7917
7918    /**
7919     * @hide
7920     */
7921    @Override
7922    public int installExistingPackageAsUser(String packageName, int userId) {
7923        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7924                null);
7925        PackageSetting pkgSetting;
7926        final int uid = Binder.getCallingUid();
7927        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7928        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7929            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7930        }
7931
7932        long callingId = Binder.clearCallingIdentity();
7933        try {
7934            boolean sendAdded = false;
7935            Bundle extras = new Bundle(1);
7936
7937            // writer
7938            synchronized (mPackages) {
7939                pkgSetting = mSettings.mPackages.get(packageName);
7940                if (pkgSetting == null) {
7941                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7942                }
7943                if (!pkgSetting.getInstalled(userId)) {
7944                    pkgSetting.setInstalled(true, userId);
7945                    pkgSetting.setHidden(false, userId);
7946                    mSettings.writePackageRestrictionsLPr(userId);
7947                    sendAdded = true;
7948                }
7949            }
7950
7951            if (sendAdded) {
7952                sendPackageAddedForUser(packageName, pkgSetting, userId);
7953            }
7954        } finally {
7955            Binder.restoreCallingIdentity(callingId);
7956        }
7957
7958        return PackageManager.INSTALL_SUCCEEDED;
7959    }
7960
7961    boolean isUserRestricted(int userId, String restrictionKey) {
7962        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7963        if (restrictions.getBoolean(restrictionKey, false)) {
7964            Log.w(TAG, "User is restricted: " + restrictionKey);
7965            return true;
7966        }
7967        return false;
7968    }
7969
7970    @Override
7971    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7972        mContext.enforceCallingOrSelfPermission(
7973                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7974                "Only package verification agents can verify applications");
7975
7976        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7977        final PackageVerificationResponse response = new PackageVerificationResponse(
7978                verificationCode, Binder.getCallingUid());
7979        msg.arg1 = id;
7980        msg.obj = response;
7981        mHandler.sendMessage(msg);
7982    }
7983
7984    @Override
7985    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7986            long millisecondsToDelay) {
7987        mContext.enforceCallingOrSelfPermission(
7988                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7989                "Only package verification agents can extend verification timeouts");
7990
7991        final PackageVerificationState state = mPendingVerification.get(id);
7992        final PackageVerificationResponse response = new PackageVerificationResponse(
7993                verificationCodeAtTimeout, Binder.getCallingUid());
7994
7995        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7996            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7997        }
7998        if (millisecondsToDelay < 0) {
7999            millisecondsToDelay = 0;
8000        }
8001        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8002                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8003            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8004        }
8005
8006        if ((state != null) && !state.timeoutExtended()) {
8007            state.extendTimeout();
8008
8009            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8010            msg.arg1 = id;
8011            msg.obj = response;
8012            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8013        }
8014    }
8015
8016    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8017            int verificationCode, UserHandle user) {
8018        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8019        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8020        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8021        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8022        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8023
8024        mContext.sendBroadcastAsUser(intent, user,
8025                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8026    }
8027
8028    private ComponentName matchComponentForVerifier(String packageName,
8029            List<ResolveInfo> receivers) {
8030        ActivityInfo targetReceiver = null;
8031
8032        final int NR = receivers.size();
8033        for (int i = 0; i < NR; i++) {
8034            final ResolveInfo info = receivers.get(i);
8035            if (info.activityInfo == null) {
8036                continue;
8037            }
8038
8039            if (packageName.equals(info.activityInfo.packageName)) {
8040                targetReceiver = info.activityInfo;
8041                break;
8042            }
8043        }
8044
8045        if (targetReceiver == null) {
8046            return null;
8047        }
8048
8049        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8050    }
8051
8052    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8053            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8054        if (pkgInfo.verifiers.length == 0) {
8055            return null;
8056        }
8057
8058        final int N = pkgInfo.verifiers.length;
8059        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8060        for (int i = 0; i < N; i++) {
8061            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8062
8063            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8064                    receivers);
8065            if (comp == null) {
8066                continue;
8067            }
8068
8069            final int verifierUid = getUidForVerifier(verifierInfo);
8070            if (verifierUid == -1) {
8071                continue;
8072            }
8073
8074            if (DEBUG_VERIFY) {
8075                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8076                        + " with the correct signature");
8077            }
8078            sufficientVerifiers.add(comp);
8079            verificationState.addSufficientVerifier(verifierUid);
8080        }
8081
8082        return sufficientVerifiers;
8083    }
8084
8085    private int getUidForVerifier(VerifierInfo verifierInfo) {
8086        synchronized (mPackages) {
8087            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8088            if (pkg == null) {
8089                return -1;
8090            } else if (pkg.mSignatures.length != 1) {
8091                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8092                        + " has more than one signature; ignoring");
8093                return -1;
8094            }
8095
8096            /*
8097             * If the public key of the package's signature does not match
8098             * our expected public key, then this is a different package and
8099             * we should skip.
8100             */
8101
8102            final byte[] expectedPublicKey;
8103            try {
8104                final Signature verifierSig = pkg.mSignatures[0];
8105                final PublicKey publicKey = verifierSig.getPublicKey();
8106                expectedPublicKey = publicKey.getEncoded();
8107            } catch (CertificateException e) {
8108                return -1;
8109            }
8110
8111            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8112
8113            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8114                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8115                        + " does not have the expected public key; ignoring");
8116                return -1;
8117            }
8118
8119            return pkg.applicationInfo.uid;
8120        }
8121    }
8122
8123    @Override
8124    public void finishPackageInstall(int token) {
8125        enforceSystemOrRoot("Only the system is allowed to finish installs");
8126
8127        if (DEBUG_INSTALL) {
8128            Slog.v(TAG, "BM finishing package install for " + token);
8129        }
8130
8131        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8132        mHandler.sendMessage(msg);
8133    }
8134
8135    /**
8136     * Get the verification agent timeout.
8137     *
8138     * @return verification timeout in milliseconds
8139     */
8140    private long getVerificationTimeout() {
8141        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8142                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8143                DEFAULT_VERIFICATION_TIMEOUT);
8144    }
8145
8146    /**
8147     * Get the default verification agent response code.
8148     *
8149     * @return default verification response code
8150     */
8151    private int getDefaultVerificationResponse() {
8152        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8153                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8154                DEFAULT_VERIFICATION_RESPONSE);
8155    }
8156
8157    /**
8158     * Check whether or not package verification has been enabled.
8159     *
8160     * @return true if verification should be performed
8161     */
8162    private boolean isVerificationEnabled(int userId, int installFlags) {
8163        if (!DEFAULT_VERIFY_ENABLE) {
8164            return false;
8165        }
8166
8167        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8168
8169        // Check if installing from ADB
8170        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8171            // Do not run verification in a test harness environment
8172            if (ActivityManager.isRunningInTestHarness()) {
8173                return false;
8174            }
8175            if (ensureVerifyAppsEnabled) {
8176                return true;
8177            }
8178            // Check if the developer does not want package verification for ADB installs
8179            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8180                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8181                return false;
8182            }
8183        }
8184
8185        if (ensureVerifyAppsEnabled) {
8186            return true;
8187        }
8188
8189        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8190                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8191    }
8192
8193    /**
8194     * Get the "allow unknown sources" setting.
8195     *
8196     * @return the current "allow unknown sources" setting
8197     */
8198    private int getUnknownSourcesSettings() {
8199        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8200                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8201                -1);
8202    }
8203
8204    @Override
8205    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8206        final int uid = Binder.getCallingUid();
8207        // writer
8208        synchronized (mPackages) {
8209            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8210            if (targetPackageSetting == null) {
8211                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8212            }
8213
8214            PackageSetting installerPackageSetting;
8215            if (installerPackageName != null) {
8216                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8217                if (installerPackageSetting == null) {
8218                    throw new IllegalArgumentException("Unknown installer package: "
8219                            + installerPackageName);
8220                }
8221            } else {
8222                installerPackageSetting = null;
8223            }
8224
8225            Signature[] callerSignature;
8226            Object obj = mSettings.getUserIdLPr(uid);
8227            if (obj != null) {
8228                if (obj instanceof SharedUserSetting) {
8229                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8230                } else if (obj instanceof PackageSetting) {
8231                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8232                } else {
8233                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8234                }
8235            } else {
8236                throw new SecurityException("Unknown calling uid " + uid);
8237            }
8238
8239            // Verify: can't set installerPackageName to a package that is
8240            // not signed with the same cert as the caller.
8241            if (installerPackageSetting != null) {
8242                if (compareSignatures(callerSignature,
8243                        installerPackageSetting.signatures.mSignatures)
8244                        != PackageManager.SIGNATURE_MATCH) {
8245                    throw new SecurityException(
8246                            "Caller does not have same cert as new installer package "
8247                            + installerPackageName);
8248                }
8249            }
8250
8251            // Verify: if target already has an installer package, it must
8252            // be signed with the same cert as the caller.
8253            if (targetPackageSetting.installerPackageName != null) {
8254                PackageSetting setting = mSettings.mPackages.get(
8255                        targetPackageSetting.installerPackageName);
8256                // If the currently set package isn't valid, then it's always
8257                // okay to change it.
8258                if (setting != null) {
8259                    if (compareSignatures(callerSignature,
8260                            setting.signatures.mSignatures)
8261                            != PackageManager.SIGNATURE_MATCH) {
8262                        throw new SecurityException(
8263                                "Caller does not have same cert as old installer package "
8264                                + targetPackageSetting.installerPackageName);
8265                    }
8266                }
8267            }
8268
8269            // Okay!
8270            targetPackageSetting.installerPackageName = installerPackageName;
8271            scheduleWriteSettingsLocked();
8272        }
8273    }
8274
8275    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8276        // Queue up an async operation since the package installation may take a little while.
8277        mHandler.post(new Runnable() {
8278            public void run() {
8279                mHandler.removeCallbacks(this);
8280                 // Result object to be returned
8281                PackageInstalledInfo res = new PackageInstalledInfo();
8282                res.returnCode = currentStatus;
8283                res.uid = -1;
8284                res.pkg = null;
8285                res.removedInfo = new PackageRemovedInfo();
8286                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8287                    args.doPreInstall(res.returnCode);
8288                    synchronized (mInstallLock) {
8289                        installPackageLI(args, res);
8290                    }
8291                    args.doPostInstall(res.returnCode, res.uid);
8292                }
8293
8294                // A restore should be performed at this point if (a) the install
8295                // succeeded, (b) the operation is not an update, and (c) the new
8296                // package has not opted out of backup participation.
8297                final boolean update = res.removedInfo.removedPackage != null;
8298                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8299                boolean doRestore = !update
8300                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8301
8302                // Set up the post-install work request bookkeeping.  This will be used
8303                // and cleaned up by the post-install event handling regardless of whether
8304                // there's a restore pass performed.  Token values are >= 1.
8305                int token;
8306                if (mNextInstallToken < 0) mNextInstallToken = 1;
8307                token = mNextInstallToken++;
8308
8309                PostInstallData data = new PostInstallData(args, res);
8310                mRunningInstalls.put(token, data);
8311                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8312
8313                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8314                    // Pass responsibility to the Backup Manager.  It will perform a
8315                    // restore if appropriate, then pass responsibility back to the
8316                    // Package Manager to run the post-install observer callbacks
8317                    // and broadcasts.
8318                    IBackupManager bm = IBackupManager.Stub.asInterface(
8319                            ServiceManager.getService(Context.BACKUP_SERVICE));
8320                    if (bm != null) {
8321                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8322                                + " to BM for possible restore");
8323                        try {
8324                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8325                        } catch (RemoteException e) {
8326                            // can't happen; the backup manager is local
8327                        } catch (Exception e) {
8328                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8329                            doRestore = false;
8330                        }
8331                    } else {
8332                        Slog.e(TAG, "Backup Manager not found!");
8333                        doRestore = false;
8334                    }
8335                }
8336
8337                if (!doRestore) {
8338                    // No restore possible, or the Backup Manager was mysteriously not
8339                    // available -- just fire the post-install work request directly.
8340                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8341                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8342                    mHandler.sendMessage(msg);
8343                }
8344            }
8345        });
8346    }
8347
8348    private abstract class HandlerParams {
8349        private static final int MAX_RETRIES = 4;
8350
8351        /**
8352         * Number of times startCopy() has been attempted and had a non-fatal
8353         * error.
8354         */
8355        private int mRetries = 0;
8356
8357        /** User handle for the user requesting the information or installation. */
8358        private final UserHandle mUser;
8359
8360        HandlerParams(UserHandle user) {
8361            mUser = user;
8362        }
8363
8364        UserHandle getUser() {
8365            return mUser;
8366        }
8367
8368        final boolean startCopy() {
8369            boolean res;
8370            try {
8371                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8372
8373                if (++mRetries > MAX_RETRIES) {
8374                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8375                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8376                    handleServiceError();
8377                    return false;
8378                } else {
8379                    handleStartCopy();
8380                    res = true;
8381                }
8382            } catch (RemoteException e) {
8383                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8384                mHandler.sendEmptyMessage(MCS_RECONNECT);
8385                res = false;
8386            }
8387            handleReturnCode();
8388            return res;
8389        }
8390
8391        final void serviceError() {
8392            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8393            handleServiceError();
8394            handleReturnCode();
8395        }
8396
8397        abstract void handleStartCopy() throws RemoteException;
8398        abstract void handleServiceError();
8399        abstract void handleReturnCode();
8400    }
8401
8402    class MeasureParams extends HandlerParams {
8403        private final PackageStats mStats;
8404        private boolean mSuccess;
8405
8406        private final IPackageStatsObserver mObserver;
8407
8408        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8409            super(new UserHandle(stats.userHandle));
8410            mObserver = observer;
8411            mStats = stats;
8412        }
8413
8414        @Override
8415        public String toString() {
8416            return "MeasureParams{"
8417                + Integer.toHexString(System.identityHashCode(this))
8418                + " " + mStats.packageName + "}";
8419        }
8420
8421        @Override
8422        void handleStartCopy() throws RemoteException {
8423            synchronized (mInstallLock) {
8424                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8425            }
8426
8427            if (mSuccess) {
8428                final boolean mounted;
8429                if (Environment.isExternalStorageEmulated()) {
8430                    mounted = true;
8431                } else {
8432                    final String status = Environment.getExternalStorageState();
8433                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8434                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8435                }
8436
8437                if (mounted) {
8438                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8439
8440                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8441                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8442
8443                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8444                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8445
8446                    // Always subtract cache size, since it's a subdirectory
8447                    mStats.externalDataSize -= mStats.externalCacheSize;
8448
8449                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8450                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8451
8452                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8453                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8454                }
8455            }
8456        }
8457
8458        @Override
8459        void handleReturnCode() {
8460            if (mObserver != null) {
8461                try {
8462                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8463                } catch (RemoteException e) {
8464                    Slog.i(TAG, "Observer no longer exists.");
8465                }
8466            }
8467        }
8468
8469        @Override
8470        void handleServiceError() {
8471            Slog.e(TAG, "Could not measure application " + mStats.packageName
8472                            + " external storage");
8473        }
8474    }
8475
8476    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8477            throws RemoteException {
8478        long result = 0;
8479        for (File path : paths) {
8480            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8481        }
8482        return result;
8483    }
8484
8485    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8486        for (File path : paths) {
8487            try {
8488                mcs.clearDirectory(path.getAbsolutePath());
8489            } catch (RemoteException e) {
8490            }
8491        }
8492    }
8493
8494    static class OriginInfo {
8495        /**
8496         * Location where install is coming from, before it has been
8497         * copied/renamed into place. This could be a single monolithic APK
8498         * file, or a cluster directory. This location may be untrusted.
8499         */
8500        final File file;
8501        final String cid;
8502
8503        /**
8504         * Flag indicating that {@link #file} or {@link #cid} has already been
8505         * staged, meaning downstream users don't need to defensively copy the
8506         * contents.
8507         */
8508        final boolean staged;
8509
8510        /**
8511         * Flag indicating that {@link #file} or {@link #cid} is an already
8512         * installed app that is being moved.
8513         */
8514        final boolean existing;
8515
8516        final String resolvedPath;
8517        final File resolvedFile;
8518
8519        static OriginInfo fromNothing() {
8520            return new OriginInfo(null, null, false, false);
8521        }
8522
8523        static OriginInfo fromUntrustedFile(File file) {
8524            return new OriginInfo(file, null, false, false);
8525        }
8526
8527        static OriginInfo fromExistingFile(File file) {
8528            return new OriginInfo(file, null, false, true);
8529        }
8530
8531        static OriginInfo fromStagedFile(File file) {
8532            return new OriginInfo(file, null, true, false);
8533        }
8534
8535        static OriginInfo fromStagedContainer(String cid) {
8536            return new OriginInfo(null, cid, true, false);
8537        }
8538
8539        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8540            this.file = file;
8541            this.cid = cid;
8542            this.staged = staged;
8543            this.existing = existing;
8544
8545            if (cid != null) {
8546                resolvedPath = PackageHelper.getSdDir(cid);
8547                resolvedFile = new File(resolvedPath);
8548            } else if (file != null) {
8549                resolvedPath = file.getAbsolutePath();
8550                resolvedFile = file;
8551            } else {
8552                resolvedPath = null;
8553                resolvedFile = null;
8554            }
8555        }
8556    }
8557
8558    class InstallParams extends HandlerParams {
8559        final OriginInfo origin;
8560        final IPackageInstallObserver2 observer;
8561        int installFlags;
8562        final String installerPackageName;
8563        final VerificationParams verificationParams;
8564        private InstallArgs mArgs;
8565        private int mRet;
8566        final String packageAbiOverride;
8567
8568        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8569                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8570                String packageAbiOverride) {
8571            super(user);
8572            this.origin = origin;
8573            this.observer = observer;
8574            this.installFlags = installFlags;
8575            this.installerPackageName = installerPackageName;
8576            this.verificationParams = verificationParams;
8577            this.packageAbiOverride = packageAbiOverride;
8578        }
8579
8580        @Override
8581        public String toString() {
8582            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8583                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8584        }
8585
8586        public ManifestDigest getManifestDigest() {
8587            if (verificationParams == null) {
8588                return null;
8589            }
8590            return verificationParams.getManifestDigest();
8591        }
8592
8593        private int installLocationPolicy(PackageInfoLite pkgLite) {
8594            String packageName = pkgLite.packageName;
8595            int installLocation = pkgLite.installLocation;
8596            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8597            // reader
8598            synchronized (mPackages) {
8599                PackageParser.Package pkg = mPackages.get(packageName);
8600                if (pkg != null) {
8601                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8602                        // Check for downgrading.
8603                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8604                            if (pkgLite.versionCode < pkg.mVersionCode) {
8605                                Slog.w(TAG, "Can't install update of " + packageName
8606                                        + " update version " + pkgLite.versionCode
8607                                        + " is older than installed version "
8608                                        + pkg.mVersionCode);
8609                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8610                            }
8611                        }
8612                        // Check for updated system application.
8613                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8614                            if (onSd) {
8615                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8616                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8617                            }
8618                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8619                        } else {
8620                            if (onSd) {
8621                                // Install flag overrides everything.
8622                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8623                            }
8624                            // If current upgrade specifies particular preference
8625                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8626                                // Application explicitly specified internal.
8627                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8628                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8629                                // App explictly prefers external. Let policy decide
8630                            } else {
8631                                // Prefer previous location
8632                                if (isExternal(pkg)) {
8633                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8634                                }
8635                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8636                            }
8637                        }
8638                    } else {
8639                        // Invalid install. Return error code
8640                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8641                    }
8642                }
8643            }
8644            // All the special cases have been taken care of.
8645            // Return result based on recommended install location.
8646            if (onSd) {
8647                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8648            }
8649            return pkgLite.recommendedInstallLocation;
8650        }
8651
8652        /*
8653         * Invoke remote method to get package information and install
8654         * location values. Override install location based on default
8655         * policy if needed and then create install arguments based
8656         * on the install location.
8657         */
8658        public void handleStartCopy() throws RemoteException {
8659            int ret = PackageManager.INSTALL_SUCCEEDED;
8660
8661            // If we're already staged, we've firmly committed to an install location
8662            if (origin.staged) {
8663                if (origin.file != null) {
8664                    installFlags |= PackageManager.INSTALL_INTERNAL;
8665                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8666                } else if (origin.cid != null) {
8667                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8668                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8669                } else {
8670                    throw new IllegalStateException("Invalid stage location");
8671                }
8672            }
8673
8674            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8675            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8676
8677            PackageInfoLite pkgLite = null;
8678
8679            if (onInt && onSd) {
8680                // Check if both bits are set.
8681                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8682                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8683            } else {
8684                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8685                        packageAbiOverride);
8686
8687                /*
8688                 * If we have too little free space, try to free cache
8689                 * before giving up.
8690                 */
8691                if (!origin.staged && pkgLite.recommendedInstallLocation
8692                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8693                    // TODO: focus freeing disk space on the target device
8694                    final StorageManager storage = StorageManager.from(mContext);
8695                    final long lowThreshold = storage.getStorageLowBytes(
8696                            Environment.getDataDirectory());
8697
8698                    final long sizeBytes = mContainerService.calculateInstalledSize(
8699                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8700
8701                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8702                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8703                                installFlags, packageAbiOverride);
8704                    }
8705
8706                    /*
8707                     * The cache free must have deleted the file we
8708                     * downloaded to install.
8709                     *
8710                     * TODO: fix the "freeCache" call to not delete
8711                     *       the file we care about.
8712                     */
8713                    if (pkgLite.recommendedInstallLocation
8714                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8715                        pkgLite.recommendedInstallLocation
8716                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8717                    }
8718                }
8719            }
8720
8721            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8722                int loc = pkgLite.recommendedInstallLocation;
8723                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8724                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8725                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8726                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8727                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8728                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8729                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8730                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8731                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8732                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8733                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8734                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8735                } else {
8736                    // Override with defaults if needed.
8737                    loc = installLocationPolicy(pkgLite);
8738                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8739                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8740                    } else if (!onSd && !onInt) {
8741                        // Override install location with flags
8742                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8743                            // Set the flag to install on external media.
8744                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8745                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8746                        } else {
8747                            // Make sure the flag for installing on external
8748                            // media is unset
8749                            installFlags |= PackageManager.INSTALL_INTERNAL;
8750                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8751                        }
8752                    }
8753                }
8754            }
8755
8756            final InstallArgs args = createInstallArgs(this);
8757            mArgs = args;
8758
8759            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8760                 /*
8761                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8762                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8763                 */
8764                int userIdentifier = getUser().getIdentifier();
8765                if (userIdentifier == UserHandle.USER_ALL
8766                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8767                    userIdentifier = UserHandle.USER_OWNER;
8768                }
8769
8770                /*
8771                 * Determine if we have any installed package verifiers. If we
8772                 * do, then we'll defer to them to verify the packages.
8773                 */
8774                final int requiredUid = mRequiredVerifierPackage == null ? -1
8775                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8776                if (!origin.existing && requiredUid != -1
8777                        && isVerificationEnabled(userIdentifier, installFlags)) {
8778                    final Intent verification = new Intent(
8779                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8780                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8781                            PACKAGE_MIME_TYPE);
8782                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8783
8784                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8785                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8786                            0 /* TODO: Which userId? */);
8787
8788                    if (DEBUG_VERIFY) {
8789                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8790                                + verification.toString() + " with " + pkgLite.verifiers.length
8791                                + " optional verifiers");
8792                    }
8793
8794                    final int verificationId = mPendingVerificationToken++;
8795
8796                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8797
8798                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8799                            installerPackageName);
8800
8801                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8802                            installFlags);
8803
8804                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8805                            pkgLite.packageName);
8806
8807                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8808                            pkgLite.versionCode);
8809
8810                    if (verificationParams != null) {
8811                        if (verificationParams.getVerificationURI() != null) {
8812                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8813                                 verificationParams.getVerificationURI());
8814                        }
8815                        if (verificationParams.getOriginatingURI() != null) {
8816                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8817                                  verificationParams.getOriginatingURI());
8818                        }
8819                        if (verificationParams.getReferrer() != null) {
8820                            verification.putExtra(Intent.EXTRA_REFERRER,
8821                                  verificationParams.getReferrer());
8822                        }
8823                        if (verificationParams.getOriginatingUid() >= 0) {
8824                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8825                                  verificationParams.getOriginatingUid());
8826                        }
8827                        if (verificationParams.getInstallerUid() >= 0) {
8828                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8829                                  verificationParams.getInstallerUid());
8830                        }
8831                    }
8832
8833                    final PackageVerificationState verificationState = new PackageVerificationState(
8834                            requiredUid, args);
8835
8836                    mPendingVerification.append(verificationId, verificationState);
8837
8838                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8839                            receivers, verificationState);
8840
8841                    /*
8842                     * If any sufficient verifiers were listed in the package
8843                     * manifest, attempt to ask them.
8844                     */
8845                    if (sufficientVerifiers != null) {
8846                        final int N = sufficientVerifiers.size();
8847                        if (N == 0) {
8848                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8849                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8850                        } else {
8851                            for (int i = 0; i < N; i++) {
8852                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8853
8854                                final Intent sufficientIntent = new Intent(verification);
8855                                sufficientIntent.setComponent(verifierComponent);
8856
8857                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8858                            }
8859                        }
8860                    }
8861
8862                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8863                            mRequiredVerifierPackage, receivers);
8864                    if (ret == PackageManager.INSTALL_SUCCEEDED
8865                            && mRequiredVerifierPackage != null) {
8866                        /*
8867                         * Send the intent to the required verification agent,
8868                         * but only start the verification timeout after the
8869                         * target BroadcastReceivers have run.
8870                         */
8871                        verification.setComponent(requiredVerifierComponent);
8872                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8873                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8874                                new BroadcastReceiver() {
8875                                    @Override
8876                                    public void onReceive(Context context, Intent intent) {
8877                                        final Message msg = mHandler
8878                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8879                                        msg.arg1 = verificationId;
8880                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8881                                    }
8882                                }, null, 0, null, null);
8883
8884                        /*
8885                         * We don't want the copy to proceed until verification
8886                         * succeeds, so null out this field.
8887                         */
8888                        mArgs = null;
8889                    }
8890                } else {
8891                    /*
8892                     * No package verification is enabled, so immediately start
8893                     * the remote call to initiate copy using temporary file.
8894                     */
8895                    ret = args.copyApk(mContainerService, true);
8896                }
8897            }
8898
8899            mRet = ret;
8900        }
8901
8902        @Override
8903        void handleReturnCode() {
8904            // If mArgs is null, then MCS couldn't be reached. When it
8905            // reconnects, it will try again to install. At that point, this
8906            // will succeed.
8907            if (mArgs != null) {
8908                processPendingInstall(mArgs, mRet);
8909            }
8910        }
8911
8912        @Override
8913        void handleServiceError() {
8914            mArgs = createInstallArgs(this);
8915            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8916        }
8917
8918        public boolean isForwardLocked() {
8919            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8920        }
8921    }
8922
8923    /**
8924     * Used during creation of InstallArgs
8925     *
8926     * @param installFlags package installation flags
8927     * @return true if should be installed on external storage
8928     */
8929    private static boolean installOnSd(int installFlags) {
8930        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8931            return false;
8932        }
8933        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8934            return true;
8935        }
8936        return false;
8937    }
8938
8939    /**
8940     * Used during creation of InstallArgs
8941     *
8942     * @param installFlags package installation flags
8943     * @return true if should be installed as forward locked
8944     */
8945    private static boolean installForwardLocked(int installFlags) {
8946        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8947    }
8948
8949    private InstallArgs createInstallArgs(InstallParams params) {
8950        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8951            return new AsecInstallArgs(params);
8952        } else {
8953            return new FileInstallArgs(params);
8954        }
8955    }
8956
8957    /**
8958     * Create args that describe an existing installed package. Typically used
8959     * when cleaning up old installs, or used as a move source.
8960     */
8961    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8962            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8963        final boolean isInAsec;
8964        if (installOnSd(installFlags)) {
8965            /* Apps on SD card are always in ASEC containers. */
8966            isInAsec = true;
8967        } else if (installForwardLocked(installFlags)
8968                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8969            /*
8970             * Forward-locked apps are only in ASEC containers if they're the
8971             * new style
8972             */
8973            isInAsec = true;
8974        } else {
8975            isInAsec = false;
8976        }
8977
8978        if (isInAsec) {
8979            return new AsecInstallArgs(codePath, instructionSets,
8980                    installOnSd(installFlags), installForwardLocked(installFlags));
8981        } else {
8982            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8983                    instructionSets);
8984        }
8985    }
8986
8987    static abstract class InstallArgs {
8988        /** @see InstallParams#origin */
8989        final OriginInfo origin;
8990
8991        final IPackageInstallObserver2 observer;
8992        // Always refers to PackageManager flags only
8993        final int installFlags;
8994        final String installerPackageName;
8995        final ManifestDigest manifestDigest;
8996        final UserHandle user;
8997        final String abiOverride;
8998
8999        // The list of instruction sets supported by this app. This is currently
9000        // only used during the rmdex() phase to clean up resources. We can get rid of this
9001        // if we move dex files under the common app path.
9002        /* nullable */ String[] instructionSets;
9003
9004        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9005                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9006                String[] instructionSets, String abiOverride) {
9007            this.origin = origin;
9008            this.installFlags = installFlags;
9009            this.observer = observer;
9010            this.installerPackageName = installerPackageName;
9011            this.manifestDigest = manifestDigest;
9012            this.user = user;
9013            this.instructionSets = instructionSets;
9014            this.abiOverride = abiOverride;
9015        }
9016
9017        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9018        abstract int doPreInstall(int status);
9019
9020        /**
9021         * Rename package into final resting place. All paths on the given
9022         * scanned package should be updated to reflect the rename.
9023         */
9024        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9025        abstract int doPostInstall(int status, int uid);
9026
9027        /** @see PackageSettingBase#codePathString */
9028        abstract String getCodePath();
9029        /** @see PackageSettingBase#resourcePathString */
9030        abstract String getResourcePath();
9031        abstract String getLegacyNativeLibraryPath();
9032
9033        // Need installer lock especially for dex file removal.
9034        abstract void cleanUpResourcesLI();
9035        abstract boolean doPostDeleteLI(boolean delete);
9036        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9037
9038        /**
9039         * Called before the source arguments are copied. This is used mostly
9040         * for MoveParams when it needs to read the source file to put it in the
9041         * destination.
9042         */
9043        int doPreCopy() {
9044            return PackageManager.INSTALL_SUCCEEDED;
9045        }
9046
9047        /**
9048         * Called after the source arguments are copied. This is used mostly for
9049         * MoveParams when it needs to read the source file to put it in the
9050         * destination.
9051         *
9052         * @return
9053         */
9054        int doPostCopy(int uid) {
9055            return PackageManager.INSTALL_SUCCEEDED;
9056        }
9057
9058        protected boolean isFwdLocked() {
9059            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9060        }
9061
9062        protected boolean isExternal() {
9063            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9064        }
9065
9066        UserHandle getUser() {
9067            return user;
9068        }
9069    }
9070
9071    /**
9072     * Logic to handle installation of non-ASEC applications, including copying
9073     * and renaming logic.
9074     */
9075    class FileInstallArgs extends InstallArgs {
9076        private File codeFile;
9077        private File resourceFile;
9078        private File legacyNativeLibraryPath;
9079
9080        // Example topology:
9081        // /data/app/com.example/base.apk
9082        // /data/app/com.example/split_foo.apk
9083        // /data/app/com.example/lib/arm/libfoo.so
9084        // /data/app/com.example/lib/arm64/libfoo.so
9085        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9086
9087        /** New install */
9088        FileInstallArgs(InstallParams params) {
9089            super(params.origin, params.observer, params.installFlags,
9090                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9091                    null /* instruction sets */, params.packageAbiOverride);
9092            if (isFwdLocked()) {
9093                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9094            }
9095        }
9096
9097        /** Existing install */
9098        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9099                String[] instructionSets) {
9100            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9101            this.codeFile = (codePath != null) ? new File(codePath) : null;
9102            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9103            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9104                    new File(legacyNativeLibraryPath) : null;
9105        }
9106
9107        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9108            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9109                    isFwdLocked(), abiOverride);
9110
9111            final StorageManager storage = StorageManager.from(mContext);
9112            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9113        }
9114
9115        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9116            if (origin.staged) {
9117                Slog.d(TAG, origin.file + " already staged; skipping copy");
9118                codeFile = origin.file;
9119                resourceFile = origin.file;
9120                return PackageManager.INSTALL_SUCCEEDED;
9121            }
9122
9123            try {
9124                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9125                codeFile = tempDir;
9126                resourceFile = tempDir;
9127            } catch (IOException e) {
9128                Slog.w(TAG, "Failed to create copy file: " + e);
9129                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9130            }
9131
9132            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9133                @Override
9134                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9135                    if (!FileUtils.isValidExtFilename(name)) {
9136                        throw new IllegalArgumentException("Invalid filename: " + name);
9137                    }
9138                    try {
9139                        final File file = new File(codeFile, name);
9140                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9141                                O_RDWR | O_CREAT, 0644);
9142                        Os.chmod(file.getAbsolutePath(), 0644);
9143                        return new ParcelFileDescriptor(fd);
9144                    } catch (ErrnoException e) {
9145                        throw new RemoteException("Failed to open: " + e.getMessage());
9146                    }
9147                }
9148            };
9149
9150            int ret = PackageManager.INSTALL_SUCCEEDED;
9151            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9152            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9153                Slog.e(TAG, "Failed to copy package");
9154                return ret;
9155            }
9156
9157            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9158            NativeLibraryHelper.Handle handle = null;
9159            try {
9160                handle = NativeLibraryHelper.Handle.create(codeFile);
9161                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9162                        abiOverride);
9163            } catch (IOException e) {
9164                Slog.e(TAG, "Copying native libraries failed", e);
9165                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9166            } finally {
9167                IoUtils.closeQuietly(handle);
9168            }
9169
9170            return ret;
9171        }
9172
9173        int doPreInstall(int status) {
9174            if (status != PackageManager.INSTALL_SUCCEEDED) {
9175                cleanUp();
9176            }
9177            return status;
9178        }
9179
9180        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9181            if (status != PackageManager.INSTALL_SUCCEEDED) {
9182                cleanUp();
9183                return false;
9184            } else {
9185                final File beforeCodeFile = codeFile;
9186                final File afterCodeFile = getNextCodePath(pkg.packageName);
9187
9188                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9189                try {
9190                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9191                } catch (ErrnoException e) {
9192                    Slog.d(TAG, "Failed to rename", e);
9193                    return false;
9194                }
9195
9196                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9197                    Slog.d(TAG, "Failed to restorecon");
9198                    return false;
9199                }
9200
9201                // Reflect the rename internally
9202                codeFile = afterCodeFile;
9203                resourceFile = afterCodeFile;
9204
9205                // Reflect the rename in scanned details
9206                pkg.codePath = afterCodeFile.getAbsolutePath();
9207                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9208                        pkg.baseCodePath);
9209                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9210                        pkg.splitCodePaths);
9211
9212                // Reflect the rename in app info
9213                pkg.applicationInfo.setCodePath(pkg.codePath);
9214                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9215                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9216                pkg.applicationInfo.setResourcePath(pkg.codePath);
9217                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9218                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9219
9220                return true;
9221            }
9222        }
9223
9224        int doPostInstall(int status, int uid) {
9225            if (status != PackageManager.INSTALL_SUCCEEDED) {
9226                cleanUp();
9227            }
9228            return status;
9229        }
9230
9231        @Override
9232        String getCodePath() {
9233            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9234        }
9235
9236        @Override
9237        String getResourcePath() {
9238            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9239        }
9240
9241        @Override
9242        String getLegacyNativeLibraryPath() {
9243            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9244        }
9245
9246        private boolean cleanUp() {
9247            if (codeFile == null || !codeFile.exists()) {
9248                return false;
9249            }
9250
9251            if (codeFile.isDirectory()) {
9252                FileUtils.deleteContents(codeFile);
9253            }
9254            codeFile.delete();
9255
9256            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9257                resourceFile.delete();
9258            }
9259
9260            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9261                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9262                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9263                }
9264                legacyNativeLibraryPath.delete();
9265            }
9266
9267            return true;
9268        }
9269
9270        void cleanUpResourcesLI() {
9271            // Try enumerating all code paths before deleting
9272            List<String> allCodePaths = Collections.EMPTY_LIST;
9273            if (codeFile != null && codeFile.exists()) {
9274                try {
9275                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9276                    allCodePaths = pkg.getAllCodePaths();
9277                } catch (PackageParserException e) {
9278                    // Ignored; we tried our best
9279                }
9280            }
9281
9282            cleanUp();
9283
9284            if (!allCodePaths.isEmpty()) {
9285                if (instructionSets == null) {
9286                    throw new IllegalStateException("instructionSet == null");
9287                }
9288                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9289                for (String codePath : allCodePaths) {
9290                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9291                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9292                        if (retCode < 0) {
9293                            Slog.w(TAG, "Couldn't remove dex file for package: "
9294                                    + " at location " + codePath + ", retcode=" + retCode);
9295                            // we don't consider this to be a failure of the core package deletion
9296                        }
9297                    }
9298                }
9299            }
9300        }
9301
9302        boolean doPostDeleteLI(boolean delete) {
9303            // XXX err, shouldn't we respect the delete flag?
9304            cleanUpResourcesLI();
9305            return true;
9306        }
9307    }
9308
9309    private boolean isAsecExternal(String cid) {
9310        final String asecPath = PackageHelper.getSdFilesystem(cid);
9311        return !asecPath.startsWith(mAsecInternalPath);
9312    }
9313
9314    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9315            PackageManagerException {
9316        if (copyRet < 0) {
9317            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9318                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9319                throw new PackageManagerException(copyRet, message);
9320            }
9321        }
9322    }
9323
9324    /**
9325     * Extract the MountService "container ID" from the full code path of an
9326     * .apk.
9327     */
9328    static String cidFromCodePath(String fullCodePath) {
9329        int eidx = fullCodePath.lastIndexOf("/");
9330        String subStr1 = fullCodePath.substring(0, eidx);
9331        int sidx = subStr1.lastIndexOf("/");
9332        return subStr1.substring(sidx+1, eidx);
9333    }
9334
9335    /**
9336     * Logic to handle installation of ASEC applications, including copying and
9337     * renaming logic.
9338     */
9339    class AsecInstallArgs extends InstallArgs {
9340        static final String RES_FILE_NAME = "pkg.apk";
9341        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9342
9343        String cid;
9344        String packagePath;
9345        String resourcePath;
9346        String legacyNativeLibraryDir;
9347
9348        /** New install */
9349        AsecInstallArgs(InstallParams params) {
9350            super(params.origin, params.observer, params.installFlags,
9351                    params.installerPackageName, params.getManifestDigest(),
9352                    params.getUser(), null /* instruction sets */,
9353                    params.packageAbiOverride);
9354        }
9355
9356        /** Existing install */
9357        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9358                        boolean isExternal, boolean isForwardLocked) {
9359            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9360                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9361                    instructionSets, null);
9362            // Hackily pretend we're still looking at a full code path
9363            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9364                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9365            }
9366
9367            // Extract cid from fullCodePath
9368            int eidx = fullCodePath.lastIndexOf("/");
9369            String subStr1 = fullCodePath.substring(0, eidx);
9370            int sidx = subStr1.lastIndexOf("/");
9371            cid = subStr1.substring(sidx+1, eidx);
9372            setMountPath(subStr1);
9373        }
9374
9375        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9376            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9377                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9378                    instructionSets, null);
9379            this.cid = cid;
9380            setMountPath(PackageHelper.getSdDir(cid));
9381        }
9382
9383        void createCopyFile() {
9384            cid = mInstallerService.allocateExternalStageCidLegacy();
9385        }
9386
9387        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9388            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9389                    abiOverride);
9390
9391            final File target;
9392            if (isExternal()) {
9393                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9394            } else {
9395                target = Environment.getDataDirectory();
9396            }
9397
9398            final StorageManager storage = StorageManager.from(mContext);
9399            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9400        }
9401
9402        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9403            if (origin.staged) {
9404                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9405                cid = origin.cid;
9406                setMountPath(PackageHelper.getSdDir(cid));
9407                return PackageManager.INSTALL_SUCCEEDED;
9408            }
9409
9410            if (temp) {
9411                createCopyFile();
9412            } else {
9413                /*
9414                 * Pre-emptively destroy the container since it's destroyed if
9415                 * copying fails due to it existing anyway.
9416                 */
9417                PackageHelper.destroySdDir(cid);
9418            }
9419
9420            final String newMountPath = imcs.copyPackageToContainer(
9421                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9422                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9423
9424            if (newMountPath != null) {
9425                setMountPath(newMountPath);
9426                return PackageManager.INSTALL_SUCCEEDED;
9427            } else {
9428                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9429            }
9430        }
9431
9432        @Override
9433        String getCodePath() {
9434            return packagePath;
9435        }
9436
9437        @Override
9438        String getResourcePath() {
9439            return resourcePath;
9440        }
9441
9442        @Override
9443        String getLegacyNativeLibraryPath() {
9444            return legacyNativeLibraryDir;
9445        }
9446
9447        int doPreInstall(int status) {
9448            if (status != PackageManager.INSTALL_SUCCEEDED) {
9449                // Destroy container
9450                PackageHelper.destroySdDir(cid);
9451            } else {
9452                boolean mounted = PackageHelper.isContainerMounted(cid);
9453                if (!mounted) {
9454                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9455                            Process.SYSTEM_UID);
9456                    if (newMountPath != null) {
9457                        setMountPath(newMountPath);
9458                    } else {
9459                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9460                    }
9461                }
9462            }
9463            return status;
9464        }
9465
9466        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9467            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9468            String newMountPath = null;
9469            if (PackageHelper.isContainerMounted(cid)) {
9470                // Unmount the container
9471                if (!PackageHelper.unMountSdDir(cid)) {
9472                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9473                    return false;
9474                }
9475            }
9476            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9477                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9478                        " which might be stale. Will try to clean up.");
9479                // Clean up the stale container and proceed to recreate.
9480                if (!PackageHelper.destroySdDir(newCacheId)) {
9481                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9482                    return false;
9483                }
9484                // Successfully cleaned up stale container. Try to rename again.
9485                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9486                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9487                            + " inspite of cleaning it up.");
9488                    return false;
9489                }
9490            }
9491            if (!PackageHelper.isContainerMounted(newCacheId)) {
9492                Slog.w(TAG, "Mounting container " + newCacheId);
9493                newMountPath = PackageHelper.mountSdDir(newCacheId,
9494                        getEncryptKey(), Process.SYSTEM_UID);
9495            } else {
9496                newMountPath = PackageHelper.getSdDir(newCacheId);
9497            }
9498            if (newMountPath == null) {
9499                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9500                return false;
9501            }
9502            Log.i(TAG, "Succesfully renamed " + cid +
9503                    " to " + newCacheId +
9504                    " at new path: " + newMountPath);
9505            cid = newCacheId;
9506
9507            final File beforeCodeFile = new File(packagePath);
9508            setMountPath(newMountPath);
9509            final File afterCodeFile = new File(packagePath);
9510
9511            // Reflect the rename in scanned details
9512            pkg.codePath = afterCodeFile.getAbsolutePath();
9513            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9514                    pkg.baseCodePath);
9515            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9516                    pkg.splitCodePaths);
9517
9518            // Reflect the rename in app info
9519            pkg.applicationInfo.setCodePath(pkg.codePath);
9520            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9521            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9522            pkg.applicationInfo.setResourcePath(pkg.codePath);
9523            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9524            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9525
9526            return true;
9527        }
9528
9529        private void setMountPath(String mountPath) {
9530            final File mountFile = new File(mountPath);
9531
9532            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9533            if (monolithicFile.exists()) {
9534                packagePath = monolithicFile.getAbsolutePath();
9535                if (isFwdLocked()) {
9536                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9537                } else {
9538                    resourcePath = packagePath;
9539                }
9540            } else {
9541                packagePath = mountFile.getAbsolutePath();
9542                resourcePath = packagePath;
9543            }
9544
9545            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9546        }
9547
9548        int doPostInstall(int status, int uid) {
9549            if (status != PackageManager.INSTALL_SUCCEEDED) {
9550                cleanUp();
9551            } else {
9552                final int groupOwner;
9553                final String protectedFile;
9554                if (isFwdLocked()) {
9555                    groupOwner = UserHandle.getSharedAppGid(uid);
9556                    protectedFile = RES_FILE_NAME;
9557                } else {
9558                    groupOwner = -1;
9559                    protectedFile = null;
9560                }
9561
9562                if (uid < Process.FIRST_APPLICATION_UID
9563                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9564                    Slog.e(TAG, "Failed to finalize " + cid);
9565                    PackageHelper.destroySdDir(cid);
9566                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9567                }
9568
9569                boolean mounted = PackageHelper.isContainerMounted(cid);
9570                if (!mounted) {
9571                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9572                }
9573            }
9574            return status;
9575        }
9576
9577        private void cleanUp() {
9578            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9579
9580            // Destroy secure container
9581            PackageHelper.destroySdDir(cid);
9582        }
9583
9584        private List<String> getAllCodePaths() {
9585            final File codeFile = new File(getCodePath());
9586            if (codeFile != null && codeFile.exists()) {
9587                try {
9588                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9589                    return pkg.getAllCodePaths();
9590                } catch (PackageParserException e) {
9591                    // Ignored; we tried our best
9592                }
9593            }
9594            return Collections.EMPTY_LIST;
9595        }
9596
9597        void cleanUpResourcesLI() {
9598            // Enumerate all code paths before deleting
9599            cleanUpResourcesLI(getAllCodePaths());
9600        }
9601
9602        private void cleanUpResourcesLI(List<String> allCodePaths) {
9603            cleanUp();
9604
9605            if (!allCodePaths.isEmpty()) {
9606                if (instructionSets == null) {
9607                    throw new IllegalStateException("instructionSet == null");
9608                }
9609                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9610                for (String codePath : allCodePaths) {
9611                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9612                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9613                        if (retCode < 0) {
9614                            Slog.w(TAG, "Couldn't remove dex file for package: "
9615                                    + " at location " + codePath + ", retcode=" + retCode);
9616                            // we don't consider this to be a failure of the core package deletion
9617                        }
9618                    }
9619                }
9620            }
9621        }
9622
9623        boolean matchContainer(String app) {
9624            if (cid.startsWith(app)) {
9625                return true;
9626            }
9627            return false;
9628        }
9629
9630        String getPackageName() {
9631            return getAsecPackageName(cid);
9632        }
9633
9634        boolean doPostDeleteLI(boolean delete) {
9635            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9636            final List<String> allCodePaths = getAllCodePaths();
9637            boolean mounted = PackageHelper.isContainerMounted(cid);
9638            if (mounted) {
9639                // Unmount first
9640                if (PackageHelper.unMountSdDir(cid)) {
9641                    mounted = false;
9642                }
9643            }
9644            if (!mounted && delete) {
9645                cleanUpResourcesLI(allCodePaths);
9646            }
9647            return !mounted;
9648        }
9649
9650        @Override
9651        int doPreCopy() {
9652            if (isFwdLocked()) {
9653                if (!PackageHelper.fixSdPermissions(cid,
9654                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9655                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9656                }
9657            }
9658
9659            return PackageManager.INSTALL_SUCCEEDED;
9660        }
9661
9662        @Override
9663        int doPostCopy(int uid) {
9664            if (isFwdLocked()) {
9665                if (uid < Process.FIRST_APPLICATION_UID
9666                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9667                                RES_FILE_NAME)) {
9668                    Slog.e(TAG, "Failed to finalize " + cid);
9669                    PackageHelper.destroySdDir(cid);
9670                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9671                }
9672            }
9673
9674            return PackageManager.INSTALL_SUCCEEDED;
9675        }
9676    }
9677
9678    static String getAsecPackageName(String packageCid) {
9679        int idx = packageCid.lastIndexOf("-");
9680        if (idx == -1) {
9681            return packageCid;
9682        }
9683        return packageCid.substring(0, idx);
9684    }
9685
9686    // Utility method used to create code paths based on package name and available index.
9687    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9688        String idxStr = "";
9689        int idx = 1;
9690        // Fall back to default value of idx=1 if prefix is not
9691        // part of oldCodePath
9692        if (oldCodePath != null) {
9693            String subStr = oldCodePath;
9694            // Drop the suffix right away
9695            if (suffix != null && subStr.endsWith(suffix)) {
9696                subStr = subStr.substring(0, subStr.length() - suffix.length());
9697            }
9698            // If oldCodePath already contains prefix find out the
9699            // ending index to either increment or decrement.
9700            int sidx = subStr.lastIndexOf(prefix);
9701            if (sidx != -1) {
9702                subStr = subStr.substring(sidx + prefix.length());
9703                if (subStr != null) {
9704                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9705                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9706                    }
9707                    try {
9708                        idx = Integer.parseInt(subStr);
9709                        if (idx <= 1) {
9710                            idx++;
9711                        } else {
9712                            idx--;
9713                        }
9714                    } catch(NumberFormatException e) {
9715                    }
9716                }
9717            }
9718        }
9719        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9720        return prefix + idxStr;
9721    }
9722
9723    private File getNextCodePath(String packageName) {
9724        int suffix = 1;
9725        File result;
9726        do {
9727            result = new File(mAppInstallDir, packageName + "-" + suffix);
9728            suffix++;
9729        } while (result.exists());
9730        return result;
9731    }
9732
9733    // Utility method used to ignore ADD/REMOVE events
9734    // by directory observer.
9735    private static boolean ignoreCodePath(String fullPathStr) {
9736        String apkName = deriveCodePathName(fullPathStr);
9737        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9738        if (idx != -1 && ((idx+1) < apkName.length())) {
9739            // Make sure the package ends with a numeral
9740            String version = apkName.substring(idx+1);
9741            try {
9742                Integer.parseInt(version);
9743                return true;
9744            } catch (NumberFormatException e) {}
9745        }
9746        return false;
9747    }
9748
9749    // Utility method that returns the relative package path with respect
9750    // to the installation directory. Like say for /data/data/com.test-1.apk
9751    // string com.test-1 is returned.
9752    static String deriveCodePathName(String codePath) {
9753        if (codePath == null) {
9754            return null;
9755        }
9756        final File codeFile = new File(codePath);
9757        final String name = codeFile.getName();
9758        if (codeFile.isDirectory()) {
9759            return name;
9760        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9761            final int lastDot = name.lastIndexOf('.');
9762            return name.substring(0, lastDot);
9763        } else {
9764            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9765            return null;
9766        }
9767    }
9768
9769    class PackageInstalledInfo {
9770        String name;
9771        int uid;
9772        // The set of users that originally had this package installed.
9773        int[] origUsers;
9774        // The set of users that now have this package installed.
9775        int[] newUsers;
9776        PackageParser.Package pkg;
9777        int returnCode;
9778        String returnMsg;
9779        PackageRemovedInfo removedInfo;
9780
9781        public void setError(int code, String msg) {
9782            returnCode = code;
9783            returnMsg = msg;
9784            Slog.w(TAG, msg);
9785        }
9786
9787        public void setError(String msg, PackageParserException e) {
9788            returnCode = e.error;
9789            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9790            Slog.w(TAG, msg, e);
9791        }
9792
9793        public void setError(String msg, PackageManagerException e) {
9794            returnCode = e.error;
9795            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9796            Slog.w(TAG, msg, e);
9797        }
9798
9799        // In some error cases we want to convey more info back to the observer
9800        String origPackage;
9801        String origPermission;
9802    }
9803
9804    /*
9805     * Install a non-existing package.
9806     */
9807    private void installNewPackageLI(PackageParser.Package pkg,
9808            int parseFlags, int scanFlags, UserHandle user,
9809            String installerPackageName, PackageInstalledInfo res) {
9810        // Remember this for later, in case we need to rollback this install
9811        String pkgName = pkg.packageName;
9812
9813        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9814        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9815        synchronized(mPackages) {
9816            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9817                // A package with the same name is already installed, though
9818                // it has been renamed to an older name.  The package we
9819                // are trying to install should be installed as an update to
9820                // the existing one, but that has not been requested, so bail.
9821                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9822                        + " without first uninstalling package running as "
9823                        + mSettings.mRenamedPackages.get(pkgName));
9824                return;
9825            }
9826            if (mPackages.containsKey(pkgName)) {
9827                // Don't allow installation over an existing package with the same name.
9828                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9829                        + " without first uninstalling.");
9830                return;
9831            }
9832        }
9833
9834        try {
9835            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9836                    System.currentTimeMillis(), user);
9837
9838            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9839            // delete the partially installed application. the data directory will have to be
9840            // restored if it was already existing
9841            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9842                // remove package from internal structures.  Note that we want deletePackageX to
9843                // delete the package data and cache directories that it created in
9844                // scanPackageLocked, unless those directories existed before we even tried to
9845                // install.
9846                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9847                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9848                                res.removedInfo, true);
9849            }
9850
9851        } catch (PackageManagerException e) {
9852            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9853        }
9854    }
9855
9856    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9857        // Upgrade keysets are being used.  Determine if new package has a superset of the
9858        // required keys.
9859        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9860        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9861        for (int i = 0; i < upgradeKeySets.length; i++) {
9862            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9863            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9864                return true;
9865            }
9866        }
9867        return false;
9868    }
9869
9870    private void replacePackageLI(PackageParser.Package pkg,
9871            int parseFlags, int scanFlags, UserHandle user,
9872            String installerPackageName, PackageInstalledInfo res) {
9873        PackageParser.Package oldPackage;
9874        String pkgName = pkg.packageName;
9875        int[] allUsers;
9876        boolean[] perUserInstalled;
9877
9878        // First find the old package info and check signatures
9879        synchronized(mPackages) {
9880            oldPackage = mPackages.get(pkgName);
9881            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9882            PackageSetting ps = mSettings.mPackages.get(pkgName);
9883            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9884                // default to original signature matching
9885                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9886                    != PackageManager.SIGNATURE_MATCH) {
9887                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9888                            "New package has a different signature: " + pkgName);
9889                    return;
9890                }
9891            } else {
9892                if(!checkUpgradeKeySetLP(ps, pkg)) {
9893                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9894                            "New package not signed by keys specified by upgrade-keysets: "
9895                            + pkgName);
9896                    return;
9897                }
9898            }
9899
9900            // In case of rollback, remember per-user/profile install state
9901            allUsers = sUserManager.getUserIds();
9902            perUserInstalled = new boolean[allUsers.length];
9903            for (int i = 0; i < allUsers.length; i++) {
9904                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9905            }
9906        }
9907
9908        boolean sysPkg = (isSystemApp(oldPackage));
9909        if (sysPkg) {
9910            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9911                    user, allUsers, perUserInstalled, installerPackageName, res);
9912        } else {
9913            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9914                    user, allUsers, perUserInstalled, installerPackageName, res);
9915        }
9916    }
9917
9918    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9919            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9920            int[] allUsers, boolean[] perUserInstalled,
9921            String installerPackageName, PackageInstalledInfo res) {
9922        String pkgName = deletedPackage.packageName;
9923        boolean deletedPkg = true;
9924        boolean updatedSettings = false;
9925
9926        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9927                + deletedPackage);
9928        long origUpdateTime;
9929        if (pkg.mExtras != null) {
9930            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9931        } else {
9932            origUpdateTime = 0;
9933        }
9934
9935        // First delete the existing package while retaining the data directory
9936        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9937                res.removedInfo, true)) {
9938            // If the existing package wasn't successfully deleted
9939            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9940            deletedPkg = false;
9941        } else {
9942            // Successfully deleted the old package; proceed with replace.
9943
9944            // If deleted package lived in a container, give users a chance to
9945            // relinquish resources before killing.
9946            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9947                if (DEBUG_INSTALL) {
9948                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9949                }
9950                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9951                final ArrayList<String> pkgList = new ArrayList<String>(1);
9952                pkgList.add(deletedPackage.applicationInfo.packageName);
9953                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9954            }
9955
9956            deleteCodeCacheDirsLI(pkgName);
9957            try {
9958                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9959                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9960                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9961                updatedSettings = true;
9962            } catch (PackageManagerException e) {
9963                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9964            }
9965        }
9966
9967        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9968            // remove package from internal structures.  Note that we want deletePackageX to
9969            // delete the package data and cache directories that it created in
9970            // scanPackageLocked, unless those directories existed before we even tried to
9971            // install.
9972            if(updatedSettings) {
9973                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9974                deletePackageLI(
9975                        pkgName, null, true, allUsers, perUserInstalled,
9976                        PackageManager.DELETE_KEEP_DATA,
9977                                res.removedInfo, true);
9978            }
9979            // Since we failed to install the new package we need to restore the old
9980            // package that we deleted.
9981            if (deletedPkg) {
9982                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9983                File restoreFile = new File(deletedPackage.codePath);
9984                // Parse old package
9985                boolean oldOnSd = isExternal(deletedPackage);
9986                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9987                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9988                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9989                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9990                try {
9991                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9992                } catch (PackageManagerException e) {
9993                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9994                            + e.getMessage());
9995                    return;
9996                }
9997                // Restore of old package succeeded. Update permissions.
9998                // writer
9999                synchronized (mPackages) {
10000                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10001                            UPDATE_PERMISSIONS_ALL);
10002                    // can downgrade to reader
10003                    mSettings.writeLPr();
10004                }
10005                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10006            }
10007        }
10008    }
10009
10010    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10011            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10012            int[] allUsers, boolean[] perUserInstalled,
10013            String installerPackageName, PackageInstalledInfo res) {
10014        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10015                + ", old=" + deletedPackage);
10016        boolean updatedSettings = false;
10017        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10018        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10019            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10020        }
10021        String packageName = deletedPackage.packageName;
10022        if (packageName == null) {
10023            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10024                    "Attempt to delete null packageName.");
10025            return;
10026        }
10027        PackageParser.Package oldPkg;
10028        PackageSetting oldPkgSetting;
10029        // reader
10030        synchronized (mPackages) {
10031            oldPkg = mPackages.get(packageName);
10032            oldPkgSetting = mSettings.mPackages.get(packageName);
10033            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10034                    (oldPkgSetting == null)) {
10035                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10036                        "Couldn't find package:" + packageName + " information");
10037                return;
10038            }
10039        }
10040
10041        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10042
10043        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10044        res.removedInfo.removedPackage = packageName;
10045        // Remove existing system package
10046        removePackageLI(oldPkgSetting, true);
10047        // writer
10048        synchronized (mPackages) {
10049            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10050                // We didn't need to disable the .apk as a current system package,
10051                // which means we are replacing another update that is already
10052                // installed.  We need to make sure to delete the older one's .apk.
10053                res.removedInfo.args = createInstallArgsForExisting(0,
10054                        deletedPackage.applicationInfo.getCodePath(),
10055                        deletedPackage.applicationInfo.getResourcePath(),
10056                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10057                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10058            } else {
10059                res.removedInfo.args = null;
10060            }
10061        }
10062
10063        // Successfully disabled the old package. Now proceed with re-installation
10064        deleteCodeCacheDirsLI(packageName);
10065
10066        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10067        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10068
10069        PackageParser.Package newPackage = null;
10070        try {
10071            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10072            if (newPackage.mExtras != null) {
10073                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10074                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10075                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10076
10077                // is the update attempting to change shared user? that isn't going to work...
10078                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10079                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10080                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10081                            + " to " + newPkgSetting.sharedUser);
10082                    updatedSettings = true;
10083                }
10084            }
10085
10086            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10087                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10088                updatedSettings = true;
10089            }
10090
10091        } catch (PackageManagerException e) {
10092            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10093        }
10094
10095        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10096            // Re installation failed. Restore old information
10097            // Remove new pkg information
10098            if (newPackage != null) {
10099                removeInstalledPackageLI(newPackage, true);
10100            }
10101            // Add back the old system package
10102            try {
10103                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10104            } catch (PackageManagerException e) {
10105                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10106            }
10107            // Restore the old system information in Settings
10108            synchronized(mPackages) {
10109                if (updatedSettings) {
10110                    mSettings.enableSystemPackageLPw(packageName);
10111                    mSettings.setInstallerPackageName(packageName,
10112                            oldPkgSetting.installerPackageName);
10113                }
10114                mSettings.writeLPr();
10115            }
10116        }
10117    }
10118
10119    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10120            int[] allUsers, boolean[] perUserInstalled,
10121            PackageInstalledInfo res) {
10122        String pkgName = newPackage.packageName;
10123        synchronized (mPackages) {
10124            //write settings. the installStatus will be incomplete at this stage.
10125            //note that the new package setting would have already been
10126            //added to mPackages. It hasn't been persisted yet.
10127            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10128            mSettings.writeLPr();
10129        }
10130
10131        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10132
10133        synchronized (mPackages) {
10134            updatePermissionsLPw(newPackage.packageName, newPackage,
10135                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10136                            ? UPDATE_PERMISSIONS_ALL : 0));
10137            // For system-bundled packages, we assume that installing an upgraded version
10138            // of the package implies that the user actually wants to run that new code,
10139            // so we enable the package.
10140            if (isSystemApp(newPackage)) {
10141                // NB: implicit assumption that system package upgrades apply to all users
10142                if (DEBUG_INSTALL) {
10143                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10144                }
10145                PackageSetting ps = mSettings.mPackages.get(pkgName);
10146                if (ps != null) {
10147                    if (res.origUsers != null) {
10148                        for (int userHandle : res.origUsers) {
10149                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10150                                    userHandle, installerPackageName);
10151                        }
10152                    }
10153                    // Also convey the prior install/uninstall state
10154                    if (allUsers != null && perUserInstalled != null) {
10155                        for (int i = 0; i < allUsers.length; i++) {
10156                            if (DEBUG_INSTALL) {
10157                                Slog.d(TAG, "    user " + allUsers[i]
10158                                        + " => " + perUserInstalled[i]);
10159                            }
10160                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10161                        }
10162                        // these install state changes will be persisted in the
10163                        // upcoming call to mSettings.writeLPr().
10164                    }
10165                }
10166            }
10167            res.name = pkgName;
10168            res.uid = newPackage.applicationInfo.uid;
10169            res.pkg = newPackage;
10170            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10171            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10172            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10173            //to update install status
10174            mSettings.writeLPr();
10175        }
10176    }
10177
10178    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10179        final int installFlags = args.installFlags;
10180        String installerPackageName = args.installerPackageName;
10181        File tmpPackageFile = new File(args.getCodePath());
10182        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10183        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10184        boolean replace = false;
10185        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10186        // Result object to be returned
10187        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10188
10189        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10190        // Retrieve PackageSettings and parse package
10191        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10192                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10193                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10194        PackageParser pp = new PackageParser();
10195        pp.setSeparateProcesses(mSeparateProcesses);
10196        pp.setDisplayMetrics(mMetrics);
10197
10198        final PackageParser.Package pkg;
10199        try {
10200            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10201        } catch (PackageParserException e) {
10202            res.setError("Failed parse during installPackageLI", e);
10203            return;
10204        }
10205
10206        // Mark that we have an install time CPU ABI override.
10207        pkg.cpuAbiOverride = args.abiOverride;
10208
10209        String pkgName = res.name = pkg.packageName;
10210        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10211            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10212                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10213                return;
10214            }
10215        }
10216
10217        try {
10218            pp.collectCertificates(pkg, parseFlags);
10219            pp.collectManifestDigest(pkg);
10220        } catch (PackageParserException e) {
10221            res.setError("Failed collect during installPackageLI", e);
10222            return;
10223        }
10224
10225        /* If the installer passed in a manifest digest, compare it now. */
10226        if (args.manifestDigest != null) {
10227            if (DEBUG_INSTALL) {
10228                final String parsedManifest = pkg.manifestDigest == null ? "null"
10229                        : pkg.manifestDigest.toString();
10230                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10231                        + parsedManifest);
10232            }
10233
10234            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10235                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10236                return;
10237            }
10238        } else if (DEBUG_INSTALL) {
10239            final String parsedManifest = pkg.manifestDigest == null
10240                    ? "null" : pkg.manifestDigest.toString();
10241            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10242        }
10243
10244        // Get rid of all references to package scan path via parser.
10245        pp = null;
10246        String oldCodePath = null;
10247        boolean systemApp = false;
10248        synchronized (mPackages) {
10249            // Check whether the newly-scanned package wants to define an already-defined perm
10250            int N = pkg.permissions.size();
10251            for (int i = N-1; i >= 0; i--) {
10252                PackageParser.Permission perm = pkg.permissions.get(i);
10253                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10254                if (bp != null) {
10255                    // If the defining package is signed with our cert, it's okay.  This
10256                    // also includes the "updating the same package" case, of course.
10257                    // "updating same package" could also involve key-rotation.
10258                    final boolean sigsOk;
10259                    if (!bp.sourcePackage.equals(pkg.packageName)
10260                            || !(bp.packageSetting instanceof PackageSetting)
10261                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10262                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10263                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10264                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10265                    } else {
10266                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10267                    }
10268                    if (!sigsOk) {
10269                        // If the owning package is the system itself, we log but allow
10270                        // install to proceed; we fail the install on all other permission
10271                        // redefinitions.
10272                        if (!bp.sourcePackage.equals("android")) {
10273                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10274                                    + pkg.packageName + " attempting to redeclare permission "
10275                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10276                            res.origPermission = perm.info.name;
10277                            res.origPackage = bp.sourcePackage;
10278                            return;
10279                        } else {
10280                            Slog.w(TAG, "Package " + pkg.packageName
10281                                    + " attempting to redeclare system permission "
10282                                    + perm.info.name + "; ignoring new declaration");
10283                            pkg.permissions.remove(i);
10284                        }
10285                    }
10286                }
10287            }
10288
10289            // Check if installing already existing package
10290            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10291                String oldName = mSettings.mRenamedPackages.get(pkgName);
10292                if (pkg.mOriginalPackages != null
10293                        && pkg.mOriginalPackages.contains(oldName)
10294                        && mPackages.containsKey(oldName)) {
10295                    // This package is derived from an original package,
10296                    // and this device has been updating from that original
10297                    // name.  We must continue using the original name, so
10298                    // rename the new package here.
10299                    pkg.setPackageName(oldName);
10300                    pkgName = pkg.packageName;
10301                    replace = true;
10302                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10303                            + oldName + " pkgName=" + pkgName);
10304                } else if (mPackages.containsKey(pkgName)) {
10305                    // This package, under its official name, already exists
10306                    // on the device; we should replace it.
10307                    replace = true;
10308                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10309                }
10310            }
10311            PackageSetting ps = mSettings.mPackages.get(pkgName);
10312            if (ps != null) {
10313                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10314                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10315                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10316                    systemApp = (ps.pkg.applicationInfo.flags &
10317                            ApplicationInfo.FLAG_SYSTEM) != 0;
10318                }
10319                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10320            }
10321        }
10322
10323        if (systemApp && onSd) {
10324            // Disable updates to system apps on sdcard
10325            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10326                    "Cannot install updates to system apps on sdcard");
10327            return;
10328        }
10329
10330        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10331            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10332            return;
10333        }
10334
10335        if (replace) {
10336            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10337                    installerPackageName, res);
10338        } else {
10339            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10340                    args.user, installerPackageName, res);
10341        }
10342        synchronized (mPackages) {
10343            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10344            if (ps != null) {
10345                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10346            }
10347        }
10348    }
10349
10350    private static boolean isForwardLocked(PackageParser.Package pkg) {
10351        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10352    }
10353
10354    private static boolean isForwardLocked(ApplicationInfo info) {
10355        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10356    }
10357
10358    private boolean isForwardLocked(PackageSetting ps) {
10359        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10360    }
10361
10362    private static boolean isMultiArch(PackageSetting ps) {
10363        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10364    }
10365
10366    private static boolean isMultiArch(ApplicationInfo info) {
10367        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10368    }
10369
10370    private static boolean isExternal(PackageParser.Package pkg) {
10371        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10372    }
10373
10374    private static boolean isExternal(PackageSetting ps) {
10375        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10376    }
10377
10378    private static boolean isExternal(ApplicationInfo info) {
10379        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10380    }
10381
10382    private static boolean isSystemApp(PackageParser.Package pkg) {
10383        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10384    }
10385
10386    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10387        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10388    }
10389
10390    private static boolean isSystemApp(ApplicationInfo info) {
10391        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10392    }
10393
10394    private static boolean isSystemApp(PackageSetting ps) {
10395        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10396    }
10397
10398    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10399        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10400    }
10401
10402    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10403        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10404    }
10405
10406    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10407        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10408    }
10409
10410    private int packageFlagsToInstallFlags(PackageSetting ps) {
10411        int installFlags = 0;
10412        if (isExternal(ps)) {
10413            installFlags |= PackageManager.INSTALL_EXTERNAL;
10414        }
10415        if (isForwardLocked(ps)) {
10416            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10417        }
10418        return installFlags;
10419    }
10420
10421    private void deleteTempPackageFiles() {
10422        final FilenameFilter filter = new FilenameFilter() {
10423            public boolean accept(File dir, String name) {
10424                return name.startsWith("vmdl") && name.endsWith(".tmp");
10425            }
10426        };
10427        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10428            file.delete();
10429        }
10430    }
10431
10432    @Override
10433    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10434            int flags) {
10435        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10436                flags);
10437    }
10438
10439    @Override
10440    public void deletePackage(final String packageName,
10441            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10442        mContext.enforceCallingOrSelfPermission(
10443                android.Manifest.permission.DELETE_PACKAGES, null);
10444        final int uid = Binder.getCallingUid();
10445        if (UserHandle.getUserId(uid) != userId) {
10446            mContext.enforceCallingPermission(
10447                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10448                    "deletePackage for user " + userId);
10449        }
10450        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10451            try {
10452                observer.onPackageDeleted(packageName,
10453                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10454            } catch (RemoteException re) {
10455            }
10456            return;
10457        }
10458
10459        boolean uninstallBlocked = false;
10460        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10461            int[] users = sUserManager.getUserIds();
10462            for (int i = 0; i < users.length; ++i) {
10463                if (getBlockUninstallForUser(packageName, users[i])) {
10464                    uninstallBlocked = true;
10465                    break;
10466                }
10467            }
10468        } else {
10469            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10470        }
10471        if (uninstallBlocked) {
10472            try {
10473                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10474                        null);
10475            } catch (RemoteException re) {
10476            }
10477            return;
10478        }
10479
10480        if (DEBUG_REMOVE) {
10481            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10482        }
10483        // Queue up an async operation since the package deletion may take a little while.
10484        mHandler.post(new Runnable() {
10485            public void run() {
10486                mHandler.removeCallbacks(this);
10487                final int returnCode = deletePackageX(packageName, userId, flags);
10488                if (observer != null) {
10489                    try {
10490                        observer.onPackageDeleted(packageName, returnCode, null);
10491                    } catch (RemoteException e) {
10492                        Log.i(TAG, "Observer no longer exists.");
10493                    } //end catch
10494                } //end if
10495            } //end run
10496        });
10497    }
10498
10499    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10500        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10501                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10502        try {
10503            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10504                    || dpm.isDeviceOwner(packageName))) {
10505                return true;
10506            }
10507        } catch (RemoteException e) {
10508        }
10509        return false;
10510    }
10511
10512    /**
10513     *  This method is an internal method that could be get invoked either
10514     *  to delete an installed package or to clean up a failed installation.
10515     *  After deleting an installed package, a broadcast is sent to notify any
10516     *  listeners that the package has been installed. For cleaning up a failed
10517     *  installation, the broadcast is not necessary since the package's
10518     *  installation wouldn't have sent the initial broadcast either
10519     *  The key steps in deleting a package are
10520     *  deleting the package information in internal structures like mPackages,
10521     *  deleting the packages base directories through installd
10522     *  updating mSettings to reflect current status
10523     *  persisting settings for later use
10524     *  sending a broadcast if necessary
10525     */
10526    private int deletePackageX(String packageName, int userId, int flags) {
10527        final PackageRemovedInfo info = new PackageRemovedInfo();
10528        final boolean res;
10529
10530        if (isPackageDeviceAdmin(packageName, userId)) {
10531            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10532            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10533        }
10534
10535        boolean removedForAllUsers = false;
10536        boolean systemUpdate = false;
10537
10538        // for the uninstall-updates case and restricted profiles, remember the per-
10539        // userhandle installed state
10540        int[] allUsers;
10541        boolean[] perUserInstalled;
10542        synchronized (mPackages) {
10543            PackageSetting ps = mSettings.mPackages.get(packageName);
10544            allUsers = sUserManager.getUserIds();
10545            perUserInstalled = new boolean[allUsers.length];
10546            for (int i = 0; i < allUsers.length; i++) {
10547                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10548            }
10549        }
10550
10551        synchronized (mInstallLock) {
10552            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10553            res = deletePackageLI(packageName,
10554                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10555                            ? UserHandle.ALL : new UserHandle(userId),
10556                    true, allUsers, perUserInstalled,
10557                    flags | REMOVE_CHATTY, info, true);
10558            systemUpdate = info.isRemovedPackageSystemUpdate;
10559            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10560                removedForAllUsers = true;
10561            }
10562            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10563                    + " removedForAllUsers=" + removedForAllUsers);
10564        }
10565
10566        if (res) {
10567            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10568
10569            // If the removed package was a system update, the old system package
10570            // was re-enabled; we need to broadcast this information
10571            if (systemUpdate) {
10572                Bundle extras = new Bundle(1);
10573                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10574                        ? info.removedAppId : info.uid);
10575                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10576
10577                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10578                        extras, null, null, null);
10579                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10580                        extras, null, null, null);
10581                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10582                        null, packageName, null, null);
10583            }
10584        }
10585        // Force a gc here.
10586        Runtime.getRuntime().gc();
10587        // Delete the resources here after sending the broadcast to let
10588        // other processes clean up before deleting resources.
10589        if (info.args != null) {
10590            synchronized (mInstallLock) {
10591                info.args.doPostDeleteLI(true);
10592            }
10593        }
10594
10595        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10596    }
10597
10598    static class PackageRemovedInfo {
10599        String removedPackage;
10600        int uid = -1;
10601        int removedAppId = -1;
10602        int[] removedUsers = null;
10603        boolean isRemovedPackageSystemUpdate = false;
10604        // Clean up resources deleted packages.
10605        InstallArgs args = null;
10606
10607        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10608            Bundle extras = new Bundle(1);
10609            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10610            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10611            if (replacing) {
10612                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10613            }
10614            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10615            if (removedPackage != null) {
10616                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10617                        extras, null, null, removedUsers);
10618                if (fullRemove && !replacing) {
10619                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10620                            extras, null, null, removedUsers);
10621                }
10622            }
10623            if (removedAppId >= 0) {
10624                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10625                        removedUsers);
10626            }
10627        }
10628    }
10629
10630    /*
10631     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10632     * flag is not set, the data directory is removed as well.
10633     * make sure this flag is set for partially installed apps. If not its meaningless to
10634     * delete a partially installed application.
10635     */
10636    private void removePackageDataLI(PackageSetting ps,
10637            int[] allUserHandles, boolean[] perUserInstalled,
10638            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10639        String packageName = ps.name;
10640        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10641        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10642        // Retrieve object to delete permissions for shared user later on
10643        final PackageSetting deletedPs;
10644        // reader
10645        synchronized (mPackages) {
10646            deletedPs = mSettings.mPackages.get(packageName);
10647            if (outInfo != null) {
10648                outInfo.removedPackage = packageName;
10649                outInfo.removedUsers = deletedPs != null
10650                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10651                        : null;
10652            }
10653        }
10654        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10655            removeDataDirsLI(packageName);
10656            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10657        }
10658        // writer
10659        synchronized (mPackages) {
10660            if (deletedPs != null) {
10661                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10662                    if (outInfo != null) {
10663                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10664                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10665                    }
10666                    if (deletedPs != null) {
10667                        updatePermissionsLPw(deletedPs.name, null, 0);
10668                        if (deletedPs.sharedUser != null) {
10669                            // remove permissions associated with package
10670                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10671                        }
10672                    }
10673                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10674                }
10675                // make sure to preserve per-user disabled state if this removal was just
10676                // a downgrade of a system app to the factory package
10677                if (allUserHandles != null && perUserInstalled != null) {
10678                    if (DEBUG_REMOVE) {
10679                        Slog.d(TAG, "Propagating install state across downgrade");
10680                    }
10681                    for (int i = 0; i < allUserHandles.length; i++) {
10682                        if (DEBUG_REMOVE) {
10683                            Slog.d(TAG, "    user " + allUserHandles[i]
10684                                    + " => " + perUserInstalled[i]);
10685                        }
10686                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10687                    }
10688                }
10689            }
10690            // can downgrade to reader
10691            if (writeSettings) {
10692                // Save settings now
10693                mSettings.writeLPr();
10694            }
10695        }
10696        if (outInfo != null) {
10697            // A user ID was deleted here. Go through all users and remove it
10698            // from KeyStore.
10699            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10700        }
10701    }
10702
10703    static boolean locationIsPrivileged(File path) {
10704        try {
10705            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10706                    .getCanonicalPath();
10707            return path.getCanonicalPath().startsWith(privilegedAppDir);
10708        } catch (IOException e) {
10709            Slog.e(TAG, "Unable to access code path " + path);
10710        }
10711        return false;
10712    }
10713
10714    /*
10715     * Tries to delete system package.
10716     */
10717    private boolean deleteSystemPackageLI(PackageSetting newPs,
10718            int[] allUserHandles, boolean[] perUserInstalled,
10719            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10720        final boolean applyUserRestrictions
10721                = (allUserHandles != null) && (perUserInstalled != null);
10722        PackageSetting disabledPs = null;
10723        // Confirm if the system package has been updated
10724        // An updated system app can be deleted. This will also have to restore
10725        // the system pkg from system partition
10726        // reader
10727        synchronized (mPackages) {
10728            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10729        }
10730        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10731                + " disabledPs=" + disabledPs);
10732        if (disabledPs == null) {
10733            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10734            return false;
10735        } else if (DEBUG_REMOVE) {
10736            Slog.d(TAG, "Deleting system pkg from data partition");
10737        }
10738        if (DEBUG_REMOVE) {
10739            if (applyUserRestrictions) {
10740                Slog.d(TAG, "Remembering install states:");
10741                for (int i = 0; i < allUserHandles.length; i++) {
10742                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10743                }
10744            }
10745        }
10746        // Delete the updated package
10747        outInfo.isRemovedPackageSystemUpdate = true;
10748        if (disabledPs.versionCode < newPs.versionCode) {
10749            // Delete data for downgrades
10750            flags &= ~PackageManager.DELETE_KEEP_DATA;
10751        } else {
10752            // Preserve data by setting flag
10753            flags |= PackageManager.DELETE_KEEP_DATA;
10754        }
10755        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10756                allUserHandles, perUserInstalled, outInfo, writeSettings);
10757        if (!ret) {
10758            return false;
10759        }
10760        // writer
10761        synchronized (mPackages) {
10762            // Reinstate the old system package
10763            mSettings.enableSystemPackageLPw(newPs.name);
10764            // Remove any native libraries from the upgraded package.
10765            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10766        }
10767        // Install the system package
10768        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10769        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10770        if (locationIsPrivileged(disabledPs.codePath)) {
10771            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10772        }
10773
10774        final PackageParser.Package newPkg;
10775        try {
10776            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10777        } catch (PackageManagerException e) {
10778            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10779            return false;
10780        }
10781
10782        // writer
10783        synchronized (mPackages) {
10784            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10785            updatePermissionsLPw(newPkg.packageName, newPkg,
10786                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10787            if (applyUserRestrictions) {
10788                if (DEBUG_REMOVE) {
10789                    Slog.d(TAG, "Propagating install state across reinstall");
10790                }
10791                for (int i = 0; i < allUserHandles.length; i++) {
10792                    if (DEBUG_REMOVE) {
10793                        Slog.d(TAG, "    user " + allUserHandles[i]
10794                                + " => " + perUserInstalled[i]);
10795                    }
10796                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10797                }
10798                // Regardless of writeSettings we need to ensure that this restriction
10799                // state propagation is persisted
10800                mSettings.writeAllUsersPackageRestrictionsLPr();
10801            }
10802            // can downgrade to reader here
10803            if (writeSettings) {
10804                mSettings.writeLPr();
10805            }
10806        }
10807        return true;
10808    }
10809
10810    private boolean deleteInstalledPackageLI(PackageSetting ps,
10811            boolean deleteCodeAndResources, int flags,
10812            int[] allUserHandles, boolean[] perUserInstalled,
10813            PackageRemovedInfo outInfo, boolean writeSettings) {
10814        if (outInfo != null) {
10815            outInfo.uid = ps.appId;
10816        }
10817
10818        // Delete package data from internal structures and also remove data if flag is set
10819        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10820
10821        // Delete application code and resources
10822        if (deleteCodeAndResources && (outInfo != null)) {
10823            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10824                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10825                    getAppDexInstructionSets(ps));
10826            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10827        }
10828        return true;
10829    }
10830
10831    @Override
10832    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10833            int userId) {
10834        mContext.enforceCallingOrSelfPermission(
10835                android.Manifest.permission.DELETE_PACKAGES, null);
10836        synchronized (mPackages) {
10837            PackageSetting ps = mSettings.mPackages.get(packageName);
10838            if (ps == null) {
10839                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10840                return false;
10841            }
10842            if (!ps.getInstalled(userId)) {
10843                // Can't block uninstall for an app that is not installed or enabled.
10844                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10845                return false;
10846            }
10847            ps.setBlockUninstall(blockUninstall, userId);
10848            mSettings.writePackageRestrictionsLPr(userId);
10849        }
10850        return true;
10851    }
10852
10853    @Override
10854    public boolean getBlockUninstallForUser(String packageName, int userId) {
10855        synchronized (mPackages) {
10856            PackageSetting ps = mSettings.mPackages.get(packageName);
10857            if (ps == null) {
10858                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10859                return false;
10860            }
10861            return ps.getBlockUninstall(userId);
10862        }
10863    }
10864
10865    /*
10866     * This method handles package deletion in general
10867     */
10868    private boolean deletePackageLI(String packageName, UserHandle user,
10869            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10870            int flags, PackageRemovedInfo outInfo,
10871            boolean writeSettings) {
10872        if (packageName == null) {
10873            Slog.w(TAG, "Attempt to delete null packageName.");
10874            return false;
10875        }
10876        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10877        PackageSetting ps;
10878        boolean dataOnly = false;
10879        int removeUser = -1;
10880        int appId = -1;
10881        synchronized (mPackages) {
10882            ps = mSettings.mPackages.get(packageName);
10883            if (ps == null) {
10884                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10885                return false;
10886            }
10887            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10888                    && user.getIdentifier() != UserHandle.USER_ALL) {
10889                // The caller is asking that the package only be deleted for a single
10890                // user.  To do this, we just mark its uninstalled state and delete
10891                // its data.  If this is a system app, we only allow this to happen if
10892                // they have set the special DELETE_SYSTEM_APP which requests different
10893                // semantics than normal for uninstalling system apps.
10894                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10895                ps.setUserState(user.getIdentifier(),
10896                        COMPONENT_ENABLED_STATE_DEFAULT,
10897                        false, //installed
10898                        true,  //stopped
10899                        true,  //notLaunched
10900                        false, //hidden
10901                        null, null, null,
10902                        false // blockUninstall
10903                        );
10904                if (!isSystemApp(ps)) {
10905                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10906                        // Other user still have this package installed, so all
10907                        // we need to do is clear this user's data and save that
10908                        // it is uninstalled.
10909                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10910                        removeUser = user.getIdentifier();
10911                        appId = ps.appId;
10912                        mSettings.writePackageRestrictionsLPr(removeUser);
10913                    } else {
10914                        // We need to set it back to 'installed' so the uninstall
10915                        // broadcasts will be sent correctly.
10916                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10917                        ps.setInstalled(true, user.getIdentifier());
10918                    }
10919                } else {
10920                    // This is a system app, so we assume that the
10921                    // other users still have this package installed, so all
10922                    // we need to do is clear this user's data and save that
10923                    // it is uninstalled.
10924                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10925                    removeUser = user.getIdentifier();
10926                    appId = ps.appId;
10927                    mSettings.writePackageRestrictionsLPr(removeUser);
10928                }
10929            }
10930        }
10931
10932        if (removeUser >= 0) {
10933            // From above, we determined that we are deleting this only
10934            // for a single user.  Continue the work here.
10935            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10936            if (outInfo != null) {
10937                outInfo.removedPackage = packageName;
10938                outInfo.removedAppId = appId;
10939                outInfo.removedUsers = new int[] {removeUser};
10940            }
10941            mInstaller.clearUserData(packageName, removeUser);
10942            removeKeystoreDataIfNeeded(removeUser, appId);
10943            schedulePackageCleaning(packageName, removeUser, false);
10944            return true;
10945        }
10946
10947        if (dataOnly) {
10948            // Delete application data first
10949            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10950            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10951            return true;
10952        }
10953
10954        boolean ret = false;
10955        if (isSystemApp(ps)) {
10956            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10957            // When an updated system application is deleted we delete the existing resources as well and
10958            // fall back to existing code in system partition
10959            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10960                    flags, outInfo, writeSettings);
10961        } else {
10962            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10963            // Kill application pre-emptively especially for apps on sd.
10964            killApplication(packageName, ps.appId, "uninstall pkg");
10965            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10966                    allUserHandles, perUserInstalled,
10967                    outInfo, writeSettings);
10968        }
10969
10970        return ret;
10971    }
10972
10973    private final class ClearStorageConnection implements ServiceConnection {
10974        IMediaContainerService mContainerService;
10975
10976        @Override
10977        public void onServiceConnected(ComponentName name, IBinder service) {
10978            synchronized (this) {
10979                mContainerService = IMediaContainerService.Stub.asInterface(service);
10980                notifyAll();
10981            }
10982        }
10983
10984        @Override
10985        public void onServiceDisconnected(ComponentName name) {
10986        }
10987    }
10988
10989    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10990        final boolean mounted;
10991        if (Environment.isExternalStorageEmulated()) {
10992            mounted = true;
10993        } else {
10994            final String status = Environment.getExternalStorageState();
10995
10996            mounted = status.equals(Environment.MEDIA_MOUNTED)
10997                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10998        }
10999
11000        if (!mounted) {
11001            return;
11002        }
11003
11004        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11005        int[] users;
11006        if (userId == UserHandle.USER_ALL) {
11007            users = sUserManager.getUserIds();
11008        } else {
11009            users = new int[] { userId };
11010        }
11011        final ClearStorageConnection conn = new ClearStorageConnection();
11012        if (mContext.bindServiceAsUser(
11013                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11014            try {
11015                for (int curUser : users) {
11016                    long timeout = SystemClock.uptimeMillis() + 5000;
11017                    synchronized (conn) {
11018                        long now = SystemClock.uptimeMillis();
11019                        while (conn.mContainerService == null && now < timeout) {
11020                            try {
11021                                conn.wait(timeout - now);
11022                            } catch (InterruptedException e) {
11023                            }
11024                        }
11025                    }
11026                    if (conn.mContainerService == null) {
11027                        return;
11028                    }
11029
11030                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11031                    clearDirectory(conn.mContainerService,
11032                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11033                    if (allData) {
11034                        clearDirectory(conn.mContainerService,
11035                                userEnv.buildExternalStorageAppDataDirs(packageName));
11036                        clearDirectory(conn.mContainerService,
11037                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11038                    }
11039                }
11040            } finally {
11041                mContext.unbindService(conn);
11042            }
11043        }
11044    }
11045
11046    @Override
11047    public void clearApplicationUserData(final String packageName,
11048            final IPackageDataObserver observer, final int userId) {
11049        mContext.enforceCallingOrSelfPermission(
11050                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11051        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11052        // Queue up an async operation since the package deletion may take a little while.
11053        mHandler.post(new Runnable() {
11054            public void run() {
11055                mHandler.removeCallbacks(this);
11056                final boolean succeeded;
11057                synchronized (mInstallLock) {
11058                    succeeded = clearApplicationUserDataLI(packageName, userId);
11059                }
11060                clearExternalStorageDataSync(packageName, userId, true);
11061                if (succeeded) {
11062                    // invoke DeviceStorageMonitor's update method to clear any notifications
11063                    DeviceStorageMonitorInternal
11064                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11065                    if (dsm != null) {
11066                        dsm.checkMemory();
11067                    }
11068                }
11069                if(observer != null) {
11070                    try {
11071                        observer.onRemoveCompleted(packageName, succeeded);
11072                    } catch (RemoteException e) {
11073                        Log.i(TAG, "Observer no longer exists.");
11074                    }
11075                } //end if observer
11076            } //end run
11077        });
11078    }
11079
11080    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11081        if (packageName == null) {
11082            Slog.w(TAG, "Attempt to delete null packageName.");
11083            return false;
11084        }
11085        PackageParser.Package pkg;
11086        boolean dataOnly = false;
11087        final int appId;
11088        synchronized (mPackages) {
11089            pkg = mPackages.get(packageName);
11090            if (pkg == null) {
11091                dataOnly = true;
11092                PackageSetting ps = mSettings.mPackages.get(packageName);
11093                if ((ps == null) || (ps.pkg == null)) {
11094                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11095                    return false;
11096                }
11097                pkg = ps.pkg;
11098            }
11099            if (!dataOnly) {
11100                // need to check this only for fully installed applications
11101                if (pkg == null) {
11102                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11103                    return false;
11104                }
11105                final ApplicationInfo applicationInfo = pkg.applicationInfo;
11106                if (applicationInfo == null) {
11107                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11108                    return false;
11109                }
11110            }
11111            if (pkg != null && pkg.applicationInfo != null) {
11112                appId = pkg.applicationInfo.uid;
11113            } else {
11114                appId = -1;
11115            }
11116        }
11117        int retCode = mInstaller.clearUserData(packageName, userId);
11118        if (retCode < 0) {
11119            Slog.w(TAG, "Couldn't remove cache files for package: "
11120                    + packageName);
11121            return false;
11122        }
11123        removeKeystoreDataIfNeeded(userId, appId);
11124
11125        // Create a native library symlink only if we have native libraries
11126        // and if the native libraries are 32 bit libraries. We do not provide
11127        // this symlink for 64 bit libraries.
11128        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11129                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11130            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11131            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11132                Slog.w(TAG, "Failed linking native library dir");
11133                return false;
11134            }
11135        }
11136
11137        return true;
11138    }
11139
11140    /**
11141     * Remove entries from the keystore daemon. Will only remove it if the
11142     * {@code appId} is valid.
11143     */
11144    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11145        if (appId < 0) {
11146            return;
11147        }
11148
11149        final KeyStore keyStore = KeyStore.getInstance();
11150        if (keyStore != null) {
11151            if (userId == UserHandle.USER_ALL) {
11152                for (final int individual : sUserManager.getUserIds()) {
11153                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11154                }
11155            } else {
11156                keyStore.clearUid(UserHandle.getUid(userId, appId));
11157            }
11158        } else {
11159            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11160        }
11161    }
11162
11163    @Override
11164    public void deleteApplicationCacheFiles(final String packageName,
11165            final IPackageDataObserver observer) {
11166        mContext.enforceCallingOrSelfPermission(
11167                android.Manifest.permission.DELETE_CACHE_FILES, null);
11168        // Queue up an async operation since the package deletion may take a little while.
11169        final int userId = UserHandle.getCallingUserId();
11170        mHandler.post(new Runnable() {
11171            public void run() {
11172                mHandler.removeCallbacks(this);
11173                final boolean succeded;
11174                synchronized (mInstallLock) {
11175                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11176                }
11177                clearExternalStorageDataSync(packageName, userId, false);
11178                if(observer != null) {
11179                    try {
11180                        observer.onRemoveCompleted(packageName, succeded);
11181                    } catch (RemoteException e) {
11182                        Log.i(TAG, "Observer no longer exists.");
11183                    }
11184                } //end if observer
11185            } //end run
11186        });
11187    }
11188
11189    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11190        if (packageName == null) {
11191            Slog.w(TAG, "Attempt to delete null packageName.");
11192            return false;
11193        }
11194        PackageParser.Package p;
11195        synchronized (mPackages) {
11196            p = mPackages.get(packageName);
11197        }
11198        if (p == null) {
11199            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11200            return false;
11201        }
11202        final ApplicationInfo applicationInfo = p.applicationInfo;
11203        if (applicationInfo == null) {
11204            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11205            return false;
11206        }
11207        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11208        if (retCode < 0) {
11209            Slog.w(TAG, "Couldn't remove cache files for package: "
11210                       + packageName + " u" + userId);
11211            return false;
11212        }
11213        return true;
11214    }
11215
11216    @Override
11217    public void getPackageSizeInfo(final String packageName, int userHandle,
11218            final IPackageStatsObserver observer) {
11219        mContext.enforceCallingOrSelfPermission(
11220                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11221        if (packageName == null) {
11222            throw new IllegalArgumentException("Attempt to get size of null packageName");
11223        }
11224
11225        PackageStats stats = new PackageStats(packageName, userHandle);
11226
11227        /*
11228         * Queue up an async operation since the package measurement may take a
11229         * little while.
11230         */
11231        Message msg = mHandler.obtainMessage(INIT_COPY);
11232        msg.obj = new MeasureParams(stats, observer);
11233        mHandler.sendMessage(msg);
11234    }
11235
11236    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11237            PackageStats pStats) {
11238        if (packageName == null) {
11239            Slog.w(TAG, "Attempt to get size of null packageName.");
11240            return false;
11241        }
11242        PackageParser.Package p;
11243        boolean dataOnly = false;
11244        String libDirRoot = null;
11245        String asecPath = null;
11246        PackageSetting ps = null;
11247        synchronized (mPackages) {
11248            p = mPackages.get(packageName);
11249            ps = mSettings.mPackages.get(packageName);
11250            if(p == null) {
11251                dataOnly = true;
11252                if((ps == null) || (ps.pkg == null)) {
11253                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11254                    return false;
11255                }
11256                p = ps.pkg;
11257            }
11258            if (ps != null) {
11259                libDirRoot = ps.legacyNativeLibraryPathString;
11260            }
11261            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11262                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11263                if (secureContainerId != null) {
11264                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11265                }
11266            }
11267        }
11268        String publicSrcDir = null;
11269        if(!dataOnly) {
11270            final ApplicationInfo applicationInfo = p.applicationInfo;
11271            if (applicationInfo == null) {
11272                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11273                return false;
11274            }
11275            if (isForwardLocked(p)) {
11276                publicSrcDir = applicationInfo.getBaseResourcePath();
11277            }
11278        }
11279        // TODO: extend to measure size of split APKs
11280        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11281        // not just the first level.
11282        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11283        // just the primary.
11284        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11285        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11286                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11287        if (res < 0) {
11288            return false;
11289        }
11290
11291        // Fix-up for forward-locked applications in ASEC containers.
11292        if (!isExternal(p)) {
11293            pStats.codeSize += pStats.externalCodeSize;
11294            pStats.externalCodeSize = 0L;
11295        }
11296
11297        return true;
11298    }
11299
11300
11301    @Override
11302    public void addPackageToPreferred(String packageName) {
11303        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11304    }
11305
11306    @Override
11307    public void removePackageFromPreferred(String packageName) {
11308        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11309    }
11310
11311    @Override
11312    public List<PackageInfo> getPreferredPackages(int flags) {
11313        return new ArrayList<PackageInfo>();
11314    }
11315
11316    private int getUidTargetSdkVersionLockedLPr(int uid) {
11317        Object obj = mSettings.getUserIdLPr(uid);
11318        if (obj instanceof SharedUserSetting) {
11319            final SharedUserSetting sus = (SharedUserSetting) obj;
11320            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11321            final Iterator<PackageSetting> it = sus.packages.iterator();
11322            while (it.hasNext()) {
11323                final PackageSetting ps = it.next();
11324                if (ps.pkg != null) {
11325                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11326                    if (v < vers) vers = v;
11327                }
11328            }
11329            return vers;
11330        } else if (obj instanceof PackageSetting) {
11331            final PackageSetting ps = (PackageSetting) obj;
11332            if (ps.pkg != null) {
11333                return ps.pkg.applicationInfo.targetSdkVersion;
11334            }
11335        }
11336        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11337    }
11338
11339    @Override
11340    public void addPreferredActivity(IntentFilter filter, int match,
11341            ComponentName[] set, ComponentName activity, int userId) {
11342        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11343                "Adding preferred");
11344    }
11345
11346    private void addPreferredActivityInternal(IntentFilter filter, int match,
11347            ComponentName[] set, ComponentName activity, boolean always, int userId,
11348            String opname) {
11349        // writer
11350        int callingUid = Binder.getCallingUid();
11351        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11352        if (filter.countActions() == 0) {
11353            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11354            return;
11355        }
11356        synchronized (mPackages) {
11357            if (mContext.checkCallingOrSelfPermission(
11358                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11359                    != PackageManager.PERMISSION_GRANTED) {
11360                if (getUidTargetSdkVersionLockedLPr(callingUid)
11361                        < Build.VERSION_CODES.FROYO) {
11362                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11363                            + callingUid);
11364                    return;
11365                }
11366                mContext.enforceCallingOrSelfPermission(
11367                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11368            }
11369
11370            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11371            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11372                    + userId + ":");
11373            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11374            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11375            mSettings.writePackageRestrictionsLPr(userId);
11376        }
11377    }
11378
11379    @Override
11380    public void replacePreferredActivity(IntentFilter filter, int match,
11381            ComponentName[] set, ComponentName activity, int userId) {
11382        if (filter.countActions() != 1) {
11383            throw new IllegalArgumentException(
11384                    "replacePreferredActivity expects filter to have only 1 action.");
11385        }
11386        if (filter.countDataAuthorities() != 0
11387                || filter.countDataPaths() != 0
11388                || filter.countDataSchemes() > 1
11389                || filter.countDataTypes() != 0) {
11390            throw new IllegalArgumentException(
11391                    "replacePreferredActivity expects filter to have no data authorities, " +
11392                    "paths, or types; and at most one scheme.");
11393        }
11394
11395        final int callingUid = Binder.getCallingUid();
11396        enforceCrossUserPermission(callingUid, userId, true, "replace preferred activity");
11397        synchronized (mPackages) {
11398            if (mContext.checkCallingOrSelfPermission(
11399                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11400                    != PackageManager.PERMISSION_GRANTED) {
11401                if (getUidTargetSdkVersionLockedLPr(callingUid)
11402                        < Build.VERSION_CODES.FROYO) {
11403                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11404                            + Binder.getCallingUid());
11405                    return;
11406                }
11407                mContext.enforceCallingOrSelfPermission(
11408                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11409            }
11410
11411            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11412            if (pir != null) {
11413                // Get all of the existing entries that exactly match this filter.
11414                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11415                if (existing != null && existing.size() == 1) {
11416                    PreferredActivity cur = existing.get(0);
11417                    if (DEBUG_PREFERRED) {
11418                        Slog.i(TAG, "Checking replace of preferred:");
11419                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11420                        if (!cur.mPref.mAlways) {
11421                            Slog.i(TAG, "  -- CUR; not mAlways!");
11422                        } else {
11423                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11424                            Slog.i(TAG, "  -- CUR: mSet="
11425                                    + Arrays.toString(cur.mPref.mSetComponents));
11426                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11427                            Slog.i(TAG, "  -- NEW: mMatch="
11428                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11429                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11430                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11431                        }
11432                    }
11433                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11434                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11435                            && cur.mPref.sameSet(set)) {
11436                        if (DEBUG_PREFERRED) {
11437                            Slog.i(TAG, "Replacing with same preferred activity "
11438                                    + cur.mPref.mShortComponent + " for user "
11439                                    + userId + ":");
11440                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11441                        } else {
11442                            Slog.i(TAG, "Replacing with same preferred activity "
11443                                    + cur.mPref.mShortComponent + " for user "
11444                                    + userId);
11445                        }
11446                        return;
11447                    }
11448                }
11449
11450                if (existing != null) {
11451                    if (DEBUG_PREFERRED) {
11452                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11453                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11454                    }
11455                    for (int i = 0; i < existing.size(); i++) {
11456                        PreferredActivity pa = existing.get(i);
11457                        if (DEBUG_PREFERRED) {
11458                            Slog.i(TAG, "Removing existing preferred activity "
11459                                    + pa.mPref.mComponent + ":");
11460                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11461                        }
11462                        pir.removeFilter(pa);
11463                    }
11464                }
11465            }
11466            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11467                    "Replacing preferred");
11468        }
11469    }
11470
11471    @Override
11472    public void clearPackagePreferredActivities(String packageName) {
11473        final int uid = Binder.getCallingUid();
11474        // writer
11475        synchronized (mPackages) {
11476            PackageParser.Package pkg = mPackages.get(packageName);
11477            if (pkg == null || pkg.applicationInfo.uid != uid) {
11478                if (mContext.checkCallingOrSelfPermission(
11479                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11480                        != PackageManager.PERMISSION_GRANTED) {
11481                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11482                            < Build.VERSION_CODES.FROYO) {
11483                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11484                                + Binder.getCallingUid());
11485                        return;
11486                    }
11487                    mContext.enforceCallingOrSelfPermission(
11488                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11489                }
11490            }
11491
11492            int user = UserHandle.getCallingUserId();
11493            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11494                mSettings.writePackageRestrictionsLPr(user);
11495                scheduleWriteSettingsLocked();
11496            }
11497        }
11498    }
11499
11500    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11501    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11502        ArrayList<PreferredActivity> removed = null;
11503        boolean changed = false;
11504        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11505            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11506            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11507            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11508                continue;
11509            }
11510            Iterator<PreferredActivity> it = pir.filterIterator();
11511            while (it.hasNext()) {
11512                PreferredActivity pa = it.next();
11513                // Mark entry for removal only if it matches the package name
11514                // and the entry is of type "always".
11515                if (packageName == null ||
11516                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11517                                && pa.mPref.mAlways)) {
11518                    if (removed == null) {
11519                        removed = new ArrayList<PreferredActivity>();
11520                    }
11521                    removed.add(pa);
11522                }
11523            }
11524            if (removed != null) {
11525                for (int j=0; j<removed.size(); j++) {
11526                    PreferredActivity pa = removed.get(j);
11527                    pir.removeFilter(pa);
11528                }
11529                changed = true;
11530            }
11531        }
11532        return changed;
11533    }
11534
11535    @Override
11536    public void resetPreferredActivities(int userId) {
11537        mContext.enforceCallingOrSelfPermission(
11538                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11539        // writer
11540        synchronized (mPackages) {
11541            int user = UserHandle.getCallingUserId();
11542            clearPackagePreferredActivitiesLPw(null, user);
11543            mSettings.readDefaultPreferredAppsLPw(this, user);
11544            mSettings.writePackageRestrictionsLPr(user);
11545            scheduleWriteSettingsLocked();
11546        }
11547    }
11548
11549    @Override
11550    public int getPreferredActivities(List<IntentFilter> outFilters,
11551            List<ComponentName> outActivities, String packageName) {
11552
11553        int num = 0;
11554        final int userId = UserHandle.getCallingUserId();
11555        // reader
11556        synchronized (mPackages) {
11557            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11558            if (pir != null) {
11559                final Iterator<PreferredActivity> it = pir.filterIterator();
11560                while (it.hasNext()) {
11561                    final PreferredActivity pa = it.next();
11562                    if (packageName == null
11563                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11564                                    && pa.mPref.mAlways)) {
11565                        if (outFilters != null) {
11566                            outFilters.add(new IntentFilter(pa));
11567                        }
11568                        if (outActivities != null) {
11569                            outActivities.add(pa.mPref.mComponent);
11570                        }
11571                    }
11572                }
11573            }
11574        }
11575
11576        return num;
11577    }
11578
11579    @Override
11580    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11581            int userId) {
11582        int callingUid = Binder.getCallingUid();
11583        if (callingUid != Process.SYSTEM_UID) {
11584            throw new SecurityException(
11585                    "addPersistentPreferredActivity can only be run by the system");
11586        }
11587        if (filter.countActions() == 0) {
11588            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11589            return;
11590        }
11591        synchronized (mPackages) {
11592            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11593                    " :");
11594            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11595            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11596                    new PersistentPreferredActivity(filter, activity));
11597            mSettings.writePackageRestrictionsLPr(userId);
11598        }
11599    }
11600
11601    @Override
11602    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11603        int callingUid = Binder.getCallingUid();
11604        if (callingUid != Process.SYSTEM_UID) {
11605            throw new SecurityException(
11606                    "clearPackagePersistentPreferredActivities can only be run by the system");
11607        }
11608        ArrayList<PersistentPreferredActivity> removed = null;
11609        boolean changed = false;
11610        synchronized (mPackages) {
11611            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11612                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11613                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11614                        .valueAt(i);
11615                if (userId != thisUserId) {
11616                    continue;
11617                }
11618                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11619                while (it.hasNext()) {
11620                    PersistentPreferredActivity ppa = it.next();
11621                    // Mark entry for removal only if it matches the package name.
11622                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11623                        if (removed == null) {
11624                            removed = new ArrayList<PersistentPreferredActivity>();
11625                        }
11626                        removed.add(ppa);
11627                    }
11628                }
11629                if (removed != null) {
11630                    for (int j=0; j<removed.size(); j++) {
11631                        PersistentPreferredActivity ppa = removed.get(j);
11632                        ppir.removeFilter(ppa);
11633                    }
11634                    changed = true;
11635                }
11636            }
11637
11638            if (changed) {
11639                mSettings.writePackageRestrictionsLPr(userId);
11640            }
11641        }
11642    }
11643
11644    @Override
11645    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11646            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11647        mContext.enforceCallingOrSelfPermission(
11648                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11649        int callingUid = Binder.getCallingUid();
11650        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11651        if (intentFilter.countActions() == 0) {
11652            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11653            return;
11654        }
11655        synchronized (mPackages) {
11656            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11657                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11658            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11659            mSettings.writePackageRestrictionsLPr(sourceUserId);
11660        }
11661    }
11662
11663    @Override
11664    public void addCrossProfileIntentsForPackage(String packageName,
11665            int sourceUserId, int targetUserId) {
11666        mContext.enforceCallingOrSelfPermission(
11667                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11668        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11669        mSettings.writePackageRestrictionsLPr(sourceUserId);
11670    }
11671
11672    @Override
11673    public void removeCrossProfileIntentsForPackage(String packageName,
11674            int sourceUserId, int targetUserId) {
11675        mContext.enforceCallingOrSelfPermission(
11676                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11677        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11678        mSettings.writePackageRestrictionsLPr(sourceUserId);
11679    }
11680
11681    @Override
11682    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11683            int ownerUserId) {
11684        mContext.enforceCallingOrSelfPermission(
11685                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11686        int callingUid = Binder.getCallingUid();
11687        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11688        int callingUserId = UserHandle.getUserId(callingUid);
11689        synchronized (mPackages) {
11690            CrossProfileIntentResolver resolver =
11691                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11692            HashSet<CrossProfileIntentFilter> set =
11693                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11694            for (CrossProfileIntentFilter filter : set) {
11695                if (filter.getOwnerPackage().equals(ownerPackage)
11696                        && filter.getOwnerUserId() == callingUserId) {
11697                    resolver.removeFilter(filter);
11698                }
11699            }
11700            mSettings.writePackageRestrictionsLPr(sourceUserId);
11701        }
11702    }
11703
11704    // Enforcing that callingUid is owning pkg on userId
11705    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11706        // The system owns everything.
11707        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11708            return;
11709        }
11710        int callingUserId = UserHandle.getUserId(callingUid);
11711        if (callingUserId != userId) {
11712            throw new SecurityException("calling uid " + callingUid
11713                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11714                    + callingUserId);
11715        }
11716        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11717        if (pi == null) {
11718            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11719                    + callingUserId);
11720        }
11721        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11722            throw new SecurityException("Calling uid " + callingUid
11723                    + " does not own package " + pkg);
11724        }
11725    }
11726
11727    @Override
11728    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11729        Intent intent = new Intent(Intent.ACTION_MAIN);
11730        intent.addCategory(Intent.CATEGORY_HOME);
11731
11732        final int callingUserId = UserHandle.getCallingUserId();
11733        List<ResolveInfo> list = queryIntentActivities(intent, null,
11734                PackageManager.GET_META_DATA, callingUserId);
11735        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11736                true, false, false, callingUserId);
11737
11738        allHomeCandidates.clear();
11739        if (list != null) {
11740            for (ResolveInfo ri : list) {
11741                allHomeCandidates.add(ri);
11742            }
11743        }
11744        return (preferred == null || preferred.activityInfo == null)
11745                ? null
11746                : new ComponentName(preferred.activityInfo.packageName,
11747                        preferred.activityInfo.name);
11748    }
11749
11750    @Override
11751    public void setApplicationEnabledSetting(String appPackageName,
11752            int newState, int flags, int userId, String callingPackage) {
11753        if (!sUserManager.exists(userId)) return;
11754        if (callingPackage == null) {
11755            callingPackage = Integer.toString(Binder.getCallingUid());
11756        }
11757        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11758    }
11759
11760    @Override
11761    public void setComponentEnabledSetting(ComponentName componentName,
11762            int newState, int flags, int userId) {
11763        if (!sUserManager.exists(userId)) return;
11764        setEnabledSetting(componentName.getPackageName(),
11765                componentName.getClassName(), newState, flags, userId, null);
11766    }
11767
11768    private void setEnabledSetting(final String packageName, String className, int newState,
11769            final int flags, int userId, String callingPackage) {
11770        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11771              || newState == COMPONENT_ENABLED_STATE_ENABLED
11772              || newState == COMPONENT_ENABLED_STATE_DISABLED
11773              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11774              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11775            throw new IllegalArgumentException("Invalid new component state: "
11776                    + newState);
11777        }
11778        PackageSetting pkgSetting;
11779        final int uid = Binder.getCallingUid();
11780        final int permission = mContext.checkCallingOrSelfPermission(
11781                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11782        enforceCrossUserPermission(uid, userId, false, "set enabled");
11783        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11784        boolean sendNow = false;
11785        boolean isApp = (className == null);
11786        String componentName = isApp ? packageName : className;
11787        int packageUid = -1;
11788        ArrayList<String> components;
11789
11790        // writer
11791        synchronized (mPackages) {
11792            pkgSetting = mSettings.mPackages.get(packageName);
11793            if (pkgSetting == null) {
11794                if (className == null) {
11795                    throw new IllegalArgumentException(
11796                            "Unknown package: " + packageName);
11797                }
11798                throw new IllegalArgumentException(
11799                        "Unknown component: " + packageName
11800                        + "/" + className);
11801            }
11802            // Allow root and verify that userId is not being specified by a different user
11803            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11804                throw new SecurityException(
11805                        "Permission Denial: attempt to change component state from pid="
11806                        + Binder.getCallingPid()
11807                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11808            }
11809            if (className == null) {
11810                // We're dealing with an application/package level state change
11811                if (pkgSetting.getEnabled(userId) == newState) {
11812                    // Nothing to do
11813                    return;
11814                }
11815                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11816                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11817                    // Don't care about who enables an app.
11818                    callingPackage = null;
11819                }
11820                pkgSetting.setEnabled(newState, userId, callingPackage);
11821                // pkgSetting.pkg.mSetEnabled = newState;
11822            } else {
11823                // We're dealing with a component level state change
11824                // First, verify that this is a valid class name.
11825                PackageParser.Package pkg = pkgSetting.pkg;
11826                if (pkg == null || !pkg.hasComponentClassName(className)) {
11827                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11828                        throw new IllegalArgumentException("Component class " + className
11829                                + " does not exist in " + packageName);
11830                    } else {
11831                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11832                                + className + " does not exist in " + packageName);
11833                    }
11834                }
11835                switch (newState) {
11836                case COMPONENT_ENABLED_STATE_ENABLED:
11837                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11838                        return;
11839                    }
11840                    break;
11841                case COMPONENT_ENABLED_STATE_DISABLED:
11842                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11843                        return;
11844                    }
11845                    break;
11846                case COMPONENT_ENABLED_STATE_DEFAULT:
11847                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11848                        return;
11849                    }
11850                    break;
11851                default:
11852                    Slog.e(TAG, "Invalid new component state: " + newState);
11853                    return;
11854                }
11855            }
11856            mSettings.writePackageRestrictionsLPr(userId);
11857            components = mPendingBroadcasts.get(userId, packageName);
11858            final boolean newPackage = components == null;
11859            if (newPackage) {
11860                components = new ArrayList<String>();
11861            }
11862            if (!components.contains(componentName)) {
11863                components.add(componentName);
11864            }
11865            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11866                sendNow = true;
11867                // Purge entry from pending broadcast list if another one exists already
11868                // since we are sending one right away.
11869                mPendingBroadcasts.remove(userId, packageName);
11870            } else {
11871                if (newPackage) {
11872                    mPendingBroadcasts.put(userId, packageName, components);
11873                }
11874                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11875                    // Schedule a message
11876                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11877                }
11878            }
11879        }
11880
11881        long callingId = Binder.clearCallingIdentity();
11882        try {
11883            if (sendNow) {
11884                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11885                sendPackageChangedBroadcast(packageName,
11886                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11887            }
11888        } finally {
11889            Binder.restoreCallingIdentity(callingId);
11890        }
11891    }
11892
11893    private void sendPackageChangedBroadcast(String packageName,
11894            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11895        if (DEBUG_INSTALL)
11896            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11897                    + componentNames);
11898        Bundle extras = new Bundle(4);
11899        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11900        String nameList[] = new String[componentNames.size()];
11901        componentNames.toArray(nameList);
11902        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11903        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11904        extras.putInt(Intent.EXTRA_UID, packageUid);
11905        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11906                new int[] {UserHandle.getUserId(packageUid)});
11907    }
11908
11909    @Override
11910    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11911        if (!sUserManager.exists(userId)) return;
11912        final int uid = Binder.getCallingUid();
11913        final int permission = mContext.checkCallingOrSelfPermission(
11914                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11915        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11916        enforceCrossUserPermission(uid, userId, true, "stop package");
11917        // writer
11918        synchronized (mPackages) {
11919            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11920                    uid, userId)) {
11921                scheduleWritePackageRestrictionsLocked(userId);
11922            }
11923        }
11924    }
11925
11926    @Override
11927    public String getInstallerPackageName(String packageName) {
11928        // reader
11929        synchronized (mPackages) {
11930            return mSettings.getInstallerPackageNameLPr(packageName);
11931        }
11932    }
11933
11934    @Override
11935    public int getApplicationEnabledSetting(String packageName, int userId) {
11936        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11937        int uid = Binder.getCallingUid();
11938        enforceCrossUserPermission(uid, userId, false, "get enabled");
11939        // reader
11940        synchronized (mPackages) {
11941            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11942        }
11943    }
11944
11945    @Override
11946    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11947        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11948        int uid = Binder.getCallingUid();
11949        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11950        // reader
11951        synchronized (mPackages) {
11952            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11953        }
11954    }
11955
11956    @Override
11957    public void enterSafeMode() {
11958        enforceSystemOrRoot("Only the system can request entering safe mode");
11959
11960        if (!mSystemReady) {
11961            mSafeMode = true;
11962        }
11963    }
11964
11965    @Override
11966    public void systemReady() {
11967        mSystemReady = true;
11968
11969        // Read the compatibilty setting when the system is ready.
11970        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11971                mContext.getContentResolver(),
11972                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11973        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11974        if (DEBUG_SETTINGS) {
11975            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11976        }
11977
11978        synchronized (mPackages) {
11979            // Verify that all of the preferred activity components actually
11980            // exist.  It is possible for applications to be updated and at
11981            // that point remove a previously declared activity component that
11982            // had been set as a preferred activity.  We try to clean this up
11983            // the next time we encounter that preferred activity, but it is
11984            // possible for the user flow to never be able to return to that
11985            // situation so here we do a sanity check to make sure we haven't
11986            // left any junk around.
11987            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11988            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11989                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11990                removed.clear();
11991                for (PreferredActivity pa : pir.filterSet()) {
11992                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11993                        removed.add(pa);
11994                    }
11995                }
11996                if (removed.size() > 0) {
11997                    for (int r=0; r<removed.size(); r++) {
11998                        PreferredActivity pa = removed.get(r);
11999                        Slog.w(TAG, "Removing dangling preferred activity: "
12000                                + pa.mPref.mComponent);
12001                        pir.removeFilter(pa);
12002                    }
12003                    mSettings.writePackageRestrictionsLPr(
12004                            mSettings.mPreferredActivities.keyAt(i));
12005                }
12006            }
12007        }
12008        sUserManager.systemReady();
12009
12010        // Kick off any messages waiting for system ready
12011        if (mPostSystemReadyMessages != null) {
12012            for (Message msg : mPostSystemReadyMessages) {
12013                msg.sendToTarget();
12014            }
12015            mPostSystemReadyMessages = null;
12016        }
12017    }
12018
12019    @Override
12020    public boolean isSafeMode() {
12021        return mSafeMode;
12022    }
12023
12024    @Override
12025    public boolean hasSystemUidErrors() {
12026        return mHasSystemUidErrors;
12027    }
12028
12029    static String arrayToString(int[] array) {
12030        StringBuffer buf = new StringBuffer(128);
12031        buf.append('[');
12032        if (array != null) {
12033            for (int i=0; i<array.length; i++) {
12034                if (i > 0) buf.append(", ");
12035                buf.append(array[i]);
12036            }
12037        }
12038        buf.append(']');
12039        return buf.toString();
12040    }
12041
12042    static class DumpState {
12043        public static final int DUMP_LIBS = 1 << 0;
12044        public static final int DUMP_FEATURES = 1 << 1;
12045        public static final int DUMP_RESOLVERS = 1 << 2;
12046        public static final int DUMP_PERMISSIONS = 1 << 3;
12047        public static final int DUMP_PACKAGES = 1 << 4;
12048        public static final int DUMP_SHARED_USERS = 1 << 5;
12049        public static final int DUMP_MESSAGES = 1 << 6;
12050        public static final int DUMP_PROVIDERS = 1 << 7;
12051        public static final int DUMP_VERIFIERS = 1 << 8;
12052        public static final int DUMP_PREFERRED = 1 << 9;
12053        public static final int DUMP_PREFERRED_XML = 1 << 10;
12054        public static final int DUMP_KEYSETS = 1 << 11;
12055        public static final int DUMP_VERSION = 1 << 12;
12056        public static final int DUMP_INSTALLS = 1 << 13;
12057
12058        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12059
12060        private int mTypes;
12061
12062        private int mOptions;
12063
12064        private boolean mTitlePrinted;
12065
12066        private SharedUserSetting mSharedUser;
12067
12068        public boolean isDumping(int type) {
12069            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12070                return true;
12071            }
12072
12073            return (mTypes & type) != 0;
12074        }
12075
12076        public void setDump(int type) {
12077            mTypes |= type;
12078        }
12079
12080        public boolean isOptionEnabled(int option) {
12081            return (mOptions & option) != 0;
12082        }
12083
12084        public void setOptionEnabled(int option) {
12085            mOptions |= option;
12086        }
12087
12088        public boolean onTitlePrinted() {
12089            final boolean printed = mTitlePrinted;
12090            mTitlePrinted = true;
12091            return printed;
12092        }
12093
12094        public boolean getTitlePrinted() {
12095            return mTitlePrinted;
12096        }
12097
12098        public void setTitlePrinted(boolean enabled) {
12099            mTitlePrinted = enabled;
12100        }
12101
12102        public SharedUserSetting getSharedUser() {
12103            return mSharedUser;
12104        }
12105
12106        public void setSharedUser(SharedUserSetting user) {
12107            mSharedUser = user;
12108        }
12109    }
12110
12111    @Override
12112    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12113        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12114                != PackageManager.PERMISSION_GRANTED) {
12115            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12116                    + Binder.getCallingPid()
12117                    + ", uid=" + Binder.getCallingUid()
12118                    + " without permission "
12119                    + android.Manifest.permission.DUMP);
12120            return;
12121        }
12122
12123        DumpState dumpState = new DumpState();
12124        boolean fullPreferred = false;
12125        boolean checkin = false;
12126
12127        String packageName = null;
12128
12129        int opti = 0;
12130        while (opti < args.length) {
12131            String opt = args[opti];
12132            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12133                break;
12134            }
12135            opti++;
12136            if ("-a".equals(opt)) {
12137                // Right now we only know how to print all.
12138            } else if ("-h".equals(opt)) {
12139                pw.println("Package manager dump options:");
12140                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12141                pw.println("    --checkin: dump for a checkin");
12142                pw.println("    -f: print details of intent filters");
12143                pw.println("    -h: print this help");
12144                pw.println("  cmd may be one of:");
12145                pw.println("    l[ibraries]: list known shared libraries");
12146                pw.println("    f[ibraries]: list device features");
12147                pw.println("    k[eysets]: print known keysets");
12148                pw.println("    r[esolvers]: dump intent resolvers");
12149                pw.println("    perm[issions]: dump permissions");
12150                pw.println("    pref[erred]: print preferred package settings");
12151                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12152                pw.println("    prov[iders]: dump content providers");
12153                pw.println("    p[ackages]: dump installed packages");
12154                pw.println("    s[hared-users]: dump shared user IDs");
12155                pw.println("    m[essages]: print collected runtime messages");
12156                pw.println("    v[erifiers]: print package verifier info");
12157                pw.println("    version: print database version info");
12158                pw.println("    write: write current settings now");
12159                pw.println("    <package.name>: info about given package");
12160                pw.println("    installs: details about install sessions");
12161                return;
12162            } else if ("--checkin".equals(opt)) {
12163                checkin = true;
12164            } else if ("-f".equals(opt)) {
12165                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12166            } else {
12167                pw.println("Unknown argument: " + opt + "; use -h for help");
12168            }
12169        }
12170
12171        // Is the caller requesting to dump a particular piece of data?
12172        if (opti < args.length) {
12173            String cmd = args[opti];
12174            opti++;
12175            // Is this a package name?
12176            if ("android".equals(cmd) || cmd.contains(".")) {
12177                packageName = cmd;
12178                // When dumping a single package, we always dump all of its
12179                // filter information since the amount of data will be reasonable.
12180                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12181            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12182                dumpState.setDump(DumpState.DUMP_LIBS);
12183            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_FEATURES);
12185            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12186                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12187            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12188                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12189            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12190                dumpState.setDump(DumpState.DUMP_PREFERRED);
12191            } else if ("preferred-xml".equals(cmd)) {
12192                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12193                if (opti < args.length && "--full".equals(args[opti])) {
12194                    fullPreferred = true;
12195                    opti++;
12196                }
12197            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12198                dumpState.setDump(DumpState.DUMP_PACKAGES);
12199            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12200                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12201            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12202                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12203            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12204                dumpState.setDump(DumpState.DUMP_MESSAGES);
12205            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12206                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12207            } else if ("version".equals(cmd)) {
12208                dumpState.setDump(DumpState.DUMP_VERSION);
12209            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12210                dumpState.setDump(DumpState.DUMP_KEYSETS);
12211            } else if ("write".equals(cmd)) {
12212                synchronized (mPackages) {
12213                    mSettings.writeLPr();
12214                    pw.println("Settings written.");
12215                    return;
12216                }
12217            } else if ("installs".equals(cmd)) {
12218                dumpState.setDump(DumpState.DUMP_INSTALLS);
12219            }
12220        }
12221
12222        if (checkin) {
12223            pw.println("vers,1");
12224        }
12225
12226        // reader
12227        synchronized (mPackages) {
12228            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12229                if (!checkin) {
12230                    if (dumpState.onTitlePrinted())
12231                        pw.println();
12232                    pw.println("Database versions:");
12233                    pw.print("  SDK Version:");
12234                    pw.print(" internal=");
12235                    pw.print(mSettings.mInternalSdkPlatform);
12236                    pw.print(" external=");
12237                    pw.println(mSettings.mExternalSdkPlatform);
12238                    pw.print("  DB Version:");
12239                    pw.print(" internal=");
12240                    pw.print(mSettings.mInternalDatabaseVersion);
12241                    pw.print(" external=");
12242                    pw.println(mSettings.mExternalDatabaseVersion);
12243                }
12244            }
12245
12246            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12247                if (!checkin) {
12248                    if (dumpState.onTitlePrinted())
12249                        pw.println();
12250                    pw.println("Verifiers:");
12251                    pw.print("  Required: ");
12252                    pw.print(mRequiredVerifierPackage);
12253                    pw.print(" (uid=");
12254                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12255                    pw.println(")");
12256                } else if (mRequiredVerifierPackage != null) {
12257                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12258                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12259                }
12260            }
12261
12262            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12263                boolean printedHeader = false;
12264                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12265                while (it.hasNext()) {
12266                    String name = it.next();
12267                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12268                    if (!checkin) {
12269                        if (!printedHeader) {
12270                            if (dumpState.onTitlePrinted())
12271                                pw.println();
12272                            pw.println("Libraries:");
12273                            printedHeader = true;
12274                        }
12275                        pw.print("  ");
12276                    } else {
12277                        pw.print("lib,");
12278                    }
12279                    pw.print(name);
12280                    if (!checkin) {
12281                        pw.print(" -> ");
12282                    }
12283                    if (ent.path != null) {
12284                        if (!checkin) {
12285                            pw.print("(jar) ");
12286                            pw.print(ent.path);
12287                        } else {
12288                            pw.print(",jar,");
12289                            pw.print(ent.path);
12290                        }
12291                    } else {
12292                        if (!checkin) {
12293                            pw.print("(apk) ");
12294                            pw.print(ent.apk);
12295                        } else {
12296                            pw.print(",apk,");
12297                            pw.print(ent.apk);
12298                        }
12299                    }
12300                    pw.println();
12301                }
12302            }
12303
12304            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12305                if (dumpState.onTitlePrinted())
12306                    pw.println();
12307                if (!checkin) {
12308                    pw.println("Features:");
12309                }
12310                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12311                while (it.hasNext()) {
12312                    String name = it.next();
12313                    if (!checkin) {
12314                        pw.print("  ");
12315                    } else {
12316                        pw.print("feat,");
12317                    }
12318                    pw.println(name);
12319                }
12320            }
12321
12322            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12323                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12324                        : "Activity Resolver Table:", "  ", packageName,
12325                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12326                    dumpState.setTitlePrinted(true);
12327                }
12328                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12329                        : "Receiver Resolver Table:", "  ", packageName,
12330                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12331                    dumpState.setTitlePrinted(true);
12332                }
12333                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12334                        : "Service Resolver Table:", "  ", packageName,
12335                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12336                    dumpState.setTitlePrinted(true);
12337                }
12338                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12339                        : "Provider Resolver Table:", "  ", packageName,
12340                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12341                    dumpState.setTitlePrinted(true);
12342                }
12343            }
12344
12345            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12346                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12347                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12348                    int user = mSettings.mPreferredActivities.keyAt(i);
12349                    if (pir.dump(pw,
12350                            dumpState.getTitlePrinted()
12351                                ? "\nPreferred Activities User " + user + ":"
12352                                : "Preferred Activities User " + user + ":", "  ",
12353                            packageName, true)) {
12354                        dumpState.setTitlePrinted(true);
12355                    }
12356                }
12357            }
12358
12359            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12360                pw.flush();
12361                FileOutputStream fout = new FileOutputStream(fd);
12362                BufferedOutputStream str = new BufferedOutputStream(fout);
12363                XmlSerializer serializer = new FastXmlSerializer();
12364                try {
12365                    serializer.setOutput(str, "utf-8");
12366                    serializer.startDocument(null, true);
12367                    serializer.setFeature(
12368                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12369                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12370                    serializer.endDocument();
12371                    serializer.flush();
12372                } catch (IllegalArgumentException e) {
12373                    pw.println("Failed writing: " + e);
12374                } catch (IllegalStateException e) {
12375                    pw.println("Failed writing: " + e);
12376                } catch (IOException e) {
12377                    pw.println("Failed writing: " + e);
12378                }
12379            }
12380
12381            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12382                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12383                if (packageName == null) {
12384                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12385                        if (iperm == 0) {
12386                            if (dumpState.onTitlePrinted())
12387                                pw.println();
12388                            pw.println("AppOp Permissions:");
12389                        }
12390                        pw.print("  AppOp Permission ");
12391                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12392                        pw.println(":");
12393                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12394                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12395                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12396                        }
12397                    }
12398                }
12399            }
12400
12401            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12402                boolean printedSomething = false;
12403                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12404                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12405                        continue;
12406                    }
12407                    if (!printedSomething) {
12408                        if (dumpState.onTitlePrinted())
12409                            pw.println();
12410                        pw.println("Registered ContentProviders:");
12411                        printedSomething = true;
12412                    }
12413                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12414                    pw.print("    "); pw.println(p.toString());
12415                }
12416                printedSomething = false;
12417                for (Map.Entry<String, PackageParser.Provider> entry :
12418                        mProvidersByAuthority.entrySet()) {
12419                    PackageParser.Provider p = entry.getValue();
12420                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12421                        continue;
12422                    }
12423                    if (!printedSomething) {
12424                        if (dumpState.onTitlePrinted())
12425                            pw.println();
12426                        pw.println("ContentProvider Authorities:");
12427                        printedSomething = true;
12428                    }
12429                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12430                    pw.print("    "); pw.println(p.toString());
12431                    if (p.info != null && p.info.applicationInfo != null) {
12432                        final String appInfo = p.info.applicationInfo.toString();
12433                        pw.print("      applicationInfo="); pw.println(appInfo);
12434                    }
12435                }
12436            }
12437
12438            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12439                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12440            }
12441
12442            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12443                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12444            }
12445
12446            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12447                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12448            }
12449
12450            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS)) {
12451                if (dumpState.onTitlePrinted()) pw.println();
12452                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12453            }
12454
12455            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12456                if (dumpState.onTitlePrinted()) pw.println();
12457                mSettings.dumpReadMessagesLPr(pw, dumpState);
12458
12459                pw.println();
12460                pw.println("Package warning messages:");
12461                final File fname = getSettingsProblemFile();
12462                FileInputStream in = null;
12463                try {
12464                    in = new FileInputStream(fname);
12465                    final int avail = in.available();
12466                    final byte[] data = new byte[avail];
12467                    in.read(data);
12468                    pw.print(new String(data));
12469                } catch (FileNotFoundException e) {
12470                } catch (IOException e) {
12471                } finally {
12472                    if (in != null) {
12473                        try {
12474                            in.close();
12475                        } catch (IOException e) {
12476                        }
12477                    }
12478                }
12479            }
12480        }
12481    }
12482
12483    // ------- apps on sdcard specific code -------
12484    static final boolean DEBUG_SD_INSTALL = false;
12485
12486    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12487
12488    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12489
12490    private boolean mMediaMounted = false;
12491
12492    static String getEncryptKey() {
12493        try {
12494            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12495                    SD_ENCRYPTION_KEYSTORE_NAME);
12496            if (sdEncKey == null) {
12497                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12498                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12499                if (sdEncKey == null) {
12500                    Slog.e(TAG, "Failed to create encryption keys");
12501                    return null;
12502                }
12503            }
12504            return sdEncKey;
12505        } catch (NoSuchAlgorithmException nsae) {
12506            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12507            return null;
12508        } catch (IOException ioe) {
12509            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12510            return null;
12511        }
12512    }
12513
12514    /*
12515     * Update media status on PackageManager.
12516     */
12517    @Override
12518    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12519        int callingUid = Binder.getCallingUid();
12520        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12521            throw new SecurityException("Media status can only be updated by the system");
12522        }
12523        // reader; this apparently protects mMediaMounted, but should probably
12524        // be a different lock in that case.
12525        synchronized (mPackages) {
12526            Log.i(TAG, "Updating external media status from "
12527                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12528                    + (mediaStatus ? "mounted" : "unmounted"));
12529            if (DEBUG_SD_INSTALL)
12530                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12531                        + ", mMediaMounted=" + mMediaMounted);
12532            if (mediaStatus == mMediaMounted) {
12533                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12534                        : 0, -1);
12535                mHandler.sendMessage(msg);
12536                return;
12537            }
12538            mMediaMounted = mediaStatus;
12539        }
12540        // Queue up an async operation since the package installation may take a
12541        // little while.
12542        mHandler.post(new Runnable() {
12543            public void run() {
12544                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12545            }
12546        });
12547    }
12548
12549    /**
12550     * Called by MountService when the initial ASECs to scan are available.
12551     * Should block until all the ASEC containers are finished being scanned.
12552     */
12553    public void scanAvailableAsecs() {
12554        updateExternalMediaStatusInner(true, false, false);
12555        if (mShouldRestoreconData) {
12556            SELinuxMMAC.setRestoreconDone();
12557            mShouldRestoreconData = false;
12558        }
12559    }
12560
12561    /*
12562     * Collect information of applications on external media, map them against
12563     * existing containers and update information based on current mount status.
12564     * Please note that we always have to report status if reportStatus has been
12565     * set to true especially when unloading packages.
12566     */
12567    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12568            boolean externalStorage) {
12569        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12570        int[] uidArr = EmptyArray.INT;
12571
12572        final String[] list = PackageHelper.getSecureContainerList();
12573        if (ArrayUtils.isEmpty(list)) {
12574            Log.i(TAG, "No secure containers found");
12575        } else {
12576            // Process list of secure containers and categorize them
12577            // as active or stale based on their package internal state.
12578
12579            // reader
12580            synchronized (mPackages) {
12581                for (String cid : list) {
12582                    // Leave stages untouched for now; installer service owns them
12583                    if (PackageInstallerService.isStageName(cid)) continue;
12584
12585                    if (DEBUG_SD_INSTALL)
12586                        Log.i(TAG, "Processing container " + cid);
12587                    String pkgName = getAsecPackageName(cid);
12588                    if (pkgName == null) {
12589                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12590                        continue;
12591                    }
12592                    if (DEBUG_SD_INSTALL)
12593                        Log.i(TAG, "Looking for pkg : " + pkgName);
12594
12595                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12596                    if (ps == null) {
12597                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12598                        continue;
12599                    }
12600
12601                    /*
12602                     * Skip packages that are not external if we're unmounting
12603                     * external storage.
12604                     */
12605                    if (externalStorage && !isMounted && !isExternal(ps)) {
12606                        continue;
12607                    }
12608
12609                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12610                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12611                    // The package status is changed only if the code path
12612                    // matches between settings and the container id.
12613                    if (ps.codePathString != null
12614                            && ps.codePathString.startsWith(args.getCodePath())) {
12615                        if (DEBUG_SD_INSTALL) {
12616                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12617                                    + " at code path: " + ps.codePathString);
12618                        }
12619
12620                        // We do have a valid package installed on sdcard
12621                        processCids.put(args, ps.codePathString);
12622                        final int uid = ps.appId;
12623                        if (uid != -1) {
12624                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12625                        }
12626                    } else {
12627                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12628                                + ps.codePathString);
12629                    }
12630                }
12631            }
12632
12633            Arrays.sort(uidArr);
12634        }
12635
12636        // Process packages with valid entries.
12637        if (isMounted) {
12638            if (DEBUG_SD_INSTALL)
12639                Log.i(TAG, "Loading packages");
12640            loadMediaPackages(processCids, uidArr);
12641            startCleaningPackages();
12642            mInstallerService.onSecureContainersAvailable();
12643        } else {
12644            if (DEBUG_SD_INSTALL)
12645                Log.i(TAG, "Unloading packages");
12646            unloadMediaPackages(processCids, uidArr, reportStatus);
12647        }
12648    }
12649
12650    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12651            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12652        int size = pkgList.size();
12653        if (size > 0) {
12654            // Send broadcasts here
12655            Bundle extras = new Bundle();
12656            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12657                    .toArray(new String[size]));
12658            if (uidArr != null) {
12659                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12660            }
12661            if (replacing) {
12662                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12663            }
12664            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12665                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12666            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12667        }
12668    }
12669
12670   /*
12671     * Look at potentially valid container ids from processCids If package
12672     * information doesn't match the one on record or package scanning fails,
12673     * the cid is added to list of removeCids. We currently don't delete stale
12674     * containers.
12675     */
12676    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12677        ArrayList<String> pkgList = new ArrayList<String>();
12678        Set<AsecInstallArgs> keys = processCids.keySet();
12679
12680        for (AsecInstallArgs args : keys) {
12681            String codePath = processCids.get(args);
12682            if (DEBUG_SD_INSTALL)
12683                Log.i(TAG, "Loading container : " + args.cid);
12684            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12685            try {
12686                // Make sure there are no container errors first.
12687                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12688                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12689                            + " when installing from sdcard");
12690                    continue;
12691                }
12692                // Check code path here.
12693                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12694                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12695                            + " does not match one in settings " + codePath);
12696                    continue;
12697                }
12698                // Parse package
12699                int parseFlags = mDefParseFlags;
12700                if (args.isExternal()) {
12701                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12702                }
12703                if (args.isFwdLocked()) {
12704                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12705                }
12706
12707                synchronized (mInstallLock) {
12708                    PackageParser.Package pkg = null;
12709                    try {
12710                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12711                    } catch (PackageManagerException e) {
12712                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12713                    }
12714                    // Scan the package
12715                    if (pkg != null) {
12716                        /*
12717                         * TODO why is the lock being held? doPostInstall is
12718                         * called in other places without the lock. This needs
12719                         * to be straightened out.
12720                         */
12721                        // writer
12722                        synchronized (mPackages) {
12723                            retCode = PackageManager.INSTALL_SUCCEEDED;
12724                            pkgList.add(pkg.packageName);
12725                            // Post process args
12726                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12727                                    pkg.applicationInfo.uid);
12728                        }
12729                    } else {
12730                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12731                    }
12732                }
12733
12734            } finally {
12735                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12736                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12737                }
12738            }
12739        }
12740        // writer
12741        synchronized (mPackages) {
12742            // If the platform SDK has changed since the last time we booted,
12743            // we need to re-grant app permission to catch any new ones that
12744            // appear. This is really a hack, and means that apps can in some
12745            // cases get permissions that the user didn't initially explicitly
12746            // allow... it would be nice to have some better way to handle
12747            // this situation.
12748            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12749            if (regrantPermissions)
12750                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12751                        + mSdkVersion + "; regranting permissions for external storage");
12752            mSettings.mExternalSdkPlatform = mSdkVersion;
12753
12754            // Make sure group IDs have been assigned, and any permission
12755            // changes in other apps are accounted for
12756            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12757                    | (regrantPermissions
12758                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12759                            : 0));
12760
12761            mSettings.updateExternalDatabaseVersion();
12762
12763            // can downgrade to reader
12764            // Persist settings
12765            mSettings.writeLPr();
12766        }
12767        // Send a broadcast to let everyone know we are done processing
12768        if (pkgList.size() > 0) {
12769            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12770        }
12771    }
12772
12773   /*
12774     * Utility method to unload a list of specified containers
12775     */
12776    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12777        // Just unmount all valid containers.
12778        for (AsecInstallArgs arg : cidArgs) {
12779            synchronized (mInstallLock) {
12780                arg.doPostDeleteLI(false);
12781           }
12782       }
12783   }
12784
12785    /*
12786     * Unload packages mounted on external media. This involves deleting package
12787     * data from internal structures, sending broadcasts about diabled packages,
12788     * gc'ing to free up references, unmounting all secure containers
12789     * corresponding to packages on external media, and posting a
12790     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12791     * that we always have to post this message if status has been requested no
12792     * matter what.
12793     */
12794    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12795            final boolean reportStatus) {
12796        if (DEBUG_SD_INSTALL)
12797            Log.i(TAG, "unloading media packages");
12798        ArrayList<String> pkgList = new ArrayList<String>();
12799        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12800        final Set<AsecInstallArgs> keys = processCids.keySet();
12801        for (AsecInstallArgs args : keys) {
12802            String pkgName = args.getPackageName();
12803            if (DEBUG_SD_INSTALL)
12804                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12805            // Delete package internally
12806            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12807            synchronized (mInstallLock) {
12808                boolean res = deletePackageLI(pkgName, null, false, null, null,
12809                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12810                if (res) {
12811                    pkgList.add(pkgName);
12812                } else {
12813                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12814                    failedList.add(args);
12815                }
12816            }
12817        }
12818
12819        // reader
12820        synchronized (mPackages) {
12821            // We didn't update the settings after removing each package;
12822            // write them now for all packages.
12823            mSettings.writeLPr();
12824        }
12825
12826        // We have to absolutely send UPDATED_MEDIA_STATUS only
12827        // after confirming that all the receivers processed the ordered
12828        // broadcast when packages get disabled, force a gc to clean things up.
12829        // and unload all the containers.
12830        if (pkgList.size() > 0) {
12831            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12832                    new IIntentReceiver.Stub() {
12833                public void performReceive(Intent intent, int resultCode, String data,
12834                        Bundle extras, boolean ordered, boolean sticky,
12835                        int sendingUser) throws RemoteException {
12836                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12837                            reportStatus ? 1 : 0, 1, keys);
12838                    mHandler.sendMessage(msg);
12839                }
12840            });
12841        } else {
12842            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12843                    keys);
12844            mHandler.sendMessage(msg);
12845        }
12846    }
12847
12848    /** Binder call */
12849    @Override
12850    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12851            final int flags) {
12852        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12853        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12854        int returnCode = PackageManager.MOVE_SUCCEEDED;
12855        int currInstallFlags = 0;
12856        int newInstallFlags = 0;
12857
12858        File codeFile = null;
12859        String installerPackageName = null;
12860        String packageAbiOverride = null;
12861
12862        // reader
12863        synchronized (mPackages) {
12864            final PackageParser.Package pkg = mPackages.get(packageName);
12865            final PackageSetting ps = mSettings.mPackages.get(packageName);
12866            if (pkg == null || ps == null) {
12867                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12868            } else {
12869                // Disable moving fwd locked apps and system packages
12870                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12871                    Slog.w(TAG, "Cannot move system application");
12872                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12873                } else if (pkg.mOperationPending) {
12874                    Slog.w(TAG, "Attempt to move package which has pending operations");
12875                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12876                } else {
12877                    // Find install location first
12878                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12879                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12880                        Slog.w(TAG, "Ambigous flags specified for move location.");
12881                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12882                    } else {
12883                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12884                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12885                        currInstallFlags = isExternal(pkg)
12886                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12887
12888                        if (newInstallFlags == currInstallFlags) {
12889                            Slog.w(TAG, "No move required. Trying to move to same location");
12890                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12891                        } else {
12892                            if (isForwardLocked(pkg)) {
12893                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12894                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12895                            }
12896                        }
12897                    }
12898                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12899                        pkg.mOperationPending = true;
12900                    }
12901                }
12902
12903                codeFile = new File(pkg.codePath);
12904                installerPackageName = ps.installerPackageName;
12905                packageAbiOverride = ps.cpuAbiOverrideString;
12906            }
12907        }
12908
12909        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12910            try {
12911                observer.packageMoved(packageName, returnCode);
12912            } catch (RemoteException ignored) {
12913            }
12914            return;
12915        }
12916
12917        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12918            @Override
12919            public void onUserActionRequired(Intent intent) throws RemoteException {
12920                throw new IllegalStateException();
12921            }
12922
12923            @Override
12924            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12925                    Bundle extras) throws RemoteException {
12926                Slog.d(TAG, "Install result for move: "
12927                        + PackageManager.installStatusToString(returnCode, msg));
12928
12929                // We usually have a new package now after the install, but if
12930                // we failed we need to clear the pending flag on the original
12931                // package object.
12932                synchronized (mPackages) {
12933                    final PackageParser.Package pkg = mPackages.get(packageName);
12934                    if (pkg != null) {
12935                        pkg.mOperationPending = false;
12936                    }
12937                }
12938
12939                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12940                switch (status) {
12941                    case PackageInstaller.STATUS_SUCCESS:
12942                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12943                        break;
12944                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12945                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12946                        break;
12947                    default:
12948                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12949                        break;
12950                }
12951            }
12952        };
12953
12954        // Treat a move like reinstalling an existing app, which ensures that we
12955        // process everythign uniformly, like unpacking native libraries.
12956        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12957
12958        final Message msg = mHandler.obtainMessage(INIT_COPY);
12959        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12960        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12961                installerPackageName, null, user, packageAbiOverride);
12962        mHandler.sendMessage(msg);
12963    }
12964
12965    @Override
12966    public boolean setInstallLocation(int loc) {
12967        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12968                null);
12969        if (getInstallLocation() == loc) {
12970            return true;
12971        }
12972        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12973                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12974            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12975                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12976            return true;
12977        }
12978        return false;
12979   }
12980
12981    @Override
12982    public int getInstallLocation() {
12983        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12984                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12985                PackageHelper.APP_INSTALL_AUTO);
12986    }
12987
12988    /** Called by UserManagerService */
12989    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12990        mDirtyUsers.remove(userHandle);
12991        mSettings.removeUserLPw(userHandle);
12992        mPendingBroadcasts.remove(userHandle);
12993        if (mInstaller != null) {
12994            // Technically, we shouldn't be doing this with the package lock
12995            // held.  However, this is very rare, and there is already so much
12996            // other disk I/O going on, that we'll let it slide for now.
12997            mInstaller.removeUserDataDirs(userHandle);
12998        }
12999        mUserNeedsBadging.delete(userHandle);
13000        removeUnusedPackagesLILPw(userManager, userHandle);
13001    }
13002
13003    /**
13004     * We're removing userHandle and would like to remove any downloaded packages
13005     * that are no longer in use by any other user.
13006     * @param userHandle the user being removed
13007     */
13008    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13009        final boolean DEBUG_CLEAN_APKS = false;
13010        int [] users = userManager.getUserIdsLPr();
13011        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13012        while (psit.hasNext()) {
13013            PackageSetting ps = psit.next();
13014            if (ps.pkg == null) {
13015                continue;
13016            }
13017            final String packageName = ps.pkg.packageName;
13018            // Skip over if system app
13019            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13020                continue;
13021            }
13022            if (DEBUG_CLEAN_APKS) {
13023                Slog.i(TAG, "Checking package " + packageName);
13024            }
13025            boolean keep = false;
13026            for (int i = 0; i < users.length; i++) {
13027                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13028                    keep = true;
13029                    if (DEBUG_CLEAN_APKS) {
13030                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13031                                + users[i]);
13032                    }
13033                    break;
13034                }
13035            }
13036            if (!keep) {
13037                if (DEBUG_CLEAN_APKS) {
13038                    Slog.i(TAG, "  Removing package " + packageName);
13039                }
13040                mHandler.post(new Runnable() {
13041                    public void run() {
13042                        deletePackageX(packageName, userHandle, 0);
13043                    } //end run
13044                });
13045            }
13046        }
13047    }
13048
13049    /** Called by UserManagerService */
13050    void createNewUserLILPw(int userHandle, File path) {
13051        if (mInstaller != null) {
13052            mInstaller.createUserConfig(userHandle);
13053            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13054        }
13055    }
13056
13057    @Override
13058    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13059        mContext.enforceCallingOrSelfPermission(
13060                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13061                "Only package verification agents can read the verifier device identity");
13062
13063        synchronized (mPackages) {
13064            return mSettings.getVerifierDeviceIdentityLPw();
13065        }
13066    }
13067
13068    @Override
13069    public void setPermissionEnforced(String permission, boolean enforced) {
13070        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13071        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13072            synchronized (mPackages) {
13073                if (mSettings.mReadExternalStorageEnforced == null
13074                        || mSettings.mReadExternalStorageEnforced != enforced) {
13075                    mSettings.mReadExternalStorageEnforced = enforced;
13076                    mSettings.writeLPr();
13077                }
13078            }
13079            // kill any non-foreground processes so we restart them and
13080            // grant/revoke the GID.
13081            final IActivityManager am = ActivityManagerNative.getDefault();
13082            if (am != null) {
13083                final long token = Binder.clearCallingIdentity();
13084                try {
13085                    am.killProcessesBelowForeground("setPermissionEnforcement");
13086                } catch (RemoteException e) {
13087                } finally {
13088                    Binder.restoreCallingIdentity(token);
13089                }
13090            }
13091        } else {
13092            throw new IllegalArgumentException("No selective enforcement for " + permission);
13093        }
13094    }
13095
13096    @Override
13097    @Deprecated
13098    public boolean isPermissionEnforced(String permission) {
13099        return true;
13100    }
13101
13102    @Override
13103    public boolean isStorageLow() {
13104        final long token = Binder.clearCallingIdentity();
13105        try {
13106            final DeviceStorageMonitorInternal
13107                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13108            if (dsm != null) {
13109                return dsm.isMemoryLow();
13110            } else {
13111                return false;
13112            }
13113        } finally {
13114            Binder.restoreCallingIdentity(token);
13115        }
13116    }
13117
13118    @Override
13119    public IPackageInstaller getPackageInstaller() {
13120        return mInstallerService;
13121    }
13122
13123    private boolean userNeedsBadging(int userId) {
13124        int index = mUserNeedsBadging.indexOfKey(userId);
13125        if (index < 0) {
13126            final UserInfo userInfo;
13127            final long token = Binder.clearCallingIdentity();
13128            try {
13129                userInfo = sUserManager.getUserInfo(userId);
13130            } finally {
13131                Binder.restoreCallingIdentity(token);
13132            }
13133            final boolean b;
13134            if (userInfo != null && userInfo.isManagedProfile()) {
13135                b = true;
13136            } else {
13137                b = false;
13138            }
13139            mUserNeedsBadging.put(userId, b);
13140            return b;
13141        }
13142        return mUserNeedsBadging.valueAt(index);
13143    }
13144
13145    @Override
13146    public KeySet getKeySetByAlias(String packageName, String alias) {
13147        if (packageName == null || alias == null) {
13148            return null;
13149        }
13150        synchronized(mPackages) {
13151            final PackageParser.Package pkg = mPackages.get(packageName);
13152            if (pkg == null) {
13153                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13154                throw new IllegalArgumentException("Unknown package: " + packageName);
13155            }
13156            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13157            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13158        }
13159    }
13160
13161    @Override
13162    public KeySet getSigningKeySet(String packageName) {
13163        if (packageName == null) {
13164            return null;
13165        }
13166        synchronized(mPackages) {
13167            final PackageParser.Package pkg = mPackages.get(packageName);
13168            if (pkg == null) {
13169                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13170                throw new IllegalArgumentException("Unknown package: " + packageName);
13171            }
13172            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13173                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13174                throw new SecurityException("May not access signing KeySet of other apps.");
13175            }
13176            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13177            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13178        }
13179    }
13180
13181    @Override
13182    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13183        if (packageName == null || ks == null) {
13184            return false;
13185        }
13186        synchronized(mPackages) {
13187            final PackageParser.Package pkg = mPackages.get(packageName);
13188            if (pkg == null) {
13189                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13190                throw new IllegalArgumentException("Unknown package: " + packageName);
13191            }
13192            IBinder ksh = ks.getToken();
13193            if (ksh instanceof KeySetHandle) {
13194                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13195                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13196            }
13197            return false;
13198        }
13199    }
13200
13201    @Override
13202    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13203        if (packageName == null || ks == null) {
13204            return false;
13205        }
13206        synchronized(mPackages) {
13207            final PackageParser.Package pkg = mPackages.get(packageName);
13208            if (pkg == null) {
13209                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13210                throw new IllegalArgumentException("Unknown package: " + packageName);
13211            }
13212            IBinder ksh = ks.getToken();
13213            if (ksh instanceof KeySetHandle) {
13214                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13215                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13216            }
13217            return false;
13218        }
13219    }
13220}
13221